Friday, April 25, 2008

Drive Acrobat using VB or Microsoft Word's Visual Basic for Applications (VBA)

Adobe Acrobat's OLE interface enables you to access or manipulate PDFs from a freestanding Visual Basic script or from another application, such as Word. You can also use Acrobat's OLE interface to render a PDF inside your own program's window. The Acrobat SDK [Hack #98] comes with a number of Visual Basic examples under the InterAppCommunicationSupport directory. The SDK also includes OLE interface documentation. Look for IACOverview.pdf and IACReference.pdf. These OLE features do not work with the free Reader; you must own Acrobat.

Acrobat Distiller also has an OLE interface. It is documented in DistillerAPIReference.pdf, which comes with the full Acrobat SDK.


The following example shows how easily you can work with PDFs using Acrobat OLE. It is a Word macro that scans the currently open PDF document for readers' annotations (e.g., sticky notes). It creates a new Word document and then builds a summary of these annotation comments.

The Code
To add this macro to Word, select Tools > Macro > Macros . . . , type in the macro name SummarizeComments, and click Create. Word will open a text editor where you can enter the code. Save, and then test. You can download this code from http://www.pdfhacks.com/summarize.

VBA code for summarizing comments

Sub SummarizeComments( )

Dim app As Object

Set app = CreateObject("AcroExch.App")

If (0 < newdoc =" Documents.Add(DocumentType:=" newdocrange =" NewDoc.Range" found_notes_b =" False" avdoc =" app.GetActiveDoc" pddoc =" avdoc.GetPDDoc" num_pages =" pddoc.GetNumPages" ii =" 0" pdpage =" pddoc.AcquirePage(ii)" page_head_b =" False" num_annots =" pdpage.GetNumAnnots" jj =" 0" annot =" pdpage.GetAnnot(jj)"> "" And _

annot.GetSubtype <> "Popup") Then



If (page_head_b = False) Then ' output the page number

NewDocRange.Collapse wdCollapseEnd

NewDocRange.Text = "Page: " & (ii + 1) & vbCr

NewDocRange.Bold = True

NewDocRange.ParagraphFormat.LineUnitBefore = 1

page_head_b = True

End If



' output the annotation title and format it a little

NewDocRange.Collapse wdCollapseEnd

NewDocRange.Text = annot.GetTitle & vbCr

NewDocRange.Italic = True

NewDocRange.Font.Size = NewDocRange.Font.Size - 1

NewDocRange.ParagraphFormat.LineUnitBefore = 0.6



' output the note text and format it a little

NewDocRange.Collapse wdCollapseEnd

NewDocRange.Text = annot.GetContents & vbCr

NewDocRange.Font.Size = NewDocRange.Font.Size - 2



found_notes_b = True

End If

Next jj

End If

Next ii



If (Not found_notes_b) Then

NewDocRange.Collapse wdCollapseEnd

NewDocRange.Text = "No Notes Found in PDF" & vbCr

NewDocRange.Bold = True

End If

End If

End Sub

0 comments: