Site icon

Print a PDF using VBA

I'm often asked how to control print settings when using a macro to print from Outlook. In most cases you can't, because the print dialog is not exposed in the object model. You can use Windows Shell to print any document type, using the native application, assuming you have an application installed that can open and print the file type, but you can't set options, such as page numbers, using Windows Shell.

If the application supports OLE, you may be able to control some aspects of the printout. For example, if you are printing a PDF and have Adobe Acrobat installed, you can use the PrintPages function in the Acrobat object model to print selected pages and shrink to fit the page.

Function PrintPages(nFirstPage As Long, nLastPage As Long, nPSLevel As Long, bBinaryOk As Long, bShrinkToFit As Long) As Boolean

Call the function in the macro using this format:
Call AcroExchAVDoc.PrintPages(0, 1, 2, 1, 1)

The page count begins with 0, not 1, so to print the first 3 pages, you'd use 0 and 2 as the first 2 values:
Call AcroExchAVDoc.PrintPages(0, 2, 2, 1, 1)

To print only page 2, use 1 and 1 as the first 2 values:
Call AcroExchAVDoc.PrintPages(1, 1, 2, 1, 1)

To use this code in Office applications, you need to set a reference to Acrobat in the VB Editor's Tools, References dialog box.

In the sample code below, pass the FileName and optional PrintMode values to the macro using

AcrobatPrint "c:\My Documents\my-file.pdf", "All"
AcrobatPrint "c:\My Documents\my-file.pdf"

Public Sub AcrobatPrint(FileName As String, PrintMode As String)

     Dim AcroExchApp As Acrobat.CAcroApp
     Dim AcroExchAVDoc As Acrobat.CAcroAVDoc
     Dim AcroExchPDDoc As Acrobat.CAcroPDDoc
     Dim num As Integer

     Set AcroExchApp = CreateObject("AcroExch.App")
     Set AcroExchAVDoc = CreateObject("AcroExch.AVDoc")

     ' Open the [Filename] pdf file
     AcroExchAVDoc.Open FileName, ""

     'Get the PDDoc associated with the open AVDoc
     Set AcroExchPDDoc = AcroExchAVDoc.GetPDDoc

     'Get the number of pages for this pdf
     num = AcroExchPDDoc.GetNumPages - 1

     If PrintMode = "All" Then

          'Print Entire Document
           Call AcroExchAVDoc.PrintPages(0, num, 1, 1, 1)
           If num = 0 Then
               'Print one page document
                Call AcroExchAVDoc.PrintPages(0, num, 2, 1, 1)
               'Print first two pages
                Call AcroExchAVDoc.PrintPages(0, 1, 1, 1, 1)
           End If
     End If
     AcroExchAVDoc.Close (True)

End Sub

More Information

Developing Applications Using Interapplication Communication

Exit mobile version