PDF Creator Developer Manual
PDF Creator Developer Manual
Developers Manual
Updated December 27, 2004
www.amyuni.com
Contents
Legal Information ...................................................................................................... 5 Acknowledgments...................................................................................................... 5 Description of the various modules............................................................................ 6 General operation ...................................................................................................... 7 New in version 1.5..................................................................................................... 8 New in version 2.0 ..................................................................................................... 8 Inserting the PDF Creator control into a project........................................................ 9 Setting the Licensing information ............................................................................ 10 PDF Creator Control Properties................................................................................ 11 PDF Creator Control Methods................................................................................... 14
SetLicenseKey Method.............................................................................................................................15 AddPage Method......................................................................................................................................16 CreateObject Method...............................................................................................................................17 DeleteObject Method ...............................................................................................................................18 DoCommandTool Method.........................................................................................................................19 UpdateCommandTool Method..................................................................................................................20 InitBlank Method.....................................................................................................................................21 InitReport Method ...................................................................................................................................22 InitTable Method .....................................................................................................................................23 InsertObject Method................................................................................................................................24 Print Method............................................................................................................................................25 Undo Method ...........................................................................................................................................26 UndoLevels Function................................................................................................................................27 Redo Method............................................................................................................................................28 RedoLevels Function................................................................................................................................29 RedrawObject Method .............................................................................................................................30 Refresh Method (PDFCreativeX class)......................................................................................................31 ScrollWindow Method..............................................................................................................................32 ReachText Function .................................................................................................................................33 ReachTextEx Function .............................................................................................................................34 Append Method........................................................................................................................................35 AppendEx Method....................................................................................................................................36 Merge Method..........................................................................................................................................37 MergeEx Method......................................................................................................................................38 RotatePage Method .................................................................................................................................39 MovePages Method..................................................................................................................................40 DeletePage Method..................................................................................................................................41 DuplicatePage Method.............................................................................................................................42 ActivateObject Method.............................................................................................................................43 ActiveTool Function .................................................................................................................................44 ClearPage Method....................................................................................................................................45 DrawCurrentPage Method........................................................................................................................46 EmbedFont Method..................................................................................................................................47 OptimizeDocument Method......................................................................................................................48 ExportToExcel method.............................................................................................................................49 ExportToHTML method ............................................................................................................................50 ExportToJPeg method..............................................................................................................................51 ExportToRTF method ...............................................................................................................................52 GetWarningLevel Method.........................................................................................................................53 LockAllObjects Method ............................................................................................................................54 OpenEx Function......................................................................................................................................55 SelectAllObjects Method..........................................................................................................................56 SetAttributeForMultipleSelection Method ................................................................................................57 RedrawRect Method.................................................................................................................................58 DataReceived Method..............................................................................................................................59 PageReceived Method..............................................................................................................................60
PrintPage Event.......................................................................................................................................65 SavePage Event.......................................................................................................................................68 Refresh Event ..........................................................................................................................................68 SelectedObjectChange Event...................................................................................................................70 ObjectTextChange Event..........................................................................................................................71
Inserting formulas in fields and tables................................................................... 105 Linking to a database............................................................................................. 106 Reading / Writing PDF files.................................................................................... 107
Open, OpenEx Methods..........................................................................................................................108 Save Method..........................................................................................................................................109 SavePage Event.....................................................................................................................................110 StartSave Method ..................................................................................................................................111 SavePage Method ..................................................................................................................................112 EndSave Method....................................................................................................................................113
Creating large PDF documents............................................................................... 114 Loading/Save PDF data from/to memory or other sources.................................... 115 Securing PDF documents........................................................................................ 116
Encrypt Method......................................................................................................................................117 Encrypt128 Method................................................................................................................................118 DigitalSignature method........................................................................................................................119 Signature object ....................................................................................................................................120
Legal Information
Information in this document is subject to change without notice and does not represent a commitment on the part of AMYUNI. The software described in this document is provided under a license agreement or nondisclosure agreement. The software may be used or copied only in accordance with the terms of the agreement. It is against the law to copy the software on any medium except as specifically allowed in the license or nondisclosure agreement. The licensee may make one copy of the software for backup purposes. No part of this manual may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or information storage and retrieval systems, for any purpose other than the licensees personal use, without express written permission of AMYUNI. Copyright 2001-2005, AMYUNI Consultants AMYUNI Technologies. All rights reserved. Amyuni and the Amyuni logo are trademarks of Amyuni Technologies Inc. Microsoft, the Microsoft logo, Microsoft Windows, Microsoft Windows NT and their logos are trademarks of Microsoft Corporation. All other trademarks are the property of their respective owners.
Acknowledgments
This software uses the deflate algorithm developed by Jean-loup Gailly ([email protected]) and Mark Adler ([email protected]). This software is also based in part on the work of the Independent JPEG Group and on parts of the FreeType library.
General operation
The Amyuni PDF Creator was designed for two main purposes: Viewing, editing and printing PDF documents Creating reports, forms and general documents directly in PDF format The ActiveX controls that are part of the PDF Creator can be integrated into most development environments to provide the final user with advanced PDF document management capabilities. The PDF Creator control can be in one of four modes: Design mode Run or Compiled mode Annotation mode Print preview mode
When a blank document is first created, the control is in design mode. The user or developer can add objects to the document, delete objects, modify object properties and do all editing operations allowed by the PDF Creator control. When an existing PDF document is opened, two things can happen: 1 The PDF document was generated by the PDF Creator and contains all design information generated by the control. In this case, the document is opened in the same state as when it was saved, i.e. either Design, Run, Annotate or PrintPreview modes. 2 The PDF document was generated by another tool such as the Amyuni PDF Converter. In this case, the document is opened immediately in Run mode. The document can only be read or printed and if the user has enough rights on the document, the user can switch the document to annotation or design mode and edit it using the PDF Creator interface. The documents created by the PDF Creator can contain fields with formulas or data coming from a database. Compiling the document instructs the PDF Creator to compute those formulas and fetch information from the database. Once compiled, the document switches to Run mode and only the fields or objects defined as Editable can be modified in Run mode. Version 2.0 of the PDF Creator added the Annotation mode as one of the PDF Creator modes of operation. In Annotation mode, the contents of the original document cannot be modified, the user can only add or modify PDF annotations such as Text, Line, Highlighter or Sticky note annotations.
The control shows in the list of insertable components as Amyuni PDFCreactiveX Component. Once inserted into the project, the component appears in the components toolbar and can be inserted on a form:
"Left") = 200 "Top") = 200 "Right") = 600 "Bottom") = 400 "Text") = "Hello There" ' save modified document
If the developer does not wish to place the control on a form, the control can be created dynamically and its properties and methods accessed in a similar manner. The ProgId associated with the control is PDFCreactiveX.PDFCreactiveX. To create the control dynamically using VB, one can use:
Dim PDF1 As New acPDFCreactiveX.PDFCreactiveX Or Dim PDF1 As Object Set PDF1 = CreateObject( "PDFCreactiveX.PDFCreactiveX" )
10
Boolean
True/False
False
>= 1
True/False
False
ReportState *Read/Write
ReportStateConstants 0 - acReportStateRun document in Run mode 1 - acReportStateDesign document in Design mode 2 - acReportStateLoading document is being loaded from file 3acReportStatePrintPreview document in PrintPreview mode 4 - acReportStateAnnotate document in Annotation mode
acReportStateRun
View AutoRefresh When set to True, the control is refreshed each time a property is modified Number of copies to print document Activate duplex printing of document Boolean True/False True
Copies Duplex
Longint Integer
1 0: Printer default
FitToParent
When set to True, the control sizes itself to fill the form where it is located Show/Hide table grids. This is valid only for table or form style documents
Boolean
True/False
False
GridView
GridViewConstants
acGridViewNone grids are hidden acGridViewBoth show horizontal and vertical grids acGridViewVertical show vertical grid acGridViewHorizontal show horizontal grid
acGridViewBoth
HorzScrollBar
Boolean
True/False
False
11
MinimumGap
Longint
>= 0
30 pixels
Modified
Indicates whether Boolean the document is modified and needs to be saved Control is in readonly mode. This is determined by the license key. Report view option Background color for rulers Height of horizontal ruler and width of vertical ruler in Pixels Scale contents to fit in window Longint
True/False
False
ReadOnly *ReadOnly
ScaleToWindow
acScaleConstants
0: acScaleNone
SelectedObject
IacObject
SelectedObjectCount ShowMargins
Number of selected Longint objects When set to True, show page margins as thin lines around the page Boolean True/False
0 False
StatusBar VerticalNaviguationBar
Hide/Display status Boolean bar Hide/Display vertical naviguation bar When set to False, hide vertical scroll bar Zoom factor at which document is viewed Data source to read external data Boolean
True/False True/False
True True
VertScrollBar
Boolean
True/False
False
ZoomFactor
Longint
140
Database DataSource DataSourceEx String Access .MDB file or an ODBC data source
Data source to IacDatabase read external data. This can be used to provide a custom data source. Main data table or view from which to fetch data When set, the document is printed to a file as opposed to a real printer Scale contents to String
DataTableOrView
ScaleToPrinter
acScaleConstants
0: acScaleNone
0: acScaleNone 12
Templates TemplateMode Set the PDF Boolean Creator in template mode Specifies whether the template document should be printed or not. Boolean True/False False
TemplatePrint
True/False
True
TemplateRepeat
Specifies whether Boolean the pages of the template document should be repeated when the number of pages is less than the main documents pages Specifies whether the template document is visible or hidden Returns a reference to the Document object Parent object container Root bookmark for access to whole bookmark tree When True, Tab keys are handled by the control Boolean
True/False
False
TemplateVisible
True/False
True
IacContainer IacBookmark
Boolean
True/False
False
13
14
SetLicenseKey Method
The SetLicenceKey method is used to set Licensing Information. Before any operation can be done on the PDF Creator control, version 1.5 requires that the control be activated using this method. (See also page 8) Syntax Sub SetLicenseKey(Company As String, LicKey As String) HRESULT SetLicenseKey(BSTR Company, BSTR LicKey);
Parameters Company Name of the company or private user having licensed the product. LicKey License key provided by Amyuni Technologies when downloading or purchasing a product. Return Value
Example Const LicenseTo = "Evaluation Version" Const ActivationCode = 07EFCDAB01000100C71720CB68064821476D5694497DB50A43E40D4A14E5D47EF7075 62F287274F4AA099D562E4F6DC6F5CF1F74904B9BFE995AC248306749C9092EA202478B0E1D72748B5D78870 EC142CC8B9A4ABF6AA49DDF7E8AB55D617055803A" Private Sub Form_Load() PDF1.SetLicenseKey LicenseTo, ActivationCode End Sub
15
AddPage Method
The AddPage method can be used to add a blank page to the document at specified position
Parameters PageIndex If PageIndex is greater than the number of pages in the document, a new page is appended at the end of the document. The inserted page becomes the currently active page and all operations such as inserting objects are applied to the new page. Return Value
Example
Private Sub cmdAddPage_Click() With PDF1 .Open "C:\temp\test.pdf", "" .ReportState = acReportStateDesign
'Insert a blank page at PageIndex 0 (the first page) .AddPage 0 .ReportState = acReportStateRun .Save "C:\temp\testPageAdded.pdf", 1 End With End Sub
16
CreateObject Method
The CreateObject method can be used to create a new object on the current page with specified type and reference.
Syntax Sub CreateObject(ObjectType As ObjectTypeConstants, Reference As String) HRESULT CreateObject(ObjectTypeConstants ObjectType, BSTR Reference);
Parameters ObjectType Object type acObjectTypeLine acObjectTypeFrame acObjectTypeText acObjectTypeField acObjectTypePicture acObjectTypePolygon acObjectTypeTable acObjectTypeExcel acObjectTypeWord acObjectTypeGraph acObjectTypeOLE acObjectTypeCheckBox acObjectTypeStickyNote acObjectTypeHighlight acObjectTypeSelection Reference Reference name of the object. Class ID 1 2 5 6 7 8 16 17 18 19 20 21 22 23 24 Description Straight line Rectangular frame Static text Editable field Picture object Polygon object Table object Microsoft Excel object Microsoft Word object Microsoft Chart object Generic OLE object CheckBox, RadioButton and PushButton objects Annotation Highlighter ComboBox, ListBox
Return Value This method launches an exception if the object cannot be created E_NOTIMPL E_ACCESSDENIED E_FAIL The license key that is provided does not enable modifying the document The document security settings do not allow the user to modify the document Failed to create the object
Remarks - Member of PDFCreactiveX - Details and samples explaining the use of this method are found in the section Dynamically creating new objects in the PDF document on page 93.
Example - See the section Dynamically creating new objects in the PDF document on page 93.
17
DeleteObject Method
The DeleteObject method can be used to delete an object referenced by the Object parameter from the PDF document. Syntax Sub DeleteObject(Object As String, CanUndo As Long) HRESULT DeleteObject(BSTR Object, BOOL CanUndo);
Parameters Object An object name to delete CanUndo This parameter should be set to True if the user is allowed to undo the delete object action, this is usually the case when this method is called from a menu or other user interface. This parameter should be set to False if the user cannot undo this action, this is more efficient and avoids the overhead related to managing the Undo list. Return Value
Example ' find and delete an object Frame 1 Private Sub cmdDeleteObject_Click() Dim obj As Variant Dim objarray As Variant PDF1.Open "c:\temp\test.pdf", "" ' get an array of all objects in Page[1] of "testFrame.pdf" objarray = PDF1.ObjectAttribute("Pages[1]", "Objects")
' find and delete object named "Frame 1" For Each obj In objarray If obj.Attribute("Name") = "Frame 1" Then PDF1.DeleteObject "Frame 1", 0 ' this fucntion enables the changes PDF1.DoCommandTool (acCommandToolRunDocument) End If Next PDF1.Save "c:\temp\deleteObject.pdf", 0 ' save the document with design & view data End Sub
18
DoCommandTool Method
Command or tool button clicked on toolbar. The PDF Creator responds to various commands sent to it through this method. Syntax Sub DoCommandTool(Id As CommandToolConstants) HRESULT DoCommandTool(CommandToolConstants Id);
Parameters Id See List of commands provided by the PDF Control on page 130.
Return Value
Example Private Sub cmdDoCommandTool_Click() With PDF1 .InitBlank ' initialize a blank page .DoCommandTool (acCommandToolDesignMode) ' put control in Design mode to insert an object .DoCommandTool (acCommandToolPageView) ' set the page to PageView display .DoCommandTool (acCommandToolTable) ' enable to insert a table object End With End Sub
19
UpdateCommandTool Method
The UpdateCommandTool method returns the status of a command or tool button. To get the status of a specific command button, we can use the UpdateCommandTool method.
Syntax Function UpdateCommandTool(Id As CommandToolConstants) As CommandToolStatusConstants HRESULT UpdateCommandTool([in]CommandToolConstants Id, [out, retval] CommandToolStatusConstants *Status);
Parameters Id See List of commands provided by the PDF Control on page 130. Return Value CommandToolStatusConstants The status of a command or tool button. This can be either Enabled, Disabled and/or Pressed. Option acCommandToolStatusDisabled acCommandToolStatusEnabled acCommandToolStatusPressed acCommandToolStatusUnknown Value 0 1 2 0
Example Private Dim Dim Dim Sub cmdUpdateCommand_Click() tableStatus As CommandToolStatusConstants pageViewStatus As CommandToolStatusConstants desModeStatus As CommandToolStatusConstants
desModeStatus = PDF1.UpdateCommandTool(acCommandToolDesignMode) pageViewStatus = PDF1.UpdateCommandTool(acCommandToolPageView) tableStatus = PDF1.UpdateCommandTool(acCommandToolTable) MsgBox desModeStatus MsgBox pageViewStatus MsgBox tableStatus End Sub
20
InitBlank Method
The InitBlank method initializes a blank document
Parameters
Return Value
Example Private Sub cmdInitBlank_Click() With PDF1 .InitBlank ' initialize a blank page
' set the page to PageView display ' .DoCommandTool (acCommandToolPageView) .Refresh End With End Sub ' refresh the display
21
InitReport Method
The InitReport method is used to initialize as a report style document.
Parameters
Return Value
Example Private Sub cmdInitReport_Click() With PDF1 .ReportState = acReportStateDesign ' initialize as a report style document .InitReport .Refresh End With End Sub
22
InitTable Method
The InitTable method initializes the document as a table of RowCount x ColCount
Syntax Sub InitTable(RowCount As Long, ColCount As Long) HRESULT InitTable(long RowCount, long ColCount);
Parameters RowCount The number of rows ColCount The number of columns Return Value
Example Private Sub cmdInitTable_Click() With PDF1 ' initializes the document as a table of 10 rows x 3 columns .InitTable 10, 3 ' set the page to PageView display .DoCommandTool (acCommandToolPageView) ' set the background color of cell(1,1) to red .ObjectAttribute("Cells[1,1]", "BackColor") = &HFF& ' draw horizontal and vertical border lines of the cell(3,2) .ObjectAttribute("Cells[3,2]", "HorzBorders") = 1 ' top only .ObjectAttribute("Cells[3,2]", "VertBorders") = 3 ' left & right .Refresh End With End Sub ' refresh the display
23
InsertObject Method
The InsertObject method can be used to start inserting an object into the document. This method should be called when a user chooses a drawing tool from the toolbar and allows the user to create an object on the document. The cursor changes depending on the selected tool.
Syntax Sub InsertObject(ObjectType As ObjectTypeConstants) HRESULT InsertObject(ObjectTypeConstants ObjectType); Parameters ObjectType Object type acObjectTypeLine acObjectTypeFrame acObjectTypeText acObjectTypeField acObjectTypePicture acObjectTypePolygon acObjectTypeTable acObjectTypeExcel acObjectTypeWord acObjectTypeGraph acObjectTypeOLE acObjectTypeCheckBox acObjectTypeStickyNote acObjectTypeHighlight acObjectTypeSelection Return Value Class ID 1 2 5 6 7 8 16 17 18 19 20 21 22 23 24 Description Straight line Rectangular frame Static text Editable field Picture object Polygon object Table object Microsoft Excel object Microsoft Word object Microsoft Chart object Generic OLE object CheckBox, RadioButton and PushButton objects Annotation Highlighter ComboBox, ListBox
Remarks Member of PDFCreactiveX This method allows the user to visually create objects, for this reason it cannot be called programmatically if the PDF Creator control is not placed on a form.
Example ' command button to draw a frame Private Sub cmdInsertObjectFrame_Click() With PDF1 .ReportState = acReportStateDesign .InsertObject acObjectTypeFrame End With End Sub
' put control in Design mode to insert an object ' let the user to draw a Frame
' command button to draw a line Private Sub cmdInsertObjectLine_Click() Dim PDF1 As New ACPDFCREACTIVEX.PDFCREACTIVEX With PDF1 .SetLicenseKey Licensee, LicenseCode ' activate the ocntrol .ReportState = acReportStateDesign ' put control in Design mode to insert an object ' This line will fail because the control is not on a Form .InsertObject acObjectTypeLine End With End Sub
24
Print Method
The Print method is used to print the document to specified printer Syntax Sub Print(PrinterName As String, Prompt As Boolean) HRESULT Print(BSTR PrinterName, BOOL Prompt);
Parameters PrinterName If no printer name is specified, the document is printed to the default printer. Prompt If this parameter is set to True, the user is prompted with the printer selection dialog box. Return Value
Example Private Sub cmdPrint_Click() With PDF1 .Open "c:\temp\test.pdf", "" .Print "Amyuni PDF Converter", False End With End Sub
For details about using this method, refer to the section 'Printing documents' on page 121 of this manual.
25
Undo Method
The Undo method is used to undo latest action
Parameters
Return Value
Example Private Sub cmdInsertObjectFrame_Click() ' a user can insert a Frame object by clicking on this button With PDF1 .ReportState = acReportStateDesign ' put control in Design mode to insert an object .InsertObject acObjectTypeFrame ' let the user to draw a Frame End With End Sub
Private Sub cmdUndo_Click() ' a command button to Undo With PDF1 If .UndoLevels > 0 Then ' Undo if UndoLevels is greater than 0 .Undo .Refresh Else MsgBox "No more action to undo" End If End With End Sub
26
UndoLevels Function
The UndoLevels function reads number of current undo levels
Parameters
Example Private Sub cmdUndo_Click() If PDF1.UndoLevels > 0 Then PDF1.Undo PDF1.Refresh End If End Sub
27
Redo Method
The Redo method is used to redo latest undone action
Parameters
Return Value
Example Private Sub cmdInsertObjectFrame_Click() ' a user can insert a Frame object by clicking on this button With PDF1 .ReportState = acReportStateDesign ' put control in Design mode to insert an object .InsertObject acObjectTypeFrame ' let the user to draw a Frame End With End Sub
Private Sub cmdRedo_Click() ' a command button to Redo With PDF1 If .RedoLevels > 0 Then ' Redo if UndoLevels is greater than 0 .Redo .Refresh Else MsgBox "No more action to redo" End If End With End Sub
28
RedoLevels Function
The RedoLevels function reads number of redo levels
Parameters
Example Private Sub cmdRedo_Click() With PDF1 If .RedoLevels > 0 Then ' Redo if UndoLevels is greater than 0 .Redo .Refresh Else MsgBox "No more action to redo" End If End With End Sub
29
RedrawObject Method
The RedrawObject method redraws the object referenced by Object. This can be called after changing the objects properties to refresh the object.
Return Value
Example Private Sub cmdRedrawObject_Click() Dim obj As Variant Dim objarray As Variant ' open "testText.pdf" containing an object named "text 1" PDF1.Open "c:\temp\testText.pdf", "" ' get an array of all objects in Page[1] of "testText.pdf" objarray = PDF1.ObjectAttribute("Pages[1]", "Objects") ' find and modify object named "Text 1" For Each obj In objarray If obj.Attribute("Name") = "Text 1" Then With PDF1 .ObjectAttribute("Text 1", "Left") = 200 .ObjectAttribute("Text 1", "Top") = 200 .ObjectAttribute("Text 1", "Right") = 2000 .ObjectAttribute("Text 1", "Bottom") = 500 ' change background color to red .ObjectAttribute("Text 1", "BackColor") = &HFF& ' change text .ObjectAttribute("Text 1", "Text") = "Text 1 Modified" ' redraw the object with modified properties .RedrawObject ("Text 1") End With End If Next End Sub
30
Parameters
Return Value
Example Private Sub cmdRefresh_Click() With PDF1 ' initializes the document as a table of 10 rows x 3 columns .InitTable 10, 3 ' set the page to PageView display .DoCommandTool (acCommandToolPageView) ' set the background color of cell(1,1) to red .ObjectAttribute("Cells[1,1]", "BackColor") = &HFF& .Refresh End With End Sub ' refresh the document
31
ScrollWindow Method
The ScrollWindow method can be used to scroll the document window by HorzScroll and VertScroll increments
Syntax Sub ScrollWindow(HorzScroll As Long, VertScroll As Long) HRESULT ScrollWindow(long HorzScroll, long VertScroll);
Parameters HorzScroll The amount to scroll horizontally in twips. VertScroll The amount to scroll vertically in twips.
Return Value
Example Private Sub Form_Load() With PDF1 .SetLicenseKey LicenseTo, ActivationCode .Open "c:\temp\test.pdf", "" ' scroll horizontally and vertically .ScrollWindow 100, 500 End With End Sub
32
ReachText Function
The ReachText function reaches a text object having specified text and font attributes This function searches the document for the first object containing the specified text and makes that object visible.
Syntax Function ReachText(Option As ReachTextOptionConstants, Text As String, FontName As String, FontSize As Integer, Bold As Long, Italic As Long) As Long HRESULT ReachText(ReachTextOptionConstants Option, BSTR Text, BSTR FontName, short FontSize, BOOL Bold, BOOL Italic, [out] BOOL *pVal);
Parameters Option Option acReachTextOptionStart acReachTextOptionCurrent acReachTextOptionStartNoCase acReachTextOptionCurrentNoCase Text Text to search for FontName If provided (not empty), the text has to be in the specified font FontSize If provided (not 0), the text has to be in the specified font size Bold If provided (not 0), the text has to be in the specified font style Italic If provided (not 0), the text has to be in the specified font style Value -1 0 1 2 Description case sensitive search from the beginning of the document case sensitive search from current position search from the beginning of the document, case-insensitive search from the current position, caseinsensitive
Return Value This function returns True if the text is found, False otherwise.
Example Private Sub cmdReachText_Click() Dim x As Boolean With PDF1 .Open "c:\temp\searchText.pdf", "" x = .ReachText(1, "hello", "", 0, 0, 0) ' Search for a string "hello" from the beginning of the document, case-insensitive. ' Font name, size and styles not specified. ' If found, return True, otherwise False. If (x) Then MsgBox "Text 'hello' found" Else MsgBox "Text 'hello' not found" End If End With End Sub
33
ReachTextEx Function
The ReachTextEx function reaches a text object having specified text and font attributes This is the same as the ReachText function except that it returns the object reference if the text is found, an empty string otherwise. Syntax Function ReachTextEx(Option As ReachTextOptionConstants, Text As String, FontName As String, FontSize As Integer, Bold As Long, Italic As Long) As String HRESULT ReachTextEx(ReachTextOptionConstants Option, BSTR Text, BSTR FontName, short FontSize, BOOL Bold, BOOL Italic, [out] BSTR *pVal); Parameters Option Option acReachTextOptionStart acReachTextOptionCurrent acReachTextOptionStartNoCase acReachTextOptionCurrentNoCase Text Text to search for FontName If provided (not empty), the text has to be in the specified font FontSize If provided (not 0), the text has to be in the specified font size Bold If provided (not 0), the text has to be in the specified font style Italic If provided (not 0), the text has to be in the specified font style Value -1 0 1 2 Description case sensitive search from the beginning of the document case sensitive search from current position search from the beginning of the document, case-insensitive search from the current position, caseinsensitive
Return Value It returns the object reference if the text is found, an empty string otherwise.
Example Private Sub cmdReachTextEx_Click() Dim objref As String With PDF1 .Open "c:\temp\testSaved.pdf", "" objref = .ReachTextEx(-1, "Hello", "", 0, 0, 0) ' Search for a string "Hello" from the beginning of the document, case-sensitive. ' Font name, size and styles not specified. ' If found, return the object reference, otherwise an empty string. If objref = "" Then MsgBox "No match found" Else MsgBox objref ' if found, display the object reference in the message box End If End With End Sub
34
Append Method
The Append method can be used to append or concatenate a PDF file to the current document
Syntax Sub Append(FileName As String, Password As String) HRESULT Append(BSTR FileName, BSTR Password);
Parameters FileName name of the file to append Password password to open the file, if set Return Value
Example Private Sub cmdAppend_Click() With PDF1 ' open file to append to .Open "c:\temp\test1.pdf", "" ' apppend the specified file to the current document .Append "c:\temp\test2.pdf", "" .Refresh .DoCommandTool (acCommandToolRunDocument) .Save "c:\temp\testAppended.pdf", 0 End With End Sub
35
AppendEx Method
The AppendEx method can be used to append or concatenate a PDF file to the current document Whenever possible, it is recommended to call the Append method rather than the AppendEx method. The Append method is usually more efficient.
Parameters Document Another PDF Creator Control that holds the file to append
Return Value
Example Private Sub cmdAppendEx_Click() ' open a document to append using another instance of PDF Creator Control PDF2.Open "c:\temp\test2.pdf", "" With PDF1 ' open file to append to .Open "c:\temp\test1.pdf", "" ' append PDF2 document to the current document .AppendEx PDF2 .Refresh .DoCommandTool (acCommandToolRunDocument) .Save "c:\temp\testAppendedEx.pdf", 0 End With End Sub
36
Merge Method
The Merge method merges the contents of the current document into a specified PDF file
Syntax Sub Merge(FileName As String, Password As String, Options As Long) HRESULT Merge(BSTR FileName, BSTR Password, long Options);
Parameters FileName Name of the file to merge to Password password to open the file, if set Options The Options parameter is a combination of the following flags: Option 1 2 Return Value Description Repeat : The contents of the current document are repeated on all pages. Above : The contents of the current document are above the document specified
Example Private Sub cmdMerge_Click() With PDF1 ' open a file to merge .Open "c:\temp\test1.pdf", "" ' merge the current document to the specified file .Merge "c:\temp\test2.pdf", "", 1 + 2 ' Repeat & Above .Refresh .DoCommandTool (acCommandToolRunDocument) .Save "c:\temp\testMerged.pdf", 0 End With End Sub
37
MergeEx Method
The MergeEx method merges the contents of the current document into a specified PDF file
Syntax Sub MergeEx(Document As PDFCreactiveX, Options As Long) HRESULT MergeEx(IPDFCreactiveX* Document, long Options));
Parameters Document Another PDF Creator Control that holds the file to merge Options The Options parameter is a combination of the following flags: Option 1 2 Description Repeat : The contents of the current document are repeated on all pages. Above : The contents of the current document are above the document specified
Return Value
Remarks - Whenever possible, it is recommended to call the Merge method rather than the MergeEx method. The Merge function is usually more efficient. - Member of PDFCreactiveX
Example Private Sub cmdMergeEx_Click() ' open a file to merge with, using another instance of PDF Creator Control PDF2.Open "c:\temp\test2.pdf", "" With PDF1 ' open a file to merge .Open "c:\temp\test1.pdf", "" ' merge the current document with PDF2 document .MergeEx PDF2, 1 ' Repeat on all pages .Refresh .DoCommandTool (acCommandToolRunDocument) .Save "c\temp\testMergedEx.pdf", 0 End With End Sub
38
RotatePage Method
The RotatePage method rotates the contents of the specified page
Syntax Sub RotatePage(PageNumber As Long, Rotation As RotatePageConstants) HRESULT RotatePage([in] long PageNumber, [in] RotatePageConstants Rotation )
Parameters Pagenumber Index of page to rotate. Rotate 90, -90 or 180 degrees.
Return Value
Remarks - Member of PDFCreactiveX - This method can be used to rotate pages that contain scanned images. It will not rotate text objects.
Example
39
MovePages Method
The MovePages moves one or more pages to another location within the document
Syntax Sub MovePages(PageNumber As Long, PageCount As Long, Destination As Long) HRESULT MovePages([in] long PageNumber, [in] long PageCount, [in] long Destination )
Parameters PageNumber Starting page PageCount Number of pages to move Destination Where to place the moved pages
Return Value
Example
40
DeletePage Method
The DeletePage method deletes the page at specified location
Syntax Sub DeletePage(PageIndex As Long, CanUndo As Long) HRESULT DeletePage(long PageIndex, BOOL CanUndo);
Parameters PageIndex PageIndex starts at 1 for the first page. CanUndo This parameter specifies whether the operation can be undone using the Undo method. An operation that can be undone usually consumes memory and is slower to execute.
Return Value
Example Private Sub cmdDeletePage_Click() Dim counter As Integer With PDF1 .Open "c:\temp\test.pdf", "" counter = .PageCount MsgBox (counter) ' the number of pages before deleted ' delete page 2 of the current document. This action is set undoable. .DeletePage 2, True counter = .PageCount MsgBox (counter) ' the number of pages after deleted .Save "c:\temp\pageDeleted.pdf", 0 End With End Sub
41
DuplicatePage Method
The DuplicatePage method duplicates the current page and add it at specified position This method creates a copy of the current page with all its contents and places the copy at the position specified by PageIndex. Syntax Sub DuplicatePage(PageIndex As Long) HRESULT DuplicatePage(long PageIndex);
Parameters PageIndex The page index to place the copy of the current page Return Value
Example Private Sub cmdDuplicatePage_Click() Dim counter As Integer With PDF1 .Open "c:\temp\test.pdf", "" .CurrentPage = 2 ' current page is at page 2 counter = .PageCount MsgBox (counter) ' the number of pages before duplication ' duplicate the current page and insert it at page index 3 .DuplicatePage 3 counter = .PageCount MsgBox (counter) ' the number of pages after duplication .Save "c:\temp\pageDuplicated.pdf", 0 End With End Sub
42
ActivateObject Method
The ActivateObject method activates an object, disactivate all objects if Object parameter is empty
Parameters Object The reference of the object to activate. If this parameter is empty, all objects will be disactivated.
Return Value
Example Private Sub cmdActivateObject_Click() With PDF1 ' create a field object .CreateObject acObjectTypeField, "Field1" ' position the field object .ObjectAttribute("Field1", "Left") = 2500 .ObjectAttribute("Field1", "Right") = 4500 .ObjectAttribute("Field1", "Top") = 1000 .ObjectAttribute("Field1", "Bottom") = 1500 ' backcolor of the field .ObjectAttribute("Field1", "BackColor") = &HC0FFC0 .Refresh ' activate the field object .ActivateObject "Field1" End With End Sub
43
ActiveTool Function
The ActiveTool function returns the tool that is currently active in the view. The tool that is active is the last tool that the user has selected from the objects toolbar.
Parameters
Return Value This function returns Class ID of the active object. Object type acObjectTypeUnknown acObjectTypeLine acObjectTypeFrame acObjectTypeRoundFrame acObjectTypeEllipse acObjectTypeText acObjectTypeField acObjectTypePicture acObjectTypePolygon acObjectTypeFreehand acObjectTypeTable acObjectTypeExcel acObjectTypeWord acObjectTypeGraph acObjectTypeOLE acObjectTypeCheckBox acObjectTypeStickyNote acObjectTypeHighlight acObjectTypeSelection acObjectTypeArrow Class ID 0 1 2 3 4 5 6 7 8 9 16 17 18 19 20 21 22 23 24 36 Description No tool selected Straight line Rectangular frame Frame with rounded corners Frame with circular border Static text Editable field Picture object Polygon object Freehand drawing Table object Microsoft Excel object Microsoft Word object Microsoft Chart object Generic OLE object CheckBox, RadioButton and PushButton objects Annotation Highlighter ComboBox, ListBox Arrow object
Remarks - Member of PDFCreactiveX - The Polygon, Freehand and Arrow tools all create objects of type acObjectTypePolygon. The specific Ids acObjectTypeFreehand and acObjectTypeArrow only specify the type of polygon while it is being created. - The Frame, RoundFrame and Ellipse tools all create objects of type acObjectTypeFrame. The specific Ids acObjectTypeRoundFrame and acObjectTypeEllipse only specify the type of frame while it is being created.
Example Private Sub cmdActiveTool_Click() With PDF1 .ReportState = acReportStateDesign ' put control in Design mode to insert an object .InsertObject acObjectTypeFrame ' enable the user to draw a Frame object MsgBox .ActiveTool ' returns ID of currently active object, which is 2 for Frame. End With End Sub
44
ClearPage Method
The ClearPage method is used to clear page contents
Return Value
Example Private Sub cmdClearPage_Click() With PDF1 .Open "c:\temp\test1.pdf", "" .ClearPage 1 ' clear the contents of the page 1. Page number starts at 1. .Refresh ' refresh the display End With End Sub
45
DrawCurrentPage Method
The DrawCurrentPage is used to draw the current page on the specified device context
Syntax Sub DrawCurrentPage(hDC As Long, PrepareDC As Long) HRESULT DrawCurrentPage(long hDC, BOOL PrepareDC)
Parameters hDC device context to draw to PrepareDC Specified whether the device context is prepared by the PDF Creator control or by the external application. Return Value
Example 1 // Device context prepared by the Creator control StartDoc( hDC, &docinfo); StartPage( hDC ); PDF.DrawCurrentPage( (long)hDC, TRUE ) EndPage( hDC ); EndDoc( hDC ); Example 2 // Device context prepared by the calling application int saveDC; int oldMap; SIZE oldWindow, oldView; saveDC = SaveDC( hDC ); // set scale and origin oldMap = SetMapMode( hDC, MM_ISOTROPIC ); // set scaling factor and drawing origin SetWindowExtEx( hDC, 2000, 2000, &oldWindow ); SetViewportExtEx( hDC, m_zoomFactor, m_zoomFactor, &oldView ); // now draw the page pdf.DrawCurrentPage( (long)hDC, FALSE ); // reset previous scaling and origin SetViewportExtEx( dc, oldView.cx, oldView.cy, NULL ); SetWindowExtEx( dc, oldWindow.cx, oldWindow.cy, NULL ); SetMapMode( dc, oldMap ); RestoreDC( dc, saveDC );
46
EmbedFont Method
The EmbedFont sets font embedding option for specific fonts
Syntax Sub EmbedFont(Font As String, Option As acEmbedFontOptions) HRESULT EmbedFont(BSTR Font, acEmbedFontOptions Option);
Parameters Font Base font. Option Option acEmbedFontOptionDefault acEmbedFontOptionNoEmbed acEmbedFontOptionPartial acEmbedFontOptionFull Value -1 0 1 2 Description Default font embedding (&HFFFFFFFF) No font embedding Partial font embedding. Full font embedding
Return Value
Example Private Sub cmdEmbedFonts_Click() With PDF1 .Open "c:\temp\searchText.pdf", "" .Refresh .EmbedFont "Arial", 2 ' full font embedding, Arial .Save "c:\temp\embed.pdf", 1 End With End Sub
47
OptimizeDocument Method
The OptimizeDocument method is used to optimize the document before editing or exporting to other formats. The text inside a PDF file is usually split into multiple parts, a single sentence or paragraph can consist of multiple pieces of text positioned independently inside the PDF document. This method attempts to regroup lines or paragraphs prior to exporting the PDF file into another format, or to make the file easier to edit. See also ExportToExcel, ExportToHTML, ExportToJPeg, ExportToRTF methods.
Parameters Level Optimization Level No optimization Line optimization Paragraph optimization Table optimization Value 0 1 2 3 Description Recommended when exporting to Jpeg format. Recommended when exporting to RTF format. Recommended when exporting to HTML format. Recommended when exporting to Excel format.
Return Value
Example Private Sub cmdExportHtml_Click() With PDF1 .Open "c:\temp\test.pdf", "" ' optimize document before exporting .OptimizeDocument 2 ' recommended optimization level : paragraph optimization ' export the PDF file to HTML format using layers .ExportToHTML "c:\temp\exportHtml.html", 1 End With End Sub
48
ExportToExcel method
The ExportToExcel method is used to export a PDF document to Excel format. It is recommended to use this method together with OptimizeDocument method (See also OptimizaDocument method) .
Syntax Sub ExportToExcel(FileName As String, Option As acExcelExportOptions) HRESULT ExportToExcel(BSTR FileName, acExcelExportOptions Option);
Parameters FileName name of the file with .xls extension to export to. Option Option acExcelExportOptionSingleSheet acExcelExportOptionMultipleSheets acExcelExportDecimalSeparator_Comma Value 0 1 2 Description All pages in one sheet One sheet per page Replace Period used for the decimal separator with Comma, and vice versa.
Return Value
Example Private Sub cmdExportExcel_Click() With PDF1 .Open "c:\temp\testTextOnly.pdf", "" ' optimize document before exporting .OptimizeDocument 3 ' optimization level : table optimization ' export the PDF file to Excel format, one sheet per page ' + use comma instead of period for the decimal separator .ExportToExcel "c:\temp\exportExcel.xls", 1 + 2 End With End Sub
49
ExportToHTML method
The ExportToHTML method is used to export a PDF document to HTML format. It is recommended to use this method together with OptimizeDocument method (See also OptimizaDocument method) .
Syntax Sub ExportToHTML(FileName As String, Option As acHtmlExportOptions) HREULT ExportToHTML(BSTR FileName, acHtmlExportOptions Option);
Parameters FileName name of the file with .html extension to export to. Option Option acHtmlExportOptionLayers acHtmlExportOptionSinglePage acHtmlExportOptionMultiplePages Value 1 2 3 Description Multiple pages in a single HTML file using layers All pages in a single HTML file Each page in a separate HTML file
Return Value
Example Private Sub cmdExportHtml_Click() With PDF1 .Open "c:\temp\test.pdf", "" ' optimize document before exporting .OptimizeDocument 2 ' recommended optimization level : paragraph optimization ' export the PDF file to HTML format using layers .ExportToHTML "c:\temp\exportHtml.html", 1 End With End Sub
50
ExportToJPeg method
The ExportToJPeg method is used to export a PDF document to multiple JPEG files It is recommended to use this method together with OptimizeDocument method method) . (See also OptimizreDocument
Syntax Sub ExportToJPeg(FileName As String, Resolution As Long, JPegLevel As Long) HRESULT ExportToJPeg(BSTR FileName, long Resolution, long JPegLevel);
Parameters FileName name of the file with .jpg extension to export to. Resolution 72, 150, 300, 600 JPegLevel from 1 (highest) to 9 (lowest) in the low order word Return Value
Example Private Sub cmdExportJpeg_Click() With PDF1 .Open "c:\temp\test.pdf", "" ' optimize document before exporting .OptimizeDocument 0 ' recommended optimization level : no optimization ' export the PDF file to JPEG format with the resoluction=300 and compression level=9. .ExportToJPeg "c:\temp\exportJpeg.jpg", 300, 9 End With End Sub
51
ExportToRTF method
The ExportToRTF method is used to export a PDF document to RTF format. It is recommended to use this method together with OptimizeDocument method (See alsoOptimizaDocument method) .
Syntax Sub ExportToRTF(FileName As String, Option As acRtfExportOptions, UseTabs As Long) HRESULT ExportToRTF(BSTR FileName, acRtfExportOptions Option, BOOL UseTabs);
Parameters FileName name of the file with .rtf extension to export to. Options Option acRtfExportOptionAdvancedRTF acRtfExportOptionFullRTF acRtfExportOptionRTFText acRtfExportOptionText Value 0 1 2 3 Description Advanced RTF: using frames to position objects Full RTF: Text, Graphics and images with no frames Formatted Text only Simple text, non-formatted
UseTabs Set this parameter True to enable tabs in the document, False (or 0) to replace tabs with spaces (Effective only for non-formatted simple text).
Return Value
Example Private Sub cmdExportRTF_Click() With PDF1 .Open "c:\temp\test.pdf", "" ' optimize the document before exporting .OptimizeDocument 1 ' recommended optimization level : Line optimization ' export the PDF file to simple text, non-formatted RTF with tabs enabled. .ExportToRTF "c:\temp\exportRTF.rtf", 3, True End With End Sub
52
GetWarningLevel Method
The GetWarningLevel method is used to read any warnings generated when opening a document. The warnings are related to features not supported by the PDF Creator.
Parameters
Return Values // flag indicates a severe condition that should not be ignored PDF_WRN_SEVERE PDF_WRN_LZW PDF_WRN_CANNOT_EXTRACT_FONT PDF_WRN_CANNOT_EXTRACT_IMAGE PDF_WRN_UNSUPPORTED_COLORSPACE 0x80000000L 0x00000001L 0x00000002L 0x00000004L 0x00000008L // PDF document contains LZW compression (Obsolete in version 2) // PDF document contains a font that was not extracted properly // PDF document contains an image that was not extracted properly // Unsupported colorspace, will result in some color distortion // Document contains a digital signature that the PDF Creator could not recognize PDF_WRN_SIGNATURE_NOT_RECOGNIZED0x00000010L // Document contains a digital signature that the PDF Creator could not validate PDF_WRN_SIGNATURE_NOT_VALID 0x00000020L
Example
53
LockAllObjects Method
The LockAllObjects method is used to lock/unlock all objects on current page
Parameters Lock Set this parameter True (or 1) to lock, False (or 0) to unlock. Return Value
Example ' create objects and lock. Private Sub cmdLockAllObjects_Click() With PDF1 .ReportState = acReportStateDesign ' put control in Design mode to insert an object ' create a text object .CreateObject acObjectTypeText, "Text1" .ObjectAttribute("Text1", "Left") = 200 .ObjectAttribute("Text1", "Top") = 200 .ObjectAttribute("Text1", "Right") = 1200 .ObjectAttribute("Text1", "Bottom") = 500 .ObjectAttribute("Text1", "BackColor") = "7FFFFF" ' background color = yellow .ObjectAttribute("Text1", "Text") = "Hello there" ' text to display ' create a rectangular frame .CreateObject acObjectTypeFrame, "Frame1" .ObjectAttribute("Frame1", "Left") = 2500 .ObjectAttribute("Frame1", "Right") = 4500 .ObjectAttribute("Frame1", "Top") = 1000 .ObjectAttribute("Frame1", "Bottom") = 2400 .ObjectAttribute("Frame1", "Text") = "Hello world " 'text to display .Refresh .LockAllObjects True ' refresh the display 'lock all objects in the current page
.Save "c:\temp\testLocked.pdf", 0 ' save with Design & View mode End With End Sub ' open the saved document with another instance of PDFCreativeX control Private Sub cmdUnlockAllObjects_Click() With PDF2 .Open "c:\temp\testLocked.pdf", "" .LockAllObjects False ' unlock all objects in the current page End With End Sub
54
OpenEx Function
The OpenEx function opens PDF document from file Page by page. This method is faster than the Open method if you are opening a large document because it displays the contents as it opens page by page at the same time.
Syntax Function OpenEx(FileName As String, Password As String) As Long HRESULT OpenEx(BSTR FileName, BSTR Password, [out, retval] BOOL *Result);
Parameters FileName name of the PDF file to open Password password to use if document is protected
Remarks - Member of PDFCreactiveX - To check if a document is protected and ask the user for the password, you can use the following sequence of calls Example success = PDF1.Open("c:\temp\test.pdf", "") MsgBox success ' if the document is protected If success = False And PDF1.Protected Then ' ask for password and open the document with it success = PDF1.Open("c:\temp\test.pdf", password) MsgBox success End If
55
SelectAllObjects Method
The SelectAllObjects method selects/unselects all objects on current page
Parameters val Set this parameter True to select all objects or False to deselect all the objects. Return Value
Example ' to select all objects in the current page Private Sub cmdSelectAllObjects_Click() With PDF1 .ReportState = acReportStateDesign .SelectAllObjects True .Refresh End With End Sub ' to deselect all objects in the current page Private Sub cmdDeselectAllObjects_Click() With PDF1 .ReportState = acReportStateDesign .SelectAllObjects False .Refresh End With End Sub
' put control in Design mode ' select all objects in the current page
' put control in Design mode ' deselect all objects in the current page
56
SetAttributeForMultipleSelection Method
The SetAttributeForMultipleSelection method is used to set specified attribute for all selected objects
Syntax Sub SetAttributeForMultipleSelection(attribName As String, attribVal) HRESULT SetAttributeForMultipleSelection(BSTR attribName, Variant attribVal);
Parameters attribName Name of the attribute attribVal Value of the specified attribute to set for those selected objects. Return Value
Example Private Sub cmdSetAttributeForMultipleSelection_Click() With PDF1 .Open "c:\temp\test.pdf", "" ' open a document that contains some objects. .ReportState = acReportStateDesign ' put control in Design mode .SelectAllObjects True ' select all objects in the current page ' set all the objects' size and position all the same. .SetAttributeForMultipleSelection "Left", 0 .SetAttributeForMultipleSelection "Right", 1000 .SetAttributeForMultipleSelection "Top", 0 .SetAttributeForMultipleSelection "Bottom", 1000 .Refresh End With End Sub
57
RedrawRect Method
The RedrawRect method refreshes the contents of a rectangular area on the document.
Syntax Sub RedrawRect(left As Long, top As Long, right As Long, bottom As Long) HRESULT RedrawRect(long left, long top, long right, long bottom);
Parameters
Return Value
Example
58
DataReceived Method
This method is used in page by page loading of PDF files.
Parameters data Chunk of PDF data to be processed length length of data in bytes
Return Value
Example
59
PageReceived Method
This method is used in page by page loading of PDF files.
Parameters
Return Value
Example
60
61
ActivateObject Event
The ActivateObject event is fired before an object is activated.
Syntax Event ActivateObject(pObject As Object, Continue As Long) void ActivateObject(IacObject *pObject, long *Continue);
Parameters Continue Setting this parameter to False (-1 or 0) prevents an object from being activated Return Value
Remarks - Member of PDFCreactiveX - This event is fired when the user double-clicks on an object, moves the cursor to that object or right-clicks and selects Activate object. The calling application can prevent the object from being activated by processing this event.
Example Private Sub PDF1_ActivateObject(ByVal pObject As Object, Continue As Long) ' Make sure the user is not allowed to enter any text in a Frame object If pObject.Attribute("ObjectType") = acObjectTypeFrame Then MsgBox "Text not allowed" Continue = False End If End Sub
62
BeforeDelete Event
The BeforeDelete event is fired before deleting an object.
Parameters Continue Setting this parameter to False prevents an object from being deleted. Return Value
Remarks - Member of PDFCreactiveX - This event is fired when the user tries to delete one or more objects. The calling application can request confirmation that the object is to be deleted and prevent the user from doing so. - To know which object or objects are being deleted, the application can call the SelectedObjectCount and SelectedObject properties of the PDF Creator control.
Example Private Sub PDF1_BeforeDelete(Continue As Long) If MsgBox("Are you sure you want to delete selected objects ?", vbYesNo) = vbNo Then Continue = False Exit Sub End If ' Loop through the list of selected objects and make sure only text objects are deleted For Each Obj in PDF1.ObjectAttribute( "Pages[" & PDF1.CurrentPage & "]", "Objects" ) If Obj.Attribute( "ObjectType" ) = acObjectTypeText Then Obj.Selected = False ' de-select the object so that it does not get deleted End If Next End Sub
63
ClickHyperlink Event
The ClickHyperlink event is fired when an object containing a hyperlink has been clicked. ClickHyperLink event, the hyperlink action can be customized by the calling application. Syntax Event ClickHyperlink(Object As String, Hyperlink As String, Continue As Long) void ClickHyperlink(BSTR Object, BSTR Hyperlink, long * Continue); Parameters Object the reference of the object being clicked Hyperlink This contains the value for the hyperlink property Continue This parameter should be set to 0 if the calling application handles the hyperlink action, otherwise set to 1 to let the PDF Control do the default action Remarks - The following object types can be associated with a hyperlink: The frame object (acObjectTypeFrame) All OLE objects (acObjectTypeOLE, acObjectTypeExcel, ) The picture object (acObjectTypePicture) The static text object (acObjectTypeText) Each of these object classes provide the property HyperLink of type String. This attribute can be set to one of two formats: External hyperlinks such as http://www.amyuni.com, ftp://ftp.amyuni.com, When the document is saved to file, or compiled into execute mode, the default web browser will be launched when the object is clicked. Clicking on this text object when switching the document to run mode or opening it with other PDF viewers will open the default web browser. Internal hyperlinks When the hyperlink property starts with the # character, it denotes a link to another location inside the same document. The string after the # sign should be a reference to another object (either a page or any other object) inside the same document. By intercepting the
- Member of PDFCreactiveX
Example Private Sub PDF1_ClickHyperlink(ByVal Object As String, ByVal Hyperlink As String, Continue As Long) ' The '$' can be any character that denotes a special hyperlink If Left$(Hyperlink, 1) = "$" Then Continue = 0 ' do your own hyperlink action MsgBox "You clicked the " & Object & " button" End If End Sub
64
ContextSensitiveMenu Event
The ContextSensitiveMenu event is fired when the document is either in Annotate or Design mode and the user right-clicks on an object.
Parameters Continue Setting this parameter to False (-1 or 0) prevents the menu from opening. Return Value
Remarks - Member of PDFCreactiveX - This event is not fired when the document is in Run or PrintPreview modes.
Example Private Sub PDF1_ContextSensitiveMenu(Continue As Long) Continue = False ' Force the right-click to immediately open the properties dialog-box PDF1.DoCommandTool acCommandToolProperties End Sub
65
LoadPage Event
The event LoadPage is fired when opening a document and before each page is loaded. This allows the calling application to: Display the loading progress Cancel loading on error, user action, Load only a specified range of pages Syntax Event LoadPage(PageNumber As Long, Continue As Long) void LoadPage(long PageNumber, long * Continue);
Parameters PageNumber PageNumber is the one based index of the page that is being loaded Continue Set this parameter to 0 to skip the page, 1 to load the page, -1 to cancel loading the document Return Value
Remarks Member of PDFCreactiveX This method is more useful when the document is opened using the Open method as opposed to the OpenEx method. This is because the Open method loads the whole document and takes longer to finish.
Example Private Sub PDF1_LoadPage(ByVal PageNumber As Long, Continue As Long) ' We need to keep track of the total number of pages because PageNumber is not ' incremented when a page is skipped If PageNumber = 1 Then TotalPages = 1 Else TotalPages = TotalPages + 1 End If If TotalPages Mod 2 = 0 Then Continue = 0 ' Load only one in two pages Exit Sub End If If PageNumber > 50 Then Continue = -1 Exit Sub ' Load only 50 pages End If End Sub
66
PrintPage Event
The event PrintPage is fired before each page is printed, this allows the calling application to: Display the printing progress Cancel printing on error, user action, Print only a specified range of pages Change the printers input bin or duplex mode
Syntax Event PrintPage(PageNumber As Long, Continue As Long) void PrintPage(long PageNumber, long * Continue);
Parameters PageNumber PageNumber is the one based index of the page to be printed Continue Set this parameter to 0 to skip, 1 to print, -1 to cancel Return Value
Example Private Sub PDF1_PrintPage(ByVal PageNumber As Long, Continue As Long) ' print range of pages specified by user in StartPage and EndPage parameters If PageNumber < StartPage Then Continue = 0 ' skip all pages before StartPage ElseIf PageNumber > EndPage Then Continue = -1 ' stop printing after EndPage End If End Sub
67
Refresh Event
The Refresh event is fired whenever the contents of the document change and the status bar needs to be updated.
Parameters
Return Value
Example Private Sub cmdOpen_Click() PDF1.Open "c:\temp\test.pdf", "" PDF1.ReportState = acReportStateDesign End Sub
Private Sub PDF1_Refresh() ' Refresh event fired when the document is opened MsgBox "Refreshed!" End Sub
68
SavePage Event
The SavePage event is fired for each page being saved. The application can filter the pages to be saved by intercepting the SavePage event
Syntax Event SavePage(PageNumber As Long, Continue As Long) void SavePage(long PageNumber, long * Continue);
Parameters PageNumber page number of the document to save Continue Set this parameter to 0 to skip, 1 to save, -1 to cancel
Return Value
Remarks - Member of PDFCreactiveX - Section Reading / Writing PDF files on page 127 describes the use of this event to save only selected pages. Example Private Sub PDF1_SavePage(ByVal PageNumber As Long, Continue As Long) ' save range of pages specified by user in StartPage and EndPage parameters If PageNumber < StartPage Then Continue = 0 ' skip all pages before StartPage ElseIf PageNumber > EndPage Then Continue = -1 ' stop saving after EndPage End If End Sub
69
SelectedObjectChange Event
The SelectedObjectChange event is fired whenever the user selects another object on the current page.
Parameters
Return Value
Example Private Sub PDF1_SelectedObjectChange() Dim obj As Variant Dim arrObj As Variant ' get all objects in Page[1] and store them in an array arrObj = PDF1.ObjectAttribute("Pages[1]", "Objects") For Each obj In arrObj ' find an object selected and display the name of the object. If obj.Selected Then MsgBox obj.Name & " is selected." End If Next End Sub
70
ObjectTextChange Event
The ObjectTextChange event is fired whenever the text inside an object has changed.
Example Private Sub cmdInsertText_Click() With PDF1 .ReportState = acReportStateDesign .InsertObject acObjectTypeText End With End Sub
' put control in Design mode to insert an object ' let the user to draw a text object
Private Sub PDF1_ObjectTextChange(ByVal pObject As Object) ' flgChanged is set to False when the form is loaded. ' if the text of the object is changed, set to True flgChanged = True End Sub
Private Sub cmdExit_Click() Dim choice As Integer choice = MsgBox("Text has been changed. Save chages to the text?", vbYesNoCancel) ' if the text of the object has been changed, ask whether to save the document or not If flgChanged = True Then If choice = vbYes Then PDF1.Save "c:\temp\testSaved.pdf", 0 'Save the modified document with View & Design data flgChanged = False ElseIf choice = vbCancel Then Exit Sub Else flgChanged = False End If End If Unload Form1 End Sub
71
72
ObjectAttribute Property
The ObjectAttricute property reads/writes the attributes or properties of an object.
Syntax Property ObjectAttribute(Object As String, Attribute As String) HRESULT ObjectAttribute(BSTR Object, BSTR Attribute, [out, retval] VARIANT *pVal); HRESULT ObjectAttribute(BSTR Object, BSTR Attribute, [in] VARIANT newVal);
Parameters Object The reference of the object which attribute needs to be read or modified. Attribute The name of the property that needs to be read or written. Return Value
Example ' creating an object and modifying its attributes: Private Sub Command1_Click() With PDF1 ' create a rectangular frame .CreateObject acObjectTypeFrame, "Frame 1" ' position the object .ObjectAttribute("Frame .ObjectAttribute("Frame .ObjectAttribute("Frame .ObjectAttribute("Frame
' refresh the object when all its properties have been defined .RedrawObject "Frame 1" End With End Sub
73
ObjectAttributeStr Method
This method has been added as an alternative to ObjectAttribute for compatibility with languages that do not support the use of Variants, such as Visual FoxPro. Syntax Sub ObjectAttributeStr(Object As String, Attribute As String, newVal As String) HRESULT ObjectAttributeStr(BSTR Object, BSTR Attribute, [out, retval] BSTR *pVal); HRESULT ObjectAttributeStr(BSTR Object, BSTR Attribute, [in] BSTR newVal);
Parameters Object reference name of the object which attribute needs to be read or modified. Attribute name of the property that needs to be read or written. newVal value for the Attribute parameter. Return Value
74
75
Attribute Property
The Attribute property gets/sets attribute value for an object.
Syntax Property Attribute(Attribute As String) HRESULT Attribute([in] BSTR Attribute, [out, retval] VARIANT *pVal);
Parameters Attribute For the lists of object attributes, please refer to Object Attiributes (page 73 83)
Example Private Sub cmdSetAttribute_Click() With PDF1 'Create a Picture Object and name it as "Pic1" .CreateObject acObjectTypePicture, "Pic1" With .GetObjectByName("Pic1") .Attribute("FileName") = "c:\temp\picForTest.jpg" ' a file to disply in the picture box .Attribute("Left") = 1000 ' left positon of Pic1 in twips .Attribute("Top") = 1000 ' top position of Pic1 in twips .Attribute("Right") = PDF1.PageWidth 'right pisition of Pic1 = right end of the page .Attribute("Bottom") = PDF1.PageLength 'bottom position of Pic1 = bottom end of the page End With .Refresh .Save "c:\temp\attributesSet.pdf", 0 End With End Sub
76
Coordinates Method
The Coordinates method retrieves the coordinates of the object
Syntax Sub Coordinates(left As Long, top As Long, right As Long, bottom As Long) HRESULT Coordinates([out] int *left, [out] int *top, [out] int *right, [out] int *bottom);
Parameters left left position of the object in twips top top position of the object in twips right right position of the object in twips bottom bottom position of the object in twips Return Value
Example Private Sub cmdUseCordinates_Click() Dim left As Long Dim top As Long Dim right As Long Dim bottom As Long With PDF1 'Create a Frame Object and name it as "Frame1" .CreateObject acObjectTypeFrame, "Frame1" With .GetObjectByName("Frame1") .Attribute("Left") = 0 ' left positon in twips .Attribute("Top") = 0 ' top position in twips .Attribute("Right") = 2000 ' right position in twips .Attribute("Bottom") = 1000 ' bottom position in twips ' retrieve the coordinates' values .Coordinates left, top, right, bottom .Refresh End With MsgBox "Coordinates of Frame1 = " & left & ", " & top & ", " & right & ", " & bottom & " in twips." End With End Sub
77
Name Property
The Name property returns the name (reference) of the object
Example Private Sub cmdNameProperty_Click() Dim objname As String Dim counter As Integer Dim obj As Variant Dim objarray As Variant counter = 1 With PDF1 ' create 2 texts objects with different names .CreateObject acObjectTypeText, "Text1" .ObjectAttribute("Text1", "Text") = "Hello" .ObjectAttribute("Text1", "Left") = 200 .ObjectAttribute("Text1", "Top") = 200 .ObjectAttribute("Text1", "Right") = 2000 .ObjectAttribute("Text1", "Bottom") = 500 .CreateObject acObjectTypeText, "Text2" .ObjectAttribute("Text2", "Text") = "Bonjour" .ObjectAttribute("Text2", "Left") = 500 .ObjectAttribute("Text2", "Top") = 500 .ObjectAttribute("Text2", "Right") = 2300 .ObjectAttribute("Text2", "Bottom") = 800 .Refresh ' get an array of all objects in Page[1] of current document objarray = .ObjectAttribute("Pages[1]", "Objects") ' find and display the name of each object For Each obj In objarray objname = obj.name ' get the object name MsgBox "Name of the object " & counter & " is " & objname counter = counter + 1 Next End With End Sub
78
Selected Property
The Selected property is used to get an object selected
Syntax Property Selected As Long HRESULT Selected([in] BOOL newVal); HRESULT Selected([out, retval] BOOL *pVal);
Parameters
Return Value
Example ' create a Picture object over a Text object Private Sub cmdCreatePicOverText_Click() With PDF1 ' Create a Text object .CreateObject acObjectTypeText, "Text 1" .ObjectAttribute("Text 1", "Left") = 200 .ObjectAttribute("Text 1", "Top") = 200 .ObjectAttribute("Text 1", "Right") = 1200 .ObjectAttribute("Text 1", "Bottom") = 500 .ObjectAttribute("Text 1", "BackColor") = "7FFFFF" ' background color = yello .ObjectAttribute("Text 1", "Text") = "Hello There" ' text to display ' Create and position a Picture object over the text object .CreateObject acObjectTypePicture, "Pic 1" .ObjectAttribute("Pic 1", "FileName") = "c:\temp\picForTest.jpg" .ObjectAttribute("Pic 1", "Left") = 200 .ObjectAttribute("Pic 1", "Top") = 200 .ObjectAttribute("Pic 1", "Right") = 3000 .ObjectAttribute("Pic 1", "Bottom") = 5000 .Refresh End With ' call the function to bring the Text foreground bringTextOverPic End Sub
' function to bring a Text object over a Picture object Private Sub bringTextOverPic() Dim obj As Variant Dim objarray As Variant ' get all objects in Page[1] and store them in an array objarray = PDF1.ObjectAttribute("Pages[1]", "Objects") For Each obj In objarray ' find an object with type number 5(=Text object), select and bring it foreground If obj.Attribute("ObjectType") = 5 Then obj.Selected = True ' the object is selected PDF1.DoCommandTool (acCommandToolBringForward) ' command tool to bring forward End If Next End Sub 79
ScrollIntoView Property
The ScrollIntoView property is used to scroll the object into view.
Return Value
Example Private Sub cmdScrollIntoView_Click() Dim obj As acObject With PDF1 'Create a Text object .CreateObject acObjectTypeText, "Text1" .ObjectAttribute("Text1", "Text") = "Hello" .ObjectAttribute("Text1", "Left") = 800 .ObjectAttribute("Text1", "Top") = 5000 .ObjectAttribute("Text1", "Right") = 1500 .ObjectAttribute("Text1", "Bottom") = 6000 ' fetch the text object Set obj = .GetObjectByName("Text1") ' scroll down the page so that "Text1" is in view. obj.ScrollIntoView .Refresh End With End Sub
80
Parameters
Return Value
Example Private Sub cmdRefreshObj_Click() Dim obj As acObject With PDF1 'Create a Picture Object and name it as "Pic1" .CreateObject acObjectTypePicture, "Pic1" Set obj = .GetObjectByName("Pic1") With obj .Attribute("FileName") = "c:\temp\picForTest.jpg" ' image file to disply in the picture box .Attribute("Left") = 1000 ' left positon of Pic1 in twips .Attribute("Top") = 1000 ' top position of Pic1 in twips .Attribute("Right") = PDF1.PageWidth 'right pisition of Pic1 = right end of the page .Attribute("Bottom") = PDF1.PageLength 'bottom position of Pic1 = bottom end of the page ' refresh the object .Refresh End With End With End Sub
81
Evaluate Method
The Evaluate method evaluates any formula contained in the objects text property. Syntax Sub Evaluate(AttributeName As String) HRESULT Evaluate(BSTR AttributeName);
Parameters AttributeName The name of the property that needs to be evaluated Return Value
Example Private Sub cmdEvaluate_Click() With PDF1 ' create a text object named "acText1" .CreateObject acObjectTypeText, "acText1" .ObjectAttribute("acText1", "Left") = 0 .ObjectAttribute("acText1", "Top") = 0 .ObjectAttribute("acText1", "Right") = 3000 .ObjectAttribute("acText1", "Bottom") = 1000 .ObjectAttribute("acText1", "Text") = "Hello world." .ObjectAttribute("acText1", "BackColor") = &HFFFF00 .Refresh With .GetObjectByName("acText1") 'If .Attribute("Left") = 0 Then If .Evaluate("Left") > 1000 Then ' read and evaluate the value of Left attribute MsgBox "Value of 'Left' attribute of acText1 object is > 1000" Else MsgBox "Value of 'Left' attribute of acText1 object is <= 1000" End If End With End With End Sub
82
83
GetObjectByName Function
The GetObjectByName function returns the object with specified name
Syntax Function GetObjectByName(Name As String) As acObject HRESULT GetObjectByName([in] BSTR name, [out, retval] IacObject **Object)
Parameters Name name of the object to get Return Value This function returns the object specified by Name parameter.
Example Priavate Sub cmdGetObjByName_Click() With PDF1 ' create a text object named "acText1" .CreateObject acObjectTypeText, "acText1" With .GetObjectByName("acText1") ' get the text object by name .Attribute("Left") = 0 .Attribute("Top") = 0 .Attribute("Right") = 3000 .Attribute("Bottom") = 1000 .Attribute("Text") = "Hello world." .Attribute("BackColor") = &HFFFF00 End With .Refresh End With End Sub
84
GetObjectXY Function
GetObjectXY function returns a pointer to the object located at (X,Y) on the current page. Syntax Function GetObjectXY(X As Long, Y As Long) As acObject HRESULT GetObjectXY(long X, long Y, IacObject** Object);
Parameters X X position in twips Y Y position in twips Return Value This function returns a pointer to the object located at the specified position.
Example Private Sub cmdGetObjectXY_Click() Dim obj As acObject With PDF1 ' create a Frame object .CreateObject acObjectTypeFrame, "Frame 1" .ObjectAttribute("Frame 1", "Left") = 200 .ObjectAttribute("Frame 1", "Top") = 200 .ObjectAttribute("Frame 1", "Right") = 1000 .ObjectAttribute("Frame 1", "Bottom") = 1000 .Refresh Set obj = .GetObjectXY(200, 200) ' get the object located at (200, 200) MsgBox obj.Name ' display the name of the object Frame 1 End With End Sub
85
Reserved identifiers
Document can be used to access the main documents properties. Pages[PageNumber] can be used to access the properties of a specific page Cells[Row,Col] can be used to access a specific cell if the document is of the table or form type
86
Document Attributes
The reserved Document identifier can be used to access the main documents attributes. Some of these attributes such as PageCount and CurrentPage can also be accessed directly from the ActiveX control properties. Reading/Writing these properties from either the ActiveX control or through the Document object will produce the same results. Attribute General ActivateObjects Determines if an Boolean object created by the user is activated after being created When set to True, this property forces all objects to be clipped within the pages boundaries Current page number Default font used for all objects containing text Default font used for cell titles Boolean True/False True Description Type Values Default Value
ClipToBoundaries
True/False
True
CurrentPage DefaultFont
Longint String
DefaultTitleFont EditBackColor
String
Back color for Color editable cells and fields in compiled or run mode Part of the PDF document to save to file Integer
FileSaveOption
0 acFileSaveAll save document design data and view 1 acFileSaveView save only document view (PDF format) 2 acFileSaveDesign save only document design data
0 acFileSaveAll
Array of all fonts used in document Show or hide annotations depending on the documents state
Array Integer Combination of : 1: Hide in Run mode 2: Hide in Design mode 8: Hide in PrintPreview mode 16: Hide in Annotation mode 255: Always hide 0: Never hide
IgnoreTransparencies Improve display speed and print quality of certain documents containing transparent images MinimumGap Minimum gap in pixels to be displayed between page view and borders Unit of measurement used for the ruler bars and status bar When a tool is used to add objects to
Boolean
True/False
False
Longint
>= 0
30 pixels
MeasurementUnit
Integer
0: Millimeters
LockLastSelectedTool
Boolean
True/False
True
87
the document, the same tool remains selected until the user right-clicks on the document PageCount *ReadOnly Pages *ReadOnly ReportState *ReadOnly Number of pages in document Longint >= 1 1
Array of all pages in Array document Current state for document or report ReportStateConstants 0 - acReportStateRun document in Run mode 1 - acReportStateDesign document in Design mode 2 - acReportStateLoading document is being loaded from file 3acReportStatePrintPreview document in PrintPreview mode 4acReportStateAnnotate document in Annotation mode acReportStateRun
Rotate This property takes effect only when the document is saved and reopened ScaleToWindow
Paper rotation
Integer
0: No rotation
acScaleConstants
0: acScaleNone
ShowObjectsBorders
Show borders of all objects on the current page, irrespective of the objects border property
Integer
0: Do not show borders 1: Show borders for objects in the template document 2: Show borders for objects in the main document 3: Show borders for objects in main and template documents
ZoomFactor
Zoom factor at which document is viewed Document author Document creator Document keywords Document producer Document subject Document title Main data table or view from which to fetch data Data source to read external data
Longint
140
Metadata Author Creator Keywords Producer *ReadOnly Subject Title Database DataTableOrView String String String String String String String NULL Amyuni PDF Creator NULL Amyuni PDF Creator 2.0 NULL NULL
DataSource Printing
String
88
DestinationFile
When set, the document is printed to a file as opposed to a real printer Double-sided printing
String
Null
DuplexPrinting
Integer
1 No duplex
FormToBinMap
Assign each paper size to a specific printer tray Each page is printed as a single image Name of target printer Devmode structure associated with target printer Sequence in which pages are printed
String
(Printer1) Size1 Tray1 Size2 Tray2 (Printer2) Size1 Tray1 Size2 Tray2 True/False False
PrintAsImage
Boolean
PrinterName PrinterDevMode
String ByteArray
NULL NULL
PrintSequence ScaleToPrinter
NULL 0: acScaleNone
TraySelection
Determines how Integer does the control selected paper trays when printing
0: PDF file setting if any 1: Set by the destination printer 2: Set depending on the FormToBinMap property
Security OwnerPassword Owner password supplied when opening or encrypting the document. Combination of flags that determines which operations are enabled in a password protected document String NULL
Permissions *ReadOnly
Longint
4: Printing is allowed 8: Modify document contents 16: Copy text and graphics from the document 32: Add or modify annotations and form fields
Security *ReadOnly
Specifies whether the document is protected by a password User password supplied when opening or encrypting the document.
Integer
0: No password security
UserPassword
String
NULL
89
Page Attributes
The reserved Pages identifier can be used to access each pages attributes. To access the attributes of page 1 of a document, one can use the Pages[1] reference. Example: To display the page width of page 2 of a document, we can use: PDF1.ObjectAttribute( Pages[2], Width ) = Attribute Width Description Width of paper in Twips (inches * 20) Length of paper in Twips (inches * 20) Top margin in Twips Bottom margin in Twips Left margin in Twips Right margin in Twips Paper orientation Paper size. Type Longint Values >0 Default Value 12240 (Letter size) or 11905 (A4 size) depending on country 15840 (Letter size) or 16838 (A4 size) depending on country 340 340 340 340 False 1 (Letter size) or
Length
Longint
>0
1: Letter 8 1/2 x 11 in 9 (A4 size) depending 5: Legal 8 1/2 x 14 in on country. 9: A4 210 x 297 mm 8: A3 297 x 420 mm 256: Custom size PaperBin Paper source when printing document Integer Defined by Windows 15: default paper bin 4: manual feed 1: upper bin Objects List of objects contained on the page Array Read-Only 15: default paper bin
90
Cell Attributes
The reserved Cells identifier can be used to access each cells attributes. To access the attributes of cell (Row,Col) of a document or a table, one can use the Cells[Row,Col] reference. Note that cell indices start at 1 and the index 0 is invalid. Example: To set the background color of cell (3,2) to red, we can use: PDF1.ObjectAttribute( Cells[3,2], BackColor, 0x00FF0000 ) Note that the document itself can be in the form of a table (Excel style spreadsheet), in this case we can access each cells attributes through ObjectAttribute. If a table object named Table1 is added to a document, and we want to access the attributes of Table1, we should use: PDF1.ObjectAttribute( Table1.Cells[3,2], BackColor, 0x00FF0000 )
Description Horizontal position in Twips Width of cell in Twips. Changing this property changes the width of the column where the cell is located. Multiline text contained in cell Font used to draw cells content Color used to draw text Horizontal text alignment
String Font Color Integer If empty, default document font is used 000000 to FFFFFF 1: Left 2: Center 3: Right NULL Black (000000) 1: Left
VertAlign
Integer
1: Top
TextGap
0: None
DataType
Integer
0: Unknown
Format
Text
The formats for each data type are similar to what is provided by Microsoft Excel 000000 to FFFFFF If empty, default document value is used 1 Top Left 2 Top Center 3 Top Right 4 Bottom Left 5 Bottom Center 6 Bottom Right
Null
0 (Black) NULL
TitlePosition
Integer
1 Top Left
TitleVertical
Boolean
False
91
HorzBorders
Integer
0 - None
VertBorders
Integer
0 - None
BorderColor BorderWidth
Background color Spacing between characters Spacing between words Field can be modified by user when the document is compiled or saved in view only mode Vertical text
-1 (Transparent) 0 0 True
Vertical
Boolean
True / False
False
Cell title or caption can be in one of the four corners or centered Horizontal borders
Vertical borders
Cell content
92
Example ' create a Text object Private Sub cmdCreateText_Click() With PDF1 .Open "c:\temp\test.pdf", "" .ReportState = acReportStateDesign ' open a sample PDF document ' switch the control to design mode
' create a text to add to the document .CreateObject acObjectTypeText, " Text 1" ' text to display .ObjectAttribute("Text 1", "Text") = "Hello There" ' position the text .ObjectAttribute("Text .ObjectAttribute("Text .ObjectAttribute("Text .ObjectAttribute("Text
' set background color to yellow .ObjectAttribute("Text 1", "BackColor") = "7FFFFF" .Save "c:\temp\testFrame.pdf", 1 End With End Sub ' save the modified document
93
94
StrokeStyle
Drawing style
Integer
String in the form of: Null FontName,FontSize,We ight,Italic,Underline 1: Left 2: Center 3: Right 1: Left
HorzAlign
Integer
VertAlign
Integer
1: Top
TextGap
0: None
Paragraph indentation Color for drawing text border Width of border around text
Integer Color Integer. Units are in points or 12th of an inch. 000000 to FFFFFF 0: None 1: Simple 2: Double 3: Triple 4: Quadruple
Spacing between characters Spacing between words Angle for drawing text Allows breaking words on special characters (+, -, *, (, ), =, etc) Horizontal scaling factor Text is limited to a single line
0 0 0 False
HorizontalScale Singleline
100 False
95
Values
HorzAlign
Integer
1: Left
1: Top
0: None
False
0: None
0: None
Black (000000) 1
0 0
of a twip
96
TextAngle HorzAlign
Integer Integer
0 1: Left
1: Top
0: None
0: None
5 Black (000000) 1
StrokeStyle
Drawing style
Integer
Spacing between characters Spacing between words Polygone filling mode Polygone rotation
0 0 1: Alternate 0
97
Compression
Integer
98
BackColor HorzAlign
Color Integer
Password
Boolean
True / False
False
MultiLine
Boolean
True / False
False
DataType
Integer
0: Unknown
Format
Text
The formats for each data type are similar to what is provided by Microsoft Excel When a document is compiled, the content of the Text property is evaluated and the value stored in Value. This is the value displayed to the user when the document is in compiled or view-only mode.
Null
Value
Text
Null
99
BackColor HorzAlign
Color Integer
Text
Text
Null
Value
Text
When a document is compiled, the content of the Text property is evaluated and the value stored in Value. This is the value displayed to the user when the document is in compiled or view-only mode. This property is specific to Acrobat Reader but has no effect in the PDF Creator. This property is specific to Acrobat Reader but has no effect in the PDF Creator. This property is specific to Acrobat Reader but has no effect in the PDF Creator. 1: Left 2: Right
Null
AutoRadio
Flag that indicates if clicking on a radio-button will check/uncheck the button Caption or title of the button when it is pressed Caption or title of the button when the cursor is placed over it Text position
Boolean
True
TextDown
String
Null
TextOver
String
Null
TextPosition
Integer
1: Left
100
Longint Color Integer. Units are in points or 12th of an inch. 000000 to FFFFFF 0: None 1: Simple 2: Double 3: Triple 4: Quadruple
Author Bitmap
String 0: Default (Notepad) 1: Sticky note 2: Notepad with pen 3: Clipboard 4: Dialogue baloon
Visible Editable
Field is visible when document is printed Field can be modified by user when the document is compiled or saved in view only mode Sets open/closed state of the sticky note
Boolean Boolean
True True
Open
Boolean
True / False
True
101
BackColor TitleFont
Color Font
Longint Color Integer. Units are in points or 12th of an inch. 000000 to FFFFFF 0: None 1: Simple 2: Double 3: Triple 4: Quadruple
Name of the person creating the note/document Field is visible when document is printed Field can be modified by user when the document is compiled or saved in view only mode Sets open/closed state of the sticky note
Open
Boolean
True / False
True
102
HorzAlign
Integer
1: Left
EditBox Visible
Boolean Boolean
False True
103
Number of columns appearing Integer in the table object Number of rows appearing in the table object Color for drawing text border Width of border around cell Integer
BorderColor BorderWidth
ProgId
104
105
Linking to a database
A document created with the PDF Creator can be linked to a database. Information can be retrieved from a table or a view to populate various fields of the document. The database can be of type Microsoft Access (.MDB) database, or an ODBC source. The .MDB file name or ODBC source should be specified in the DataSource property of the Document object. The main table or view from which to retrieve data should be specified in the D ataTableOrView property of the Document object. A field or a cell can contain an expression derived from a database by using the following syntax: TableName.FieldName. Here is a sample showing how to create an object linked to a database:
Private Sub Command2_Click() With PDF1 ' set the data source to an Access file .DataSource = "c:\temp\test.mdb" ' set the main table .DataTableOrView = "DOCUMENTS" ' create a field object .CreateObject acObjectTypeField, "Field 1" ' position the object .ObjectAttribute("Field .ObjectAttribute("Field .ObjectAttribute("Field .ObjectAttribute("Field
' set the object value to be the field TITLE from the table DOCUMENTS .ObjectAttribute("Field 1", "Text") = "=DOCUMENTS.TITLE" ' compile the document and switch to Run mode ' this will fill the "Field 1" object with the first record of the table ' each time this method is called, a new value is fetched from the table .DoCommandTool (acCommandToolRunDocument) End With End Sub
106
107
Syntax Function Open(FileName As String, Password As String) As Long HRESULT Open(BSTR FileName, BSTR Password, [out, retval] BOOL *Result); Function OpenEx(FileName As String, Password As String) As Long HRESULT OpenEx(BSTR FileName, BSTR Password, [out, retval] BOOL *Result);
Parameters FileName name of the PDF file to open Password password to use if document is protected
Remarks - Member of PDFCreactiveX - To check if a document is protected and ask the user for the password, you can use the following sequence of calls
Example success = PDF1.Open("c:\temp\test.pdf", "") MsgBox success ' if the document is protected If success = False And PDF1.Protected Then ' ask for password and open the document with it success = PDF1.Open("c:\temp\test.pdf", password) MsgBox success End If
108
Save Method
The Save method saves PDF document to file.
Syntax Sub Save(FileName As String, SaveOption As FileSaveOptionConstants) HRESULT Save(BSTR FileName, FileSaveOptionConstants SaveOption);
Parameters FileName name of the file where to save the document SaveOption part of the document to save. the SaveOption is of type FileSaveOptionConstants which is defined as follows: Value Option Description 0 Save document data and view. acFileSaveAll The document can be viewed with any PDF viewer and retains all design data. 1 Save only document view. The document can be viewed with any PDF viewer including acFileSaveView Amyuni PDF Creator but all design data such as database connection, OLE objects, is lost. 2 Save only document data. The document can be opened, viewed and edited only with acFileSaveDesign the Amyuni PDF Creator. It will show as blank pages in other viewers. -1 Take the default Save option stored in the document object, acFileSaveDefault ie one of the 3 options above.
Example Private Sub cmdSave_Click() PDF1.Save "c:\temp\testFileSaveAll.pdf", acFileSaveAll 'or 0 : Save the modified document with View & Design data 'PDF1.Save "c:\temp\testFileSaveView.pdf", acFileSaveView 'or 1 : Save the modified document with only View data 'PDF1.Save "c:\temp\testFileSaveDesign.pdf", acFileSaveDesign 'or 2: 'Save the modified document with only Design data 'PDF1.Save "c:\temp\testFileSaveDefault.pdf", acFileSaveDefault 'or -1: Save with default save option of the document End Sub
109
SavePage Event
The SavePage event is fired for each page being saved. The application can filter the pages to be printed by intercepting theSavePage event
Syntax Event SavePage(PageNumber As Long, Continue As Long) void SavePage(long PageNumber, long * Continue);
Parameters PageNumber page number of the document to save Continue Set this parameter to 0 to skip, 1 to save, -1 to cancel
Return Value
Example Private Sub PDF1_SavePage(ByVal PageNumber As Long, Continue As Long) ' save range of pages specified by user in StartPage and EndPage parameters If PageNumber < StartPage Then Continue = 0 ' skip all pages before StartPage ElseIf PageNumber > EndPage Then Continue = -1 ' stop saving after EndPage End If End Sub
110
StartSave Method
The StartSave method is used to start page by page saving of a document
Syntax Sub StartSave(FileName As String, SaveOption As FileSaveOptionConstants) HRESULT StartSave(BSTR FileName, FileSaveOptionConstants SaveOption);
Parameters FileName name of the file where to save the document SaveOption part of the document to save. Note : For this method, only the acFileSaveView option of FileSaveOptionConstants is supported. Option acFileSaveView Value 1 Description Save only document view. The document can be viewed with any PDF viewer including Amyuni PDF Creator but all design data such as database connection, OLE objects, is lost.
Return Value This method launches an exception if an error occurs while saving the document.
Example Private Sub cmdSavePagebyPage_Click() Dim n As Long Dim startSave As Long Dim endSave As Long startSave = 6 endSave = 10 With PDF1 ' open a document and save only specified pages .Open "d:\temp\PDF Creator Developer Manual.pdf", "" ' Only "acFileSaveView" option is supported for this method. .startSave "c:\temp\savePageByPage.pdf", acFileSaveView ' Save only from page 6 to page 10 For n = startSave To endSave .SavePage n Next ' close the save job .endSave End With End Sub
111
SavePage Method
The SavePage method is used to save a single page during page by page saving.
Parameters PageNumber Page number of the document to save. Return Value This method launches an exception if an error occurs while saving the document.
112
EndSave Method
The EndSave method ends page by page saving of the document.
Parameters None
Return Value This method launches an exception if an error occurs while saving the document.
113
114
IStream *inputStream = NULL; IPersistStreamInit *pdfStream = NULL; // m_pdfControl is the object associated with the PDF control m_pdfControl->QueryInterface( IID_IPersistStreamInit, (void **)&pdfStream ); // hGlobal is the handle to the memory where the PDF data resides CreateStreamOnHGlobal( hGlobal, FALSE, &inputStream ); // load the PDF control from the memory object pdfStream->Load( inputStream );
115
116
Encrypt Method
The Encrypt method secures the PDF document and prevent it from unauthorized access. Two passwords, the owner password and user password, are associated to a cryted PDF document This feature is only available in the professional version of the PDF Creator Syntax Sub Encrypt(OwnerPass As String, UserPass As String, Permissions As Long) HRESULT Encrypt(BSTR OwnerPass, BSTR UserPass, long Options); Parameters OwnerPass Owner password for the author of the document . The owner password is mandatory and allows the author having this password to do any operation he/she wishes on this document, including modifying its security settings. UserPass User password for the destinator or user of the document. The user password is optional and can be one of the following: User Password Option A blank password Description The user is not prompted for a password when opening a document, but is restricted to the operations allowed by the author. The user is prompted for a password and the author of the document will not be able to open this document as an owner to change its security settings. The user will not be able to open the document unless he/she enters a valid password. When a valid password is entered, the document can be viewed but its usage restricted to the operations allowed by the author.
Permissions Permissions to user Permission Type Value &HFFFFFFC0 &HFFFFFFC0 + 4 &HFFFFFFC0 + 8 &HFFFFFFC0 + 16 &HFFFFFFC0 + 32
No permission Enable printing Enable changing the document Enable copying text and graphics Enable adding and changing notes
Return Value
Example Dim PDF As New acPDFCreactiveX.PDFCreactiveX pdf.Open "test.pdf", "" ' protect a document using an owner and a user password pdf.Encrypt "owner", "user", &HFFFFFFC0 ' to enable printing + adding and changing notes ' pdf.Encrypt "owner", "user", &HFFFFFFC0 + 4 + 32 pdf.Save "test1.pdf", 1 Set pdf = Nothing
117
Encrypt128 Method
The Encrypt128 method secures the PDF document with 128-bit encryption and prevent it from unauthorized access. Two passwords, the owner password and user password, are associated to an encrypted PDF document This feature is only available in the professional version of the PDF Creator
Syntax Sub Encrypt128(OwnerPass As String, UserPass As String, Permissions As Long) HRESULT Encrypt128(BSTR OwnerPassword, BSTR UsrePassword, long Options);
Parameters OwnerPass Owner password for the author of the document . The owner password is mandatory and allows the author having this password to do any operation he/she wishes on this document, including modifying its security settings. UserPass User password for the destinator or user of the document. The user password is optional and can be one of the following: User Password Option A blank password Description The user is not prompted for a password when opening a document, but is restricted to the operations allowed by the author. The user is prompted for a password and the author of the document will not be able to open this document as an owner to change its security settings. The user will not be able to open the document unless he/she enters a valid password. When a valid password is entered, the document can be viewed but its usage restricted to the operations allowed by the author.
Permission Type No permission Enable printing Enable changing the document Enable copying text and graphics Enable adding and changing notes Return Value
Example Private Sub cmdEncrypt128_Click() With PDF1 .Open "c:\temp\test.pdf", "" ' protect a document using an owner and user passwords with all the permissions .Encrypt128 "owner", "user", &HFFFFFFC0 + 4 + 8 + 16 + 32 .Save "c:\temp\testEncrypt128.pdf", 0 End With End Sub
118
DigitalSignature method
The DigitalSignature method is used to add a digital signature to a PDF document. Prior to digitally signing a document, the users or developers should have on their systems a digital certificate that can be used to sign documents. A user who receives a document that is digitally signed can verify if the digital signature is valid and if the document has been tempered with. Syntax Sub DigitalSignature(ByVal SignerName As String, ByVal Reason As String, ByVal ImageFile As String, ByVal Location As String, ByVal PageNumber As Integer, ByVal HorzPos As Integer, ByVal VertPos As Integer, ByVal Width As Integer, ByVal Height As Integer, ByVal Flags As Integer) HRESULT DigitalSignature( [in] BSTR SignerName, [in] BSTR Reason, [in] BSTR ImageFile, [in] BSTR Location, [in] long PageNumber, [in] long HorzPos, [in] long VertPos, [in] long Width, [in] long Height, [in] long Flags ) Parameters SignerName This is the friendly name of the digital signature as it appears to the user when the digital certificate is installed on the system. In most cases, this is the full name of the person signing the document. Reason Reason for signing the document. Can be an empty string if no reason is specified. ImageFile Full path of the file containing the image that is associated with the signature. This is optional, a digital signature does not always contain an image. Location Physical location of the person who signed the document. This parameter is optional. PageNumber Page number on which to insert the signature. Page numbers start with 1, the value -1 indicates the last page in the document. HorzPos, VertPos Horizontal and vertical position of the digital signature in Twips. Width, Height Width and height of the digital signature in Twips. Flags Combination of flags that determine how the digial signature appears on the page. A value of 0 indicates that the signature is invisible. Return Value This method returns 0 upon success, it returns one of the following exceptions upon failure: E_NOTIMPL E_ACCESSDENIED E_INVALIDARG E_FAIL Remarks - Member of PDFCreactiveX - The Flags parameter can be a combination of one of the following values: Item to show Signer name Reason for signing Location Associated image Date of signing Signature type 1 2 4 8 32 64 Value The license key that is provided does not enable digital signatures The document security settings do not allow the user to modify the document One of the arguments is invalid or the certificate does not allow signing documents The signature already exists
Example With PDF1 .Open( "c:\temp\document.pdf", "" ) ' digitally sign the document .DigitalSignature("Amyuni Dev Signature", "Testing", "c:\temp\signature.jpg", "Montreal", 1, 100, 100, 400, 200, 1 + 2 + 4 + 8 ) .Save("c:\temp\signed.pdf", "" ) End With
119
Signature object
Digital signatures are handled by the Signature object that is part of the Document object. All the digital signature parameters can be set or retrieved using the Signature object. Signature object attributes: Attribute FileName Flags Description Full path of the image associated with the signature Combination of options for how to draw the signature Type String Integer Values Default Value NULL 255: Show all
0: Hidden signature 1: Signer name 2: Reason for signing 4: Location 8: Associated image 32: Date of signing 64: Signature type 255: Show all
Location
Location where the document was signed Reason Reason for signing the document SignatureFilter Optional filter to be used by *ReadOnly the application validating the signature SignatureHandler Type of signature handler *ReadOnly SignerName Friendly name of the digital certificate StoreName Windows stores digital signatures in "stores", each store having a name. This property can be used to get/set the name of the store if it is different from the default "My" store.
Adobe.PPKMS
Remarks In the current version of the PDF Creator, only one signature object can be present in the document, future versions might support multiple signatures for each document. Example
120
Printing documents
Print Method PrintPage Event StartPrint Method PrintPage Method EndPrint Method
121
Print Method
The Print method is used to print the document to specified printer Syntax Sub Print(PrinterName As String, Prompt As Boolean) HRESULT Print(BSTR PrinterName, BOOL Prompt);
Parameters PrinterName If no printer name is specified, the document is printed to the default printer. Prompt If this parameter is set to True, the user is prompted with the printer selection dialog box. Return Value
Example Private Sub cmdPrint_Click() With PDF1 .Open "c:\temp\test.pdf", "" .Print "Amyuni PDF Converter", False End With End Sub
'
122
PrintPage Event
The event PrintPage is fired before each page is printed, this allows the calling application to: Display the printing progress Cancel printing on error, user action, Print only a specified range of pages Change the printers input bin or duplex mode
Syntax Event PrintPage(PageNumber As Long, Continue As Long) void PrintPage(long PageNumber, long * Continue);
Parameters PageNumber PageNumber is the one based index of the page to be printed Continue Set this parameter to 0 to skip, 1 to print, -1 to cancel Return Value
Example Private Sub PDF1_PrintPage(ByVal PageNumber As Long, Continue As Long) ' print range of pages specified by user in StartPage and EndPage parameters If PageNumber < StartPage Then Continue = 0 ' skip all pages before StartPage ElseIf PageNumber > EndPage Then Continue = -1 ' stop printing after EndPage End If End Sub
123
StartPrint Method
The StartPrint method starts printing the document to a specified printer. This method is used to start the printing process and takes the same parameters as the Print method Syntax Sub StartPrint(PrinterName As String, Prompt As Boolean) HRESULT StartPrint(BSTR PrinterName, BOOL Prompt);
Parameters PrinterName If no printer name is specified, the document is printed to the default printer. Prompt If Prompt is set to True, the user is prompted with the printer selection dialog box.
Return Value
Remarks - Member of PDFCreactiveX - Multiple documents can be printed as one print job by using the StartPrint, PrintPage and EndPrint methods.: Example 1 : Private Sub MultiplePrint() ' print more than one document as a single print job With PDF1 ' open fist document and print it .Open "c:\temp\document1.pdf", "" .StartPrint "Laser Printer", False For n = 1 to .PageCount .PrintPage n Next ' open second document and print it .Open "c:\temp\document2.pdf", "" For n = 1 to .PageCount .PrintPage n Next ' close the print job .EndPrint End With
- The document can be printed to a file instead of to a real printer. The output file name is determined through the use of the PrintToFileName property. When printing to file is requested, the user will not be prompted for the destination printer: Example 2 : Private Sub PrintPagesToFile(ByVal StartPage As Long, ByVal EndPage As Long) ' print range of pages specified by user in StartPage and EndPage parameters With PDF1 .PrintToFileName "c:\temp\invoice.ps" .StartPrint "Postscript Printer", False For n = StartPage to EndPage .PrintPage n Next .EndPrint End With
124
PrintPage Method
The PrintPage method prints the specified page. This method is called for every page to be printed. Syntax Sub PrintPage(PageNumber As Long) HRESULT PrintPage(long PageNumber);
Return Value
125
EndPrint Method
The EndPrint method is called to end the printing Syntax Sub EndPrint() HRESULT EndPrint();
Parameters None
Return Value
126
127
DoCommandTool Method
Command or tool button clicked on toolbar The PDF Creator responds to various commands sent to it through this method Syntax Sub DoCommandTool(Id As CommandToolConstants) HRESULT DoCommandTool(CommandToolConstants Id);
Parameters Id See List of commands provided by the PDF Control in page 105
Return Value
Example Private Sub cmdDoCommandTool_Click() With PDF1 .InitBlank ' initialize a blank page .DoCommandTool (acCommandToolDesignMode) ' put control in Design mode to insert an object .DoCommandTool (acCommandToolPageView) ' set the page to PageView display .DoCommandTool (acCommandToolTable) ' enable to insert a table object End With End Sub
128
UpdateCommandTool Function
The UpdateCommandTool function returns the status of a command or tool button. To get the status of a specific command button, we can use the UpdateCommandTool method.
Syntax Function UpdateCommandTool(Id As CommandToolConstants) As CommandToolStatusConstants HRESULT UpdateCommandTool([in]CommandToolConstants *Status); Id, [out, retval] CommandToolStatusConstants
Parameters Id See List of commands provided by the PDF Control on page 127 Return Value CommandToolStatusConstants The status of a command or tool button. This can be either Enabled, Disabled and/or Pressed. Option acCommandToolStatusDisabled acCommandToolStatusEnabled acCommandToolStatusPressed acCommandToolStatusUnknown Value 0 1 2 0
Example Private Dim Dim Dim Sub cmdUpdateCommand_Click() tableStatus As CommandToolStatusConstants pageViewStatus As CommandToolStatusConstants desModeStatus As CommandToolStatusConstants
desModeStatus = PDF1.UpdateCommandTool(acCommandToolDesignMode) pageViewStatus = PDF1.UpdateCommandTool(acCommandToolPageView) tableStatus = PDF1.UpdateCommandTool(acCommandToolTable) MsgBox desModeStatus MsgBox pageViewStatus MsgBox tableStatus End Sub
129
acCommandToolPageDown acCommandToolPageHome acCommandToolPageEnd acCommandToolActivate acCommandToolRunDocument acCommandToolDesignMode acCommandToolPageProperties acCommandToolDocumentProperties acCommandToolAlignLeftEdges acCommandToolAlignRightEdges acCommandToolAlignTopEdges acCommandToolAlignBottomEdges acCommandToolAlignHorizontalCenters acCommandToolAlignVerticalCenters acCommandToolMakeSameWidths acCommandToolMakeSameHeights acCommandToolGridSpacing acCommandToolConvToTable acCommandToolMergeCells acCommandToolSplitCells acCommandToolInsertColumn acCommandToolRemoveColumn acCommandToolInsertRow acCommandToolRemoveRow acCommandToolSearch acCommandToolReplace
D20C D20D D20E D20F D210 D211 D212 D213 D214 D215 D216 D217 D218 D219 D21A D21B D230 D2FF D300 D301 D302 D303 D304 D305 D320 D321
53772 53773 53774 53775 53776 53777 53778 53779 53780 53781 53782 53783 53784 53785 53786 53787 53808 54015 54016 54017 54018 54019 54020 54021 54048 54049
Move one page down (next page) Go to first page Go to last page Activate selected object Run/Compile the document Switch between design or execute (run) mode Open page properties dialog box Open document properties dialog box Align selected objects to the left Align selected objects to the right Align selected objects to the top Align selected objects to the bottom Align selected object centers horizontally Align selected object centers vertically Make selected object widths equal Make selected object heights equal Adjust the grid spacing Convert a group of objects into a table Merge selected cells into one cell Split merged cells back into individual cells Insert column before selected cell Remove column before selected cell Insert row before selected cell Remove row before selected cell Search for a specific text Replace a text found with a text specified
131
132
RootBookmark Property
The RootBookmark property gives access from the PDF Creator ActiveX control to the whole bookmark tree. Syntax Property RootBookmark As acBookmark HRESULT RootBookmark([out, retval] IacBookmark * *pVal);
Parameters
Return Value
Example Private Dim Dim Dim Sub cmdInsertBookmark1_Click() PDFdoc As Object intCtr As Integer intTotalPages As Integer
'Create new Bookmarks Dim root As acBookmark Dim child As acBookmark Set PDFdoc = CreateObject("PDFCreactiveX.PDFCreactiveX")' create the PDF Creator control dynamically With PDFdoc .Open "c:\temp\test.pdf", "" intTotalPages = .PageCount Set root = .RootBookmark intCtr = intCtr + 1
root.InsertChild 0, "Pages[" & intCtr & "]", "", child 'insert root bookmark at top level '/////////////////////////////////////////////////////////////////////////// 'root.InsertChild Index, Title, Object, BookMark 'Index : 0 based index where the child bookmark should be inserted 'Title : bookmark title 'Object : reference of the object where the bookmark should point 'if no object is selected, it will point to the top of the current page. 'BookMark : as acBookmark '///////////////////////////////////////////////////////////////////////// For intCtr = intTotalPages To 2 Step -1 .CurrentPage = intCtr 'Move to next page. 'insert child bookmarks, one per page with hidden ID (see next page) child.InsertChild 0, "Pages[" & intCtr & "]" & Chr$(9) & intCtr, "", Nothing Next 'Delete the bookmarks objects Set child = Nothing Set root = Nothing 'Save the pdf file with Bookmarks .Save "c:\temp\bookmark_sample.pdf", acFileSaveAll End With Set PDFdoc = Nothing End Sub
133
InsertChild Method
The InsertChild method is used to insert child bookmark at specified position. This method inserts a child bookmark at the specified location. The bookmark will point by default to the object referenced in the Object parameter. If Object is empty, the bookmark points to the first selected object, if no object is selected, it will point to the top of the current page. Syntax Sub InsertChild(Index As Long, Title As String, Object As String, Bookmark As acBookmark) HRESULT InsertChild(long Index, BSTR Title, BSTR Object, IacBookmark ** Bookmark);
Parameters Index 0 based index where the child bookmark should be inserted Title bookmark title Object reference of the object where the bookmark should point Bookmark reference to the newly inserted bookmark
Return Value
Remarks - Member of acBookmark - Starting with PDF Creator version 2, Object can describe any action defined by the PDF specifications. The object property should contain in this case valid PDF syntax to indicate a PDF action. An example is given below.
Example : VB Sample for inserting bookmarks Dim root As acBookmark Dim child As acBookmark Set root = PDF.RootBookmark ' insert bookmark at the top level root.InsertChild 0, "Page 1", "acText1", child ' insert a bookmark as child of first bookmark child.InsertChild 0, "Bookmark 1", "acText2", Nothing ' insert another bookmark that points to our website child.InsertChild 1, "Visit our web site", "/S /URI /URI (http://www.amyuni.com)", Nothing ' insert a bookmark that points to an external file child.InsertChild 2, "Check the documentation", "/S /Launch /F (c:\\temp\\documentation.pdf)", Nothing Set child = Nothing Set root = Nothing ' save PDF file with bookmarks PDF.Save "c:\temp\test.pdf", acFileSaveAll
134
RemoveChild method
The RemoveChild method is used to remove child bookmark at specified position
Parameters Index 0 based index where the child bookmark to be deleted Return Value
Example Private Sub cmdRemoveChild_Click() Dim root As acBookmark Dim child As acBookmark With PDF1 ' open a document with bookmark .Open "c:\temp\test.pdf", "" Set root = PDF1.RootBookmark ' set the root bookmark to access the whole bookmark tree Set child = root.child(0) ' set the child as the bookmark at index 0 of the root child.RemoveChild (0) ' remove bookmark at index 0 of the child .Save "c:\temp\bookmarkRemoved.pdf", 0 Set child = Nothing Set root = Nothing End With End Sub
135
acBookmark.ReachBookmark Method
The ReachBookmark is used to reach document location pointed to by the bookmark
Parameters
Return Value
Example : Navigating using bookmarks Dim root As acBookmark Dim child As acBookmark Set root = PDF.RootBookmark ' get second bookmark under root Set child = root.child(1) ' reach location specified by the bookmark child.ReachBookmark Set root = Nothing Set child = Nothing
136
PDFCreactiveX.ReachBookmark Method
The ReachBookmark method reaches location specified by bookmark
Syntax Sub ReachBookmark(Bookmark as String) HRESULT ReachBookmark(BSTR Bookmark); Parameters Bookmark title of bookmark to reach Return Value
Remarks - Member of PDFCreactiveX - If you have multiple bookmarks having the same title and need to navigate inside the document using the bookmark title, you can add a hidden ID to each bookmark as follows: bookmark.Title = "Introduction" & Chr$(9) & "1" If the ID is not added and multiple bookmarks have the same title, only the first bookmark can be reached with the ReachBookmark method.
Example ' command button to create a 5-page-document with bookmarks on each page. Private Sub DocWithBookmark_Click() Dim pageCount As Integer Dim root As acBookmark Dim child As acBookmark With PDF1 ' set the root bookmark Set root = .RootBookmark root.InsertChild 0, "Chapter 1", "", child For pageCount = 0 To 4 Step 1 If pageCount = 4 Then ' if at the last page, just insert a bookmark and don't add anymore page child.InsertChild pageCount, "Section " & pageCount + 1, "", Nothing 'The bookmark title is "Section #" Else ' otherwise add a bookmark and a new page. child.InsertChild pageCount, "Section " & pageCount + 1, "", Nothing .AddPage pageCount + 1 End If Next .Refresh .Save "c:\temp\reachBookmark.pdf", 1 End With End Sub
' command button to reach a bookmark that a user specifies Private Sub cmdReachBM_Click() Dim secTitle As String With PDF1 .Open "c:\temp\reachBookmark.pdf", "" ' open the document just created ' get an input from the user secTitle = InputBox("Enter section number you wish to go to")' secTitle = bookmark title .ReachBookmark secTitle ' jump to the bookmark which title is the same as the user input .Refresh End With End Sub
137
Title Property
The Title property is used to get/set a bookmark title.
Syntax Property Title As String HRESULT Title([out, retval] BSTR *pVal); HRESULT Title([in] BSTR newVal);
Parameters
Remarks - Member of acBookmark - If you have multiple bookmarks having the same title and need to navigate inside the document using the bookmark title, you can add a hidden ID to each bookmark as follows: bookmark.Title = "Introduction" & Chr$(9) & "1"
Example Private Sub cmdChangeTitleProperty_Click() Dim root As acBookmark Dim child As acBookmark Dim counter As Integer ' open a PDF file containing some text objects in it. PDF1.Open "c:\temp\docWithTextObj.pdf", "" ' set root bookmark pointing to the specified text object, "acText1" Set root = PDF1.RootBookmark root.InsertChild 0, "root", "acText1", child ' insert 3 child bookmarks under root bookmark pointing to each specified text objects. child.InsertChild 0, "child1", "acText2", Nothing child.InsertChild 1, "child2", "acText3", Nothing child.InsertChild 2, "child3", "acText4", Nothing ' display all the title of the child bookmarks. For counter = 0 To child.Count - 1 Step 1 MsgBox "Title of the child at index " & counter & " is " & child.child(counter).Title ' change the title of the bookmark child.child(counter).Title = "NEWchild" & counter + 1 ' display the new title MsgBox "Its title is now changed to " & child.child(counter).Title Next Set child = Nothing Set root = Nothing ' save PDF file with bookmarks PDF1.Save "c:\temp\bookmarkWithNewTitles.pdf", acFileSaveAll End Sub
138
Parent Property
The Parent property gets a parent bookmark if any
Parameters
Example Private Sub cmdParentProperty_Click() Dim root As acBookmark Dim child As acBookmark Dim grandchild As acBookmark ' open a PDF file containing some text objects in it. PDF1.Open "c:\temp\docWithTextObj.pdf", "" ' set root bookmark pointing to the specified object, "acText1" Set root = PDF1.RootBookmark root.InsertChild 0, "root", "acText1", child ' insert 2 child bookmarks under root bookmark. child.InsertChild 0, "child1", "acText2", grandchild child.InsertChild 1, "child2", "acText3", Nothing ' insert a child bookmark under "child1" bookmark . grandchild.InsertChild 0, "grandchild1", "acText4", Nothing MsgBox grandchild.Parent.Title ' displays "root" which is the title of the grandchild's parent.
' save PDF file with bookmarks PDF1.Save "c:\temp\testParentProperty.pdf", acFileSaveAll Set grandchild = Nothing Set child = Nothing Set root = Nothing End Sub
139
Child Property
The Child property gets a child bookmark object at specified position
Syntax Property Child(Index As Long) As acBookmark HRESULT Child(long Index, [out, retval] IacBookmark * *pVal);
Parameters Index 0 based index of child bookmark Return Value It returns a child bookmark object at the index specified.
Example Private Sub cmdChildProperty_Click() Dim root As acBookmark Dim child As acBookmark With PDF1 ' open a document with bookmark .Open "c:\temp\docWithBookmark.pdf", "" ' set the root bookmark to access the whole bookmark tree Set root = PDF1.RootBookmark ' set the child as the bookmark at index 0 of the root bookmark Set child = root.child(0) ' remove bookmark at index 0 of the child child.RemoveChild (0) .Save "c:\temp\testChildRemoved.pdf", acFileSaveAll Set child = Nothing Set root = Nothing End With End Sub
140
Count Property
The Count property returns the count of child bookmarks
Parameters
Example Private Sub cmdCountProperty_Click() Dim root As acBookmark Dim child As acBookmark Dim counter As Integer ' open a PDF file containing some text objects in it. PDF1.Open "c:\temp\docWithTextObj.pdf", "" ' set root bookmark pointing to the specified object, "acText1" Set root = PDF1.RootBookmark root.InsertChild 0, "root", "acText1", child ' insert 3 child bookmarks under root bookmark. child.InsertChild 0, "child1", "acText2", Nothing child.InsertChild 1, "child2", "acText3", Nothing child.InsertChild 2, "child3", "acText4", Nothing ' display the number of child bookmarks in this document. MsgBox "There are " & child.Count & " child bookmarks under the root bookmark." Set child = Nothing Set root = Nothing ' save PDF file with bookmarks PDF1.Save "c:\temp\testCountProperty.pdf", acFileSaveAll End Sub
141
Object Property
The Object property set/gets reference of object to which the bookmark points. Object can be the reference to a text, image or any other PDF Creator object. When navigating to a bookmark, the page where the object is located is shown, and the object scrolled into view.
Syntax Property Object As String HRESULT Object([out, retval] BSTR *pVal); HRESULT Object([in] BSTR newVal);
Parameters
Return Value
Remarks - Member of acBookmark - Object can be empty, in this case the bookmark points to the top of the current page. - Starting with PDF Creator version 2, Object can describe any action defined by the PDF specifications. The object property should contain in this case valid PDF syntax to indicate a PDF action. An example is given below.
Example Private Sub cmdObjectProperty_Click() Dim root As acBookmark Dim child As acBookmark ' open a PDF file containing a text object and picture object in it. PDF1.Open "c:\temp\docWithPic.pdf", "" ' set a root bookmark to access the whole bookmark tree. Set root = PDF1.RootBookmark ' insert a bookmark under the root. root.InsertChild 0, "bookmark1", "acText1", Nothing MsgBox "Bookmark1 is pointing to " & root.child(0).Object ' change the object that bookmark1 is pointing from acText1 to acPicture1 root.child(0).Object = "acPicture1" MsgBox "Bookmark 1 is now pointing to " & root.child(0).Object ' insert another bookmark that points to our website root.InsertChild 1, "Visit our web site", "/S /URI /URI (http://www.amyuni.com)", Nothing .Refresh Set child = Nothing Set root = Nothing ' save PDF file with bookmarks PDF1.Save "c:\temp\testCountProperty.pdf", acFileSaveView End Sub
142
ClickHyperlink Event
The ClickHyperlink event is fired when an object containing a hyperlink has been clicked By intercepting the ClickHyperLink event, the hyperlink action can be customized by the calling application. Syntax Event ClickHyperlink(Object As String, Hyperlink As String, Continue As Long) void ClickHyperlink(BSTR Object, BSTR Hyperlink, long * Continue); Parameters Object the reference of the object being clicked Hyperlinkt This contains the value for the hyperlink property Continue This parameter should be set to 0 if the calling application handles the hyperlink action, otherwise set to 1 to let the PDF Control do the default action Remarks - Member of PDFCreactiveX - The following object types can be associated with a hyperlink: The frame object (acObjectTypeFrame) All OLE objects (acObjectTypeOLE, acObjectTypeExcel, ) The picture object (acObjectTypePicture) The static text object (acObjectTypeText) Each of these object classes provide the property HyperLink of type String. This attribute can be set to one of two formats: 1. External hyperlinks such as http://www.amyuni.com, ftp://ftp.amyuni.com, When the document is saved to file, or compiled into execute mode, the default web browser will be launched when the object is clicked. In the following figure, the text object is set to be a hyperlink to an external web site:
143
Clicking on this text object when switching the document to run mode or opening it with other PDF viewers will open the default web browser.
2. Internal hyperlinks When the hyperlink property starts with the # character, it denotes a link to another location inside the same document. The string after the # sign should be a reference to another object (either a page or any other object) inside the same document. In the example below, clicking on the text object will bring the user to page 23 of the document:
Example Private Sub PDF1_ClickHyperlink(ByVal Object As String, ByVal Hyperlink As String, Continue As Long) ' The '$' can be any character that denotes a special hyperlink If Left$(Hyperlink, 1) = "$" Then Continue = 0 ' do your own hyperlink action MsgBox "You clicked the " & Object & " button" End If End Sub
144
145
SetPageNumbering method
The SetPageNumbering method enables the developer to automatically number all pages of a document. Page numbers are automatically adjusted when pages are added, removed or moved within the document. Syntax Sub SetPageNumbering(Position As acPageNumbersPostions, Font As String, ExtraMarginHorz As Long, ExtraMarginVert As Long, Color As Long, StartWithPage As Long, Format As String) HRESULT SetPageNumbering([in] acPageNumbersPostions Position, [in] BSTR Font, [in] LONG ExtraMarginHorz, [in] LONG ExtraMarginVert, [in] long Color, [in] long StartWithPage, [in] BSTR Format);
Parameters Position One of seven values that describe where to position the page numbers. Possible values are: acNoPageNumbers = 0 acTopLeft = 1 acTopCenter = 2 acTopRight = 3 acBottomLeft = 4 acBottomCenter = 5 acBottomRight = 6 Font String in the format "FontName,Size,Bold,Italic,Underline". This is the font used to draw the page numbers ExtraMarginHorz Horizontal left or right margin in twips ExtraMarginVert Vertical top or bottom margin in twips Color RGB color used to draw the page numbers StartWithPage Page number where to start adding page numbers. If this value is positive, page numbers will start with 1. If this value is negative, page numbers will start with the actual page number. Format Formatting for the page numbers. Two formatting keywords are currently supported: #page and #pages. All other keywords are output as is. Return Value This method returns 0 upon success. It returns an exception with one of the following exception codes upon failure: E_NOTIMPL document. E_ACCESSDENIED E_OUTOFMEMORY The license key that is provided is a read-only license key that does not allow modifying the The document security settings do not allow the user to modify the document Unable to allocate memory needed to execute this method
Remarks Member of PDFCreactiveX Once the document is saved in View Only mode, page numbers become static text part of the main document and cannot be modified anymore using this method. To be able to modify the page numbers after saving and loading a document, the document needs to be saved in "Design" or "View and Design" mode.
Example With PDF1 .Open( "c:\temp\document.pdf", "" ) ' add page numbers in the format - Page 1 of 10 .SetPageNumbering(acBottomCenter, "Verdana,11,700,0,0", 0, 0, &HFF8080, 1, "- Page #page of #pages -" ) .Save("c:\temp\document.pdf", "" ) End With
146
PageNumbers object
Page numbering is handled by the PageNumbers object that is part of the Document object. All the page numbering options can be set or retrieved using the PageNumbers object. PageNumbers object attributes: Attribute Position Description Position of the page numbers Type Integer Values 0: No page numbers 1: Top / Left 2: Top / Center 3: Top / Right 4: Bottom / Left 5: Bottom / Center 6: Bottom / Right Font ExtraMarginHorz ExtraMarginVert Color StartWithPage Font used to draw the page numbers Left or right margin in twips Top or bottom margin in twips RGB color used to draw the page numbers Page number where to start adding page numbers Font Integer Integer Color Integer If this value is positive, page numbers will start with 1. If this value is negative, page numbers will start with the actual page number Two formatting keywords are currently supported: #page and #pages. All other keywords are output as is Courier New,10,400,0,0 0 0 Black (0) 1 Default Value No page numbers (0)
Format
String
Remarks Once the document is saved in View Only mode, page numbers become static text part of the main document and cannot be modified anymore using this object. To be able to modify the page numbers after saving and loading a document, the document needs to be saved in "Design" or "View and Design" mode. Example Dim o As Object With PDF1 Set o = .ObjectAttribute( "Document", "PageNumbers" ) MsgBox o.Attribute( "Font" ) ' retrieve the font used for page numbering End With
147