All Things VB

Just another Visual Basic weblog

Print from MSWord to PDF, PNG, JPEG, BMP, PCX, TIF, PS, EPS, TXT, PDF, PSD, PCL or RAW, using Visual Basic 6

Posted By Nick on June 16, 2009

So you want to print output from Visual Basic to a file.  Easy…
Install PDFCreator, it’s open source and free!

The VB Code you need is below, The parameters to use are

‘+- [OutputTypes] ———————————————————+
‘ “AutosaveFormat” – Format Values:
‘ 0 = PDF 1 = PNG 2 = JPEG
‘ 3 = BMP 4 = PCX 5 = TIFF
‘ 6 = PS 7 = EPS 8 = TXT
‘ 9 = PDF/A-1b 10 = PDF/X 11 = PSD
‘ 12 = PCL 13 = RAW
‘+———————————————————————+
‘+-[sPath]————————————————————-+
Input and Output Folder Path
‘+———————————————————————+
‘+-[sDoc]————————————————————–+
Input doument name without file type, for this example a Word Document
Warning: if your output file name looks like this [file..],
PDFCreator will write output as [file.pdf] the second[.] is dropped
‘+———————————————————————+

Private Sub PrintReport( sPath As String, sDoc As String, Output As Integer)

‘PDF Creator Classes
Dim oPDFC As PDFCreator.clsPDFCreator
Dim oPDFE As PDFCreator.clsPDFCreatorError
Dim strPDFPrinter As String
Dim strPrinter As String
Dim oPrinter As Printer
Dim oArray() As String
Dim lPnt As Long
Dim lArray As Long

On Error Resume Next

Dim oWord As Word.Application
Dim oDoc As Word.Document

Set oWord = New Word.Application
Set oDoc = oWord.Documents.Add(App.Path & sDoc)

‘Find PDF Printer
strPDFPrinter = “”
For Each oPrinter In Printers
If oPrinter.DeviceName = “PDFCreator” Then
strPDFPrinter = oPrinter.DeviceName & ” on ” & oPrinter.Port
End If
Next

‘Ceate PDF Objects
Set oPDFC = CreateObject(”PDFCreator.clsPDFCreator”)

With oPDFC
.cStart “/NoProcessingAtStartup”, True
.cOption(”UseAutosave”) = 1
.cOption(”UseAutosaveDirectory”) = 1
.cOption(”AutosaveDirectory”) = App.Path & “\”
.cOption(”AutosaveFilename”) = sDoc
.cOption(”AutosaveFormat”) = Output ‘ 0 = PDF
.cClearCache
End With

‘Save Current Printer & PrintOut
oPDFC.cPrinterStop = True
With oDoc
strPrinter = .Application.ActivePrinter
.Application.ActivePrinter = strPDFPrinter
.PrintOut
End With

‘Wait until the print job has entered the print queue
Do Until oPDFC.cCountOfPrintjobs > 0
DoEvents
Loop

‘Wait until the print job has entered the print queue
oPDFC.cPrinterStop = False
Do Until oPDFC.cCountOfPrintjobs = 0
DoEvents
Loop

‘Destroy PDF Objects
Set oPDFC = Nothing

‘Reset Active Printer
oWord.Application.ActivePrinter = strPrinter

oDoc.Close False
Set oDoc = Nothing
oWord.Quit
Set oWord = Nothing

End Sub


Comments

Leave a Reply

Please note: Comment moderation is currently enabled so there will be a delay between when you post your comment and when it shows up. Patience is a virtue; there is no need to re-submit your comment.

You must be logged in to post a comment.