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.

  1. Option Explicit
  2.  
  3. Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
  4.  
  5. Const SETTINGS_PROGID = "Pdf7.PDFSettings"
  6. Const UTIL_PROGID = "Pdf7.PDFUtil"
  7.  
  8. Private Function PrinterIndex(ByVal printerName As String) As Integer
  9.     Dim i As Integer
  10.  
  11.     For i = 0 To Printers.Count - 1
  12.         If LCase(Printers(i).DeviceName) Like LCase(printerName) Then
  13.             PrinterIndex = i
  14.             Exit Function
  15.         End If
  16.     Next
  17.     PrinterIndex = -1
  18. End Function
  19.  
  20. Private Sub cmdPrint_Click()
  21.     Dim prtidx As Integer
  22.     Dim sPrinterName As String
  23.     Dim settings As Object
  24.     Dim util As Object
  25.  
  26.     Set util = CreateObject(UTIL_PROGID)
  27.     sPrinterName = util.defaultprintername
  28.  
  29.     Rem -- Configure the PDF print job
  30.     Set settings = CreateObject(SETTINGS_PROGID)
  31.     settings.printerName = sPrinterName
  32.     settings.SetValue "Output", "\myfile.pdf"
  33.     settings.SetValue "ConfirmOverwrite", "no"
  34.     settings.SetValue "ShowSaveAS", "never"
  35.     settings.SetValue "ShowSettings", "never"
  36.     settings.SetValue "ShowPDF", "no"
  37.     settings.SetValue "RememberLastFileName", "no"
  38.     settings.SetValue "RememberLastFolderName", "no"
  39.     settings.WriteSettings True
  40.  
  41.     Rem -- Find the index of the printer
  42.     prtidx = PrinterIndex(sPrinterName)
  43.     If prtidx < 0 Then Err.Raise 1000, , "No printer was found by the name of '" & sPrinterName & "'."
  44.  
  45.     Rem -- Set the current printer
  46.     Set Printer = Printers(prtidx)
  47.  
  48.     Rem -- Print something
  49.     Printer.FontSize = 50
  50.     Printer.Print "Hello VB6..."
  51.     Printer.FontSize = 20
  52.     Printer.ForeColor = vbBlue
  53.     Printer.Print "The time is " & Now
  54.     Printer.EndDoc
  55.  
  56.     Rem -- Wait for runonce settings file to disappear
  57.     Dim runonce As String
  58.     runonce = settings.GetSettingsFilePath(True)
  59.     While Dir(runonce, vbNormal) <> ""
  60.         Sleep 100
  61.     Wend
  62.  
  63.     MsgBox "myfile.pdf was saved on your desktop", vbInformation, "PDF Created"
  64. End Sub

Downloads

Attachment Size
Example file 2.26 KB

LiveZilla Live Chat Software
Top