Home > BSPrinter documentation > Save PDF files

How to create and save PDF files with BSPrinter without user interaction


What is required?


The Microsoft Print to PDF printer driver that comes with Windows 10 is required to be installed (it is installed by default).


What is the code needed to save PDF files with BSPrinter?


BSPrinter works with the Printer object, so what you want to save as PDF must be written or drawn there.

To test it, add a PrintPreview control to a form (you need BSPrinter component installed, if you don't have it download it from the download page), add a Command button and this code:

Private Sub Command1_Click()
    If PrintPreview1.PrinterExists("Microsoft Print to PDF") Then
        ' replace the file path with a path where you are allowed to write files
        PrintPreview1.SaveToFile "Microsoft Print to PDF", "C:\test.pdf"
        If PrintPreview1.Canceled Then
            MsgBox "Error, could not save the file, check if to are allowed to write at that location", vbExclamation
        End If
    Else
        MsgBox "'Microsoft Print to PDF' printer driver not installed, cannot save PDF file.", vbExclamation
    End If
End Sub

Private Sub PrintPreview1_PrepareReport(Cancel As Boolean)
    ' here you prepare the document
    Printer.FontSize = 16
    Printer.Print "Hello World!"
End Sub

You also will need to add this code in a module (or in the form). This is to replace the VB6 original printer object with a new one:

Public Property Get Printer() As Printer
    Set Printer = PrinterReplacement
End Property

Public Property Set Printer(nPrinter As Printer)
    Set PrinterReplacement = nPrinter
End Property

In the sample projects that are installed by the installer at [Program Files]\BSPrinter\Samples or [Program Files (x86)]\BSPrinter\Samples on Windows 64 bits, there are two sample projects for saving PDF file, they are:

5 - Save PDF file
23 - Save PDF from a toolbar button (under: 9 - Advanced samples 2)


Reference

SaveToFile method.
PrinterExists method.
Canceled property.