Create a PDF from Visual Basic 6 (VB6)
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 Writer.
Example Source Files
Option Explicit
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Const SETTINGS_PROGID = "biopdf.PDFSettings"
Const UTIL_PROGID = "biopdf.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 defidx 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", "yes"
settings.SetValue "RememberLastFileName", "no"
settings.SetValue "RememberLastFolderName", "no"
settings.WriteSettings True
Rem -- Save current default printer
defidx = PrinterIndex(Printer.DeviceName)
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
If optOrientation(0).Value Then
Printer.Orientation = PrinterObjectConstants.vbPRORPortrait
Else
Printer.Orientation = PrinterObjectConstants.vbPRORLandscape
End If
Rem -- Set paper size
Rem -- http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.powerpacks.printing.compatibility.vb6.printer.papersize.aspx
Rem -- Note: Custom paper size is not supported by VB6 after Windows 98.
Printer.PaperSize = vbPRPSA3
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
Rem --- Restore the default printer
Set Printer = Printers(defidx)
MsgBox "myfile.pdf was saved on your desktop", vbInformation, "PDF Created"
End Sub
|