Create a PDF from Visual Basic 6 / PDF Printer
This example will show you how to print from VB6 to a PDF document.
When the code runs it will use the VB6 printing system to create a print job. This print job is sent to the PDF Writer and converted to a PDF file. The conversion to PDF will use the settings that are saved to a runonce.ini file before the print is started.
After the print job is sent to the printer/spooler the code will wait for the runonce.ini file to disappear. This will make sure that the user cannot click the button again before the current settings are read by the PDF Printer.
- Option Explicit
- Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
- Const SETTINGS_PROGID = "Pdf7.PDFSettings"
- Const UTIL_PROGID = "Pdf7.PDFUtil"
- Private Function PrinterIndex(ByVal printerName As String) As Integer
- Dim i As Integer
- For i = 0 To Printers.Count - 1
- If LCase(Printers(i).DeviceName) Like LCase(printerName) Then
- PrinterIndex = i
- Exit Function
- End If
- Next
- PrinterIndex = -1
- End Function
- Private Sub cmdPrint_Click()
- Dim prtidx As Integer
- Dim sPrinterName As String
- Dim settings As Object
- Dim util As Object
- Set util = CreateObject(UTIL_PROGID)
- sPrinterName = util.defaultprintername
- Rem -- Configure the PDF print job
- Set settings = CreateObject(SETTINGS_PROGID)
- settings.printerName = sPrinterName
- settings.SetValue "Output", "\myfile.pdf"
- settings.SetValue "ConfirmOverwrite", "no"
- settings.SetValue "ShowSaveAS", "never"
- settings.SetValue "ShowSettings", "never"
- settings.SetValue "ShowPDF", "no"
- settings.SetValue "RememberLastFileName", "no"
- settings.SetValue "RememberLastFolderName", "no"
- settings.WriteSettings True
- Rem -- Find the index of the printer
- prtidx = PrinterIndex(sPrinterName)
- If prtidx < 0 Then Err.Raise 1000, , "No printer was found by the name of '" & sPrinterName & "'."
- Rem -- Set the current printer
- Set Printer = Printers(prtidx)
- Rem -- Print something
- Printer.FontSize = 50
- Printer.Print "Hello VB6..."
- Printer.FontSize = 20
- Printer.ForeColor = vbBlue
- Printer.Print "The time is " & Now
- Printer.EndDoc
- Rem -- Wait for runonce settings file to disappear
- Dim runonce As String
- runonce = settings.GetSettingsFilePath(True)
- While Dir(runonce, vbNormal) <> ""
- Sleep 100
- Wend
- MsgBox "myfile.pdf was saved on your desktop", vbInformation, "PDF Created"
- End Sub
Downloads
Attachment | Size |
---|---|
Example file | 2.26 KB |