# PDFedit 0.4.5 scripting documentation

List of Tables

5.1. List of internal variables

List of Examples

2.1. Getting through list of selected tree items
2.2. Getting through list of selected items

# Part I. Scripting documentation for PDF Editor

## Introduction

PDFEditor have support for scripting. Evey item in menu (or toolbar) runs a script (mostly just short call of function, but using complex scripts from menu is possible), and also user can type script commands directly into commandline. Every invocation of script from menu will echo the command to the commandline, so user can learn how to do things in menu directly from commandline if he wants.

QSA is used for scripting, which is based on ECMAScript standard (if you don't know what ECMAScript is, it is basically the same syntax as JavaScript)

This documentation will not explain the language syntax, but will document all functions and objects that are exported from the application to the scripting engine so they may be used in scripts and menus. Also how the scripting work in general and how it can be configured will be explained.

### Note

Scripts are not "secure" by design, as the API contain functions to read or write arbitrary files and directories and to execute external processes. See http://doc.trolltech.com/qsa-1.1.5/extensions-2.html for description of File, Dir and Process classes, which are available to script.

## Startup scripts

When new editor window is launched (but before the document is loaded or created), file `init.qs` from application's data directory is run, then file `userinit.qs` from users's application configuration directory (which is `$HOME/.pdfedit`) is run, if it exists [1] . These files should contain declaration of all functions used in toolbars or menus and may also contain any startup code to be run before loading or creating new document.

In commandline mode, file `init_console.qs` from application's data directory is run instead, then file `userinit_console.qs` from users's application configuration directory (which is `$HOME/.pdfedit`) is run, if it exists [1]

After running these init scripts, any "plugin" scripts from directories specified in configuration are run. By default, these directories are:

1. Directory `scripts` in application's data directory

2. Directory `scripts` in application's binary directory

3. Directory `./pdfedit/scripts` in user's home directory

For "plugin scripts" in commandline mode, scripts are searched in `console` subdirectory of above directories instead.

Scripts are run in alphabetical order (by their filename, case sensitive) and if the same script is encountered in more than one directory, only the one in directory later in list is executed. This ensures that if user install newer version of some script in his home directory, only his version will get executed.

After that, the document is loaded (if it was not specified on commandline, the window will be initially empty without any document)

### Note

Init script should not load a document while starting, as it will be replaced by new one as soon as the script finishes. If functionality such as "automatic loading of a document on startup" is desired, appropriate code should be added to onEmptyFile() function, which will be triggered after starting the editor with empty document. Alternatively, onLoad, onLoadUser or onLoadError fnuctions may be used for this.

## Chapter 1. Static functions common for GUI and command line

##
Annotation createAnnotation(double[4] rect,string type);

Creates and initializes new annotation of given type. Parameter rect specifies annotation rectangle in default user space units.

##
IProperty createArray()

Creates and returns new IProperty of type Array - empty array

##
IProperty createBool(bool value)

Creates and returns new IProperty of type Bool

##
PdfOperator createCompositeOperator(string beginText,string endText)

Creates new composite PDF Operator with specified starting and ending operator text

##
IProperty createDict()

Creates and returns new IProperty of type Dict - empty dictionary

##
PdfOperator createEmptyOperator()

Creates new empty (NULL) PDF Operator

##
IProperty createInt(int value)

Creates and returns new IProperty of type Int

##
IPropertyArray createIPropertyArray()

Creates new array of IProperty items. This array can be used for example as operator parameters

##
IProperty createName(string value)

Creates and returns new IProperty of type String

##
PdfOperator createOperator(string text,IPropertyArray parameters)

Creates new PDF Operator with specified operator text and parameters

##
PdfOperatorStack createPdfOperatorStack()

Create new empty PDF Operator stack

##
IProperty createReal(double value)

Creates and returns new IProperty of type Real

##
IProperty createRef(int valueNum,int valueGen)

Creates and returns new IProperty of type Ref. Does not check validity of the values (if the reference target exists, etc ...)

##
IProperty createString(string value)

Creates and returns new IProperty of type String

##
bool delinearize(string inFile,string outFile)

Tries to delinearize the PDF, reading from input file and writing delinearized result to output file. Does not check for overwriting output. Returns true if delinearization was successful, false in case of failure. In case of failure the error mesage is available via error() function.

##
string error()

Returns last error message (localized) from some operations (openFile, save, saveRevision, saveCopy, delinearize)

##
bool exists(string chkFileName)

Returns true if given file exists on disk, false otherwise

##
bool flatten(string inFile,string outFile)

Tries to flatten the PDF, reading from input file and writing flattened result to output file. Does not check for overwriting output. Returns true if flattening was successful, false in case of failure. In case of failure the error mesage is available via error() function.

##
string[] functions(bool includeSignatures)

Debugging function usable by script developers. Returns list of all functions that are present in current script interpreter. Functions are sorted alphabetically. If includeSignatures is set, function signatures are returned, otherwise only names

##
string loadFile(string name)

Load content of file into string. File is expected to be in utf-8 encoding.

##
Pdf loadPdf(string name,bool advancedMode, bool askPassword=true)

Loads a PDF file without replacing currently opened file in GUI. Scripts can manipulate the PDF file as necessary, but should close it with unloadPdf() method after it don't need to use it anymore. If advancedMode is set to true, document is opened in "advanced mode" (more advanced, but also more dangerous changes to it are possible) If askPassword is set to false, password to document (if the document is encrypted) will not be solicited from user and setPassword method of PDF object have to be called in script with correct password to allow manipulating the encrypted document.

##
string[] objects()

Debugging function usable by script developers. Returns list of all objects that are in current script interpreter

##
string pdftoxml (string inFile, Variant pagenums, string outFile)

Converts pdf to xml. inFile is name of PDF file to convert, pagenums is array with page numbers to convert, outFile is name of XML file to be created

##
void print(string str)

Outputs given string to command window, followed by newline. Useful to output various debugging or status messages

##
double rand()

return floating point pseudorandom value between 0 and 1 inclusive

##
void run(string scriptName,bool skipScriptPath)

Loads and runs script from given filename. File is looked for in the script path, unless absolute filename is given or parameter skipScriptPath is specified. If the file is not found in script path, it is searched in current directory.

##
bool saveFile(string name, string content)

Save string into file. File will be saved in utf-8 encoding.

##
bool saveRawFile(string name, ByteArray content)

Save bytes into file. File will be saved verbatim.

##
void setDebugLevel(string param)

Sets new debugging verbosity level. Accepts same parameter as -d option on commandline (either number or symbolic constant).

##
string time(string format)

Return current date/time using given format string If format string is "ISO", return time in ISO format. If format string is not specified or empty, return in default localized format. Format string may contain following:

d | day without leading zero
dd | day with leading zero
ddd | short localized day name
dddd | long localized day name
M | month without leading zero
MM | month with leading zero
MMM | short localized month name
MMMM | long localized month name
yy | two digit year
yyyy | four digit year
h | hour without leading zero
hh | hour with leading zero
m | minute without leading zero
mm | minute with leading zero
s | second without leading zero
ss | second with leading zero
z | milliseconds without leading zeroes
zzz | milliseconds with leading zeroes
AP | use AM/PM display. AP will be replaced by either "AM" or "PM".
ap | use am/pm display. ap will be replaced by either "am" or "pm".

Anything else is left as is.

##
int tick()

Return "tick counter" in milliseconds, usable to measure time differences

##
Variant transformationMatrixDiv(Variant oldCTM,Variant newCTM)

Solve equation oldCTM * requiredCTM = newCTM (find matrix for inverse transformation). Return requiredCTM. NULL is returned if no such matrix exists All transformation matrixes are represented as array of 6 doubles.

##
Variant transformationMatrixMul(Variant ma,Variant mb)

Multiply vector by transformation matrix (resulting in transformad vector) or transformation matrix by another transformation matrix (joining transformations int single matrix) First parameter (ma) is vector or matrix to multiply. Second parameter (mb) is transformation matrix Transformation matrix is represented by array of 6 float numbers Vector is array of 2 float numbers

##
Variant transformationMatrixMul(double a0,double a1,Variant mb)

Variant of transformationMatrixMul. Multiply vector [a0,a1] by transformation matrix mb and return resulting transformed vector

##
string tr(string text,string context)

Translates given text to current locale. Optional parameter context can specify context of localized text. Returns translated text.

##
void treeNeedReload()

You can call this to explicitly request the tree to reload after the script finishes execution.

##
string utf8(string original)

Return string converted from utf8 encoding to unicode encoding

##
string[] variables()

Debugging function usable by script developers. Returns sorted list of all variables that are in current script interpreter.

##
string version()

Returns version of editor. String is in format 'major.minor.release' for ordinary releases or 'major.minor.relase-suffix' for "special" versions, like cvs checkouts (suffix CVS appended) or versions from branches, which would have branch tag added)

## Chapter 2. Static functions in GUI

##
void processEvents()

Allow application to process its events, so the gui can redraw itself. Useful, it it is called periodically while doing some lenthy operation

##
string askPassword(string title)

Shows dialog that will ask user for password. Parameter title specifies title of the dialog. If not specified, some default like "Enter password" is used. Return entered password or null if dialog is cancelled

##
void setItemText(string name,string newText)

Set text of all menu and toolbar items with given name to specified string. The string will be transtated according to the translation file, so it is suggested to supply english text and add corresponding localized translation into the localization file.

##
string getItemText(string name)

Get text of menu or toolbar item with given name. Returns untranslated (english) string, even when the application is run using another language translation. When setting back the same string, it will be re-translated according to translation file, if different GUI language is selected

##
void about()

Invokes "About" dialog, showing information about this program and its authors

##
void addAnnotation(Page page,double x1,double y1,double w,double h)

Creates dialog for annotations creation. Parameter page is page in which the annotation will be added (x1,y1) are coordinated of lower left point of annotation rectangle. W is the rectangle widht and h is its height Returns after annotation have been inserted into page, or dialog have been cancelled

##
void addObjectDialog(IProperty container)

Invokes dialog for adding additional objects to specified container (which must be Dictionary or Array). After invoking dialog, this function returns immediately and the dialog is left for the user to use. If given object is not specified, curently selected object in property editor is used. If the object is not Dictionary or Array, no dialog is shown.

##
void checkItem(string name,bool check)

Check (second parameter is true) or uncheck (false) item in toolbar and/or menu, given its name If you prefix name with slash ("/"), you will affect "class" of items - every item that belong to the specified class

### Note

Toolbuttons will automatically convert to Togglable toolbuttons this way and will start togling itself automatically on each succesive click

##
void clearConsole()

Clear the console output window

##
void closeAll()

Closes all windows (and thus ends application)

##
bool closeFile(bool askSave,bool onlyAsk)

Closes file opened in this editor window. if askSave is true, user is asked to save the file if it is modified. if onlyAsk is true, file is not actually closed, only user is asked if he want to save work (if not specified, defaults to false). returns true in case of success, or false if user decide not to close current document and keep it open.

##
void createMenuItem(string parentName,string name,string caption,string action,string accel,string icon,string[] classes=QStringList())

Load one menu or toolbar item and insert it into parent menu or toolbar. If the name is "" or "-", separator is inserted on place of the item and rest of parameters are ignored. If inserting item into toolbar and the name will match one of the special items, the special item will be inserted in toolbar and rest of the parameters are ignored. Items that are loaded from settings have theyir name equal to the key in setting they are stored under.

parentName | Name of parent menu/toolbar. If NULL/empty, main menubar is the parent
name | Name of the item. Must be unique.
caption | Caption of item
action | Script to execute when the item is selected
accel | Keyboard accelerator
icon | Name of icon to use
classes | List of item classes

##
void createNewWindow()

Creates new editor window with empty document in it.

##
void enableItem(string name,bool enable)

Enable (second parameter is true) or disable (false) item in toolbar and/or menu, given its name If you prefix name with slash ("/"), you will enable or disable "class" of items - every item that belong to the specified class

##
string filename()

Return name of file loaded in editor window. If the file does not exist on disk (not loaded any file, or file was never saved, having no name), empty string is returned.

##
string fileOpenDialog()

Invokes "open file" dialog and return selected filename, or NULL if dialog was cancelled

##
string fileSaveDialog(string oldName)

Invokes "save file" dialog and return selected filename, or NULL if dialog was cancelled. If file selected in dialog already exists, user is asked to confirm overwriting before returing its name.

##
string fileSaveDialogDiffer(string origName)

Show "save file" dialog and return file selected, or NULL if dialog was cancelled. If file selected in dialog already exists, user is asked to confirm overwriting before returing its name. Name must be different than origName.

##
string fileSaveDialogXml(string oldName)

Invokes "save file" dialog for XML file and return selected filename, or NULL if dialog was cancelled. If file selected in dialog already exists, user is asked to confirm overwriting before returing its name.

##
Color getColor(string colorName);

Get color from color picker with given name. Returns false if the color picker does not exist.

##
string getEditText(string textName)

Get text from editbox or text selection box in toolbar with given name. Returns false if the box does not exist.

##
double getNumber(string name)

Get number from number editbox in toolbar with given name. Returns 0 if the number editbox does not exist.

##
void help(string topic)

Invokes program help. Optional parameter is topic - if invalid or not defined, help title page will be invoked

##
bool isVisible(string widgetName)

Check if part of the window is visible (returns true) or hidden (returns false) widgetName specifies which part:

commandline | Command line
rightside | Right side tools (Tree Window and property editor)
propertyeditor | Property editor
tree | Tree window
statusbar | Statusbar

##
void message(string msg)

Show simple messagebox with specified message and wait until user dismiss it

##
Variant mergeDialog()

Bring up "merge pages from another PDF in this document" dialog. Returns result of merge or NULL if dialog was cancelled Result is array of three elements:

- First element is array with page numbers

- Second element is array with page positions

- Third is filename of the document to be merged in

##
Variant selectPagesDialog (string filename) const

Bring up "select pages" dialog. Returns result of selection or NULL if dialog was cancelled. Result is array of three elements:

- First element is array with page numbers

- Third is filename of the document to be merged in

##
bool modified()

Return true if the document was modified since it was opened or last saved, false otherwise.

##
bool openFile(string name, bool askPassword=true)

Opens file with given name in this editor window. Opens without any questions, does not ask user to save changes to current file, etc ... If askPassword is true (default), user is asked for password to the document and loading fails if user does not enter correct password. If askPassword is false, script have to handle entering the correct password and possible closing of the document on failure by itself. Return true on success, false on failure to load file.

##
void openFileNew(string name)

Opens file with given name in new editor window

##
void options()

Invokes options dialog. Does not wait for dialog to be closed by user and return immediately.

##
Page page()

Return currently shown page

##
int pageNumber()

Return page number of currently shown page

##
Color pickColor();

Invoke dialog to select color and return the color that user have picked, or false if user cancelled the dialog.

##
Menu popupMenu(string menuName)

Create and return a Menu object. The menuName parameter specifies name of item or list from configuration, that will be used to initially fill the menu with items. If this parameter is not specified or invalid, the menu will be initially empty. See documentation for Menu object type for more info about using popup menus.

##
bool question(string msg)

Show Yes/No question and wait for answer. Return true if user selected "yes", or false if user selected "no"

##
int question_ync(string msg)

Show Yes/No/Cancel question and wait for answer. Return 1 if user selected "yes", 0 if user selected "no", -1 if user cancelled dialog (selecting Cancel)

##
void restoreWindowState()

Restore state of current editor window (size and position of window and elements inside it) State is restored from state saved in editor's configuration file.

##
bool save()

Save currently edited document. If current document have no name, user will be asked for name. If it is not possible to ask user or user presses cancel in file chooser, document is not saved. Return true if document was saved, false if it was not saved for any reason (file write error, user refused to give filename on new file ...)

##
bool saveCopy(string name)

Save currently edited document (with currently active revision) under different name. Return true if document was saved, false if it failed to save for any reason

##
bool saveRevision()

Save currently edited document, while creating new revision in the process. Return true if document was saved, false if it was not saved for any reason.

##
void saveWindowState()

Save state of current editor window (size and position of window and elements inside it) State is saved to editor's configuration file.

##
void setColor(string colorName,Variant newColor)

Set color of color picker with given name

##
void setEditText(string textName,string newText)

Set text in toolbar editbox with given name or set selection in text selection box. If you specify string that is not one of the items in the selection box, the current item will remain selected.

##
void setNumber(string name,double number)

Set number in toolbar number editbox with given name

##
void setPredefs(string name,string predefs)

Set list of predefined values for number edit box or select text box with given name. The values in the list must be separated by commas. For number edit box, the user is still able to type in any value not in the list.

##
void setTooltip(string name,string tip)

Set tooltip text for specified number edit box or select text box with given name. Tooltip text will be shown when hovering with mouse over the tool.

##
void setPredefs(string name,string[] predefs)

Set list of predefined values for number edit box or select text box with given name. For number edit box, the user is still able to type in any value not in the list.

##
void setRevision(int revision)

Change active revision in current PDF document

##
void setVisible(string widgetName, bool visible)

Set part of the window to be either visible or invisible, widgetName specifies which part, see isVisible for list of possible names.

##
void showItem(string name,bool show)

Show (second parameter is true) or hide (false) item in toolbar, given its name If you prefix name with slash ("/"), you will affect "class" of items - every item that belong to the specified class

##
TreeItem treeRoot()

Return root item of currently selected tree

##
TreeItem treeRootMain()

Return root item of main tree

##
void warn(string str)

Outputs given warning string to command window, followed by newline, and show this string in a messagebox to alert user.

##
TreeItem firstSelectedItem(string name)

Return first selected tree item. Set internal selected item pointer to first selected item For getting other selected tree items (in case more than one is selected, repeat calling nextSelectedItem() until NULL is returned (no more items)

Example 2.1. Getting through list of selected tree items

     treeItem=firstSelectedItem();
     while (treeItem) {
      doSomething(treeItem);
      treeItem=nextSelectedItem();
     }

You can optionally specify different tree as parameter (by default, selected items from currently shown tree are taken) Specify "main" for main tree, "select" for selected operators or use number to specify number for Nth tree (indexed from zero). Omitting the parameter or specifying "current" will use currently shown tree If specified tree does not exist or its name is invalid, NULL is returned

##
TreeItem nextSelectedItem()

Return next selected tree item. Move internal selected item pointer to next selected item (or invalidate it if no more selected items is found)

##
CObject firstSelected(string name)

Return object held in first selected tree item. Set internal selected item pointer to first selected item For getting other selected tree items (in case more than one is selected, repeat calling nextSelected() until NULL is returned (no more items)

Example 2.2. Getting through list of selected items

     treeObject=firstSelected();
     while (treeObject) {
      doSomething(treeObject);
      treeObject=nextSelected();
     }

You can optionally specify different tree as parameter (by default, selected items from currently shown tree are taken) Specify "main" for main tree, "select" for selected operators or use number to specify number for Nth tree (indexed from zero). Omitting the parameter or specifying "current" will use currently shown tree If specified tree does not exist or its name is invalid, NULL is returned

##
CObject nextSelected()

Return object held in next selected tree item. Move internal selected item pointer to next selected item (or invalidate it if no more selected items is found)

##
QProgressBar * progressBar()

Returns progress bar which can be used to provide visualization of progress. Uses common progress bar from PdfEditWindow class. User should keep in mind, that also someone alse can use this progress bar in same time and he should set total steps before each setProgress method.

## Chapter 3. Static functions in command line

##
void exit(int returnCode=0)

Terminate the application. You can specify return code of application in parameter

##
string[] parameters()

Return list of commandline parameters (excluding any possible switches processed by pdfeditor itself)

##
string takeParameter()

Return first parameter from list of parameters and remove it from the list. Other parameters are shifted to take the empty space. If there is no parameter to take, NULL is returned

## Chapter 4. Callback functions

These are functions called from editor on certain events. Return value (if any) is ignored. If the callback function does not exist, it is skipped

## onChangeRevision()

This function is called after active revision of document is changed

## onConsoleStart()

This function is called in commandline mode after calling all scripts specified in commanline parameters - unless some of the scripts exit the application prematurely, for example by calling exit().

## onEmptyFile()

This function is called after the editor is opened without specifying any document on commandline (without opening any file) or if the current file is closed.

## onLoad()

This function is called after document is opened

## onLoadUser()

This function is called after document is opened (after onLoad() is called)

## onLoadError()

This function is called after an error occured while trying to load a document

## onPageChange()

This function is called after changing to another page in the preview window.

## onPageDelete()

This function is called after pressing "delete" key while in preview window

## onPageRightClick()

This function is called after clicking with right mouse button in window with page preview.

## onTreeLeftClick()

This function is called after clicking with left mouse button on any item in tree window.

## onTreeRightClick()

This function is called after clicking with right mouse button on any item in tree window.

## onTreeMiddleClick()

This function is called after clicking with middle mouse button on any item in tree window.

## onTreeDoubleClick()

This function is called after doubleclicking with left mouse button on any item in tree window.

## onTreeSelectionChange()

This function is called after selection in tree changes.

## onValueChange(name)

This function is called after some of special tools change its value because of interaction. Parameter is name of the special tool. Color selection tool calls this after user select some color in it, edit tool calls this after user presses enter or leaves the control, number tool calls this after user presses enter or selects some of predefined numbers, select tool calls this after changing the selection.

## Chapter 5. Objects exported to scripting

## settings

This object hold application settings and can be used to read or write them.

###
string settings.read(string key,string default=NULL)

Returns application setting with given key. The parameter default specify default value returned when the setting does not exist. It can be omitted, in that case NULL will be returned.

###
bool settings.readBool(string key,bool default=false)

Returns application setting with given key - treating it as boolean value. The parameter default specify default value returned when the setting does not exist. It can be omitted, in that case false will be returned.

###
string settings.readExpand(string key,string default=NULL)

Returns application setting with given key. Environment variable references are expanded (see expand). The parameter default specify default value returned when the setting does not exist. It can be omitted, in that case NULL will be returned.

###
string settings.expand(string)

Return string with environment variable references (in form $VARIABLE and ${VARIABLE}) Any character preceded with backslash (especially $ character) is not processed in expansion.

### Note

Some internal variables (all of them beginning with $PDFEDIT_) can override corresponding environment variables. This function will use the internal variable in expansion if both internal and environment variables exist.

Table 5.1. List of internal variables

$PDFEDIT_BIN | Full path to directory in which the binary file resides
$PDFEDIT_DATA | Full path to directory with editor data files - usually something like `/usr/share/pdfedit` or `/usr/local/share/pdfedit` unless configured diferently when building editor.

###
string settings.write(string key,string value)

Write application setting with given key and value

###
string settings.remove(string key)

Remove key from user settings, effectively restoring the setting to its default value

###
void settings.flush()

Write all unsaved settings to disk. Unsaved settings are automatically writen to disk on application exit, but this can flush them to disk explicitly.

## Document-related objects in scripting

These objects are set to reflect currently edited document

### document

This object represents currently edited PDF document. Type of this object is Pdf

## Chapter 6. Object types (common and PDF objects)

## Annotation

Ancestor type: CObject

This type represent one annotation in page

###
Dict getDictionary()

Returns anotation dictionary

###
Page getPage()

Returns page in which this annotation is, or NULL, if it is not in any page

###
bool remove()

Remove this annotation from its page, if it is in a page. Returns true if it was removed.

###
string getType()

Return type identifier of annotation

###
string getTypeName()

Return human-readable, localized type identifier of annotation

## Array

Ancestor type: IProperty

This type represents an array in PDF document. It hold zero or more values indexed by positive integer, starting from zero. Values can be of any type, either simple types (int, bool, float, string) or complex types (Dict, Array)

###
void add(int index,IProperty ip)

Insert element at given index in array

###
void add(int index,string ip)

Insert String element at given index in array

###
void add(int index,int ip)

Insert Int element at given index in array

###
void add(IProperty ip)

Append element at end of array

###
void add(string ip)

Append String element at end of array

###
void add(int ip)

Append Int element at end of array

###
CObject child(string name)

Get Dict/Array property recursively Will take the name as slash-separated list of childs to traverse to get to target property, going through Dicts and Arrays. Any references on the way are automatically dereferenced

###
int count()

Return size of this array (number of elements)

###
void delProperty(int index)

Delete element with given index from this array. Elements with higher index (if any) are shifted to occupy the space

###
string getText()

Return string representation of this array

###
CObject property(int index)

Get element with given index from this array

## CObject

Base class for all PDF objects used in scripts

###
string type()

return name of this object's type

## ContentStream

Ancestor type: CObject

This type of object represents content stream in document (in page)

###
bool equals(QObject* otherObject)

Return true, if this object is equal to specified object (i.e. if they internally point to the same item) Reference is compared, not the value of objects

###
void deleteOperator(PdfOperator op,bool indicateChange=true)

Delete specified operator from this content stream. If parameter indicateChange is true (which is default), changes are immediately written to underlying stream.

###
string getText()

Return text representation of this content stream

###
void insertOperator(PdfOperator op,PdfOperator newOp,bool indicateChange=true)

Insert specified operator newOp in this content stream, after operator op. If parameter indicateChange is true (which is default), changes are immediately written to underlying stream.

###
void replace(PdfOperator oldOp,PdfOperator newOp,bool indicateChange=true)

Replace old operator oldOp with new operator newOp in this stream. If parameter indicateChange is true (which is default), changes are immediately written to underlying stream.

###
void saveChange()

Write any unwritten changes to operators to underlying stream.

###
PdfOperator getFirstOperator()

Return first operator in this contentstream. If not contains any operator, return NULL.

###
PdfOperator getLastOperator()

Return last operator in this contentstream. If not contains any operator, return NULL.

###
bool isEmpty()

Check if contentstream contains some operator.

## Dict

Ancestor type: IProperty

This type represents a dictionary in PDF document. It hold keys (String) and values. Each key is corresponding to one value. Keys are strings, values can be of any type, either simple types (int, bool, float, string) or complex types (Dict, Array)

###
void add(string name,IProperty ip)

Add property with given name to this dictionary

###
void add(string name,string ip)

Add string property with given name to this dictionary

###
void add(string name,int ip)

Add integer property with given name to this dictionary

###
CObject child(string name)

Get Dict/Array property recursively Will take the name as slash-separated list of childs to traverse to get to target property, going through Dicts and Arrays. Any references on the way are automatically dereferenced

###
int count()

Return number of properties held in this dictionary

###
void delProperty(string name)

Delete property with given name from this dictionary

###
bool exist(string name)

Check for existence of property with given name in this dictionary. If it exists, returns true

###
string getText()

Return string representation of this dictionary

###
CObject property(string name)

Get property with given name from this dictionary

###
CObject propertyDef(string name,int defValue)

Get property with given name from this dictionary. If the property does not exist, add it to the dictionary with given defValue (as Int) and return it

###
CObject propertyDef(string name,string defValue)

Get property with given name from this dictionary. If the property does not exist, add it to the dictionary with given defValue (as String) and return it

###
string[] propertyNames()

Return array containing names of all properties

## IProperty

Ancestor type: CObject

This object represent one property in dictionary or array

###
bool equals(QObject* otherObject)

Return true, if this object is equal to specified object (i.e. if they internally point to the same item) Reference is compared, not the value of objects

###
Variant value()

Return value store inside the property, if it is a simple type. For complex types (Array, Dict, Stream), NULL is returned

###
string getText()

Return text representation of this property

###
CObject ref()

Return reference to this property, but if the property is a reference, return the reference target. This way you will always get dereferenced property for correct manipulation

###
int getInt()

Get integer representation of this property's value, return 0 if it cannot be represented as integer

###
string getType()

Get type identifier of this Property. Can be one of: Null, Bool, Int, Real, String, Name, Ref, Array, Dict, Stream

###
string getTypeName()

Get human readable and localized name of type of this Property

###
void set(string value)

Set value of this property. Work only on Bool, Int, Real, String or Name types, automatically converts value if type of property is different than type of parameter Will do nothing if called on different types (Dict, Array, etc ...)

###
void set(int value)

Overloaded variant of set method

###
void set(double value)

Overloaded variant of set method

###
void set(bool value)

Overloaded variant of set method

## IPropertyArray

Ancestor type: CObject

This type represents arbitrary array of IProperty items It hold zero or more values indexed by positive integer, starting from zero. Values can be of any type, either simple types (int, bool, float, string) or complex types (Dict, Array)

###
void append(IProperty prop)

append one IProperty element to end of array.

###
void clear()

Delete all elements in the array

###
int count()

Return size of this array (number of elements)

###
CObject property(int index)

Get IProperty element with given index from this array

## Page

Ancestor type: CObject

This type of object represents one page in document.

###
void moveAbove(ContentStream cs)

Move specified content stream in this page one level up in painting order.

###
void moveBelow(ContentStream cs)

Move specified content stream in this page one level down in painting order.

###
void moveAbove(int csi)

Move content stream with specified index in this page one level up in painting order.

###
void moveBelow(int csi)

Move content stream with specified index in this page one level down in painting order.

###
void addAnnotation(Annotation an)

Add copy of given annotation to this page

###
void setTransformMatrix(Variant tMatrix)

Set transform matrix of this page. Expects array with 6 real numbers as the matrix.

###
void prependContentStream(PdfOperatorStack opStack)

Add new content stream to page, created from provided stack of PDF operators. They must form a valid content stream Content stream is prepended before other content streams

###
void appendContentStream(PdfOperatorStack opStack)

Add new content stream to page, created from provided stack of PDF operators. They must form a valid content stream Content stream in appended after other content streams

###
string getFontId(string fontName)

For given font name (case sensitive) return it's ID if present on page. If the font is not present, returns NULL

###
string[] getFontIdsAndNames(bool onlyNames)

Return list of all font id's and base names from resource dictionary of a page. For each font id and name pair there are two consecutive elements in returned array, first one containing font id and second one containing the name, so number of elements in output array is always even. If parametr onlyNames is true, id's are ommited and only list of names is returned instead.

###
void addSystemType1Font(string fontName)

Add new Type 1 font to this page resource dictionary with specified font name It is supposed that you insert standard system font name that should be avaiable to all PDF viewers.

###
ContentStream getContentStream(int streamNumber)

Returns content stream with given number from this page Use data fetched by loadContentStreams method, if it wasn't called, it is called before returning the stream

###
void removeContentStream(int streamNumber)

Removes content stream with given number from page.

###
int getContentStreamCount()

Returns number of content streams in this page Use data fetched by loadContentStreams method, if it wasn't called, it is called before returning the count

###
ContentStream getChange(int changeNumber)

Return change with given number as content stream

###
int getChangeCount()

Return number of changes

###
void loadContentStreams()

Get all content streams from page and store them. Get the streams with getContentStreamCount and getContentStream functions. Usually it is not necessary to call this method, as these funtions will call it automatically on first need, but you may call it explicitly to reload the streams stored in this object from the page

###
Dict getDictionary()

Returns page dictionary

###
string getText()

Return text representation of this page

###
double[] mediabox();

Return media box of this page as array (x1,y1,x2,y2). The mediabox is a rectangle from (x1,y1) to (x2,y2)

###
void setMediabox(double x1,double y1,double x2,double y2)

Set media box of this page to given rectangle - from (x1,y1) to (x2,y2)

###
void setMediabox(Rect rc)

Set media box of this page to given rectangle

## Pdf

Ancestor type: CObject

This type of object represents entire document. Note to page manipulation - page numbers start from number 1 (not from zero as some programmers may expect), number of last page is equal to count of pages.

###
bool isReadOnly()

Returns true if document is opened in read-only mode, false if in read-write mode

###
bool isEncrypted()

Returns true if document is encrypted.

###
bool isLinearized()

Return true, if document is linearized PDF, false otherwise

###
bool needsCredentials()

Return true if document is protected and opening the document reqires credentials (usually a password), false otherwise.

###
bool isValid()

Check for PDF validity - return true, if this object is valid PDF document, false if the PDF document was closed or not yet opened (so the object is invalid)

###
void unloadPdf()

Close the document. If the document was opened directly in editor window (with openFile function), it won't be closed, you must use closeFile() function for this. However, all documents loaded with loadPdf function should be closed using this function.

###
bool saveAs(string name)

Save this document under different name. Does not modify name of file in editor, original file is still edited, not this one. Does not check for file existence - it will overwrite the file without warning if it already exists Return true if document was saved, false if it failed to save for any reason

###
bool save(bool newRevision)

Save document to disk under original name If newRevision is true, create new revision while saving. Return true if saved successfully, false if failed to save because of any reason

###
bool setPassword(string pass)

Sets PDF password to use for decryption. Needed for opening password-protected documents Return true if the password was successfully set, false in case of error (bad password ...)

###
Dict getDictionary()

Get document dictionary (object catalog)

###
void removePage(int position)

Remove page with given number from document.

###
int getPagePosition(Page page)

Get position of given page in document or -1 in case of error (page not in document, invalid page, etc...)

###
int getPageCount()

Get number of pages in document

###
Page insertPage(Page page, int position)

Insert given page in document, at given position. Return inserted page.

###
Page getPage(int position)

Return page from document, given its page number.

###
Page getFirstPage()

Return first page in document.

###
Page getLastPage()

Return last page in document.

###
Page getNextPage(Page page)

Return next page in document, relative to specified page.

###
Page getPrevPage(Page page)

Return previous page in document, relative to specified page.

###
bool hasNextPage(Page page)

Return true, if there is next page in document for given page.

###
bool hasPrevPage(Page page)

Return true, if there is previous page in document for given page.

###
int getRevisionsCount()

Return number of available revisions in document

###
int getActualRevision()

Return number of currently active revisions

## PdfOperator

Ancestor type: CObject

This type of object represents pdf operator in content stream

###
bool equals(QObject* otherObject)

Return true, if this object is equal to specified object (i.e. if they internally point to the same item) Reference is compared, not the value of objects

###
double[4] getBBox ();

Return bounding box (rectangle) of this PDF operator

###
PdfOperator getLastOperator()

Return last operator if a this operator is a composite

###
bool containsNonStrokingOperator()

Tries to find first non stroking operator. (some operators are modified by stroking operators, some by nonestroking) Return true if non stroking operator found, false otherwise.

###
bool containsStrokingOperator()

Tries to find first stroking operator. (some operators are modified by stroking operators, some by nonestroking) Return true if stroking operator found, false otherwise.

###
PdfOperatorIterator iterator()

Return PDF Operator iterator, initially pointing at this operator

###
PdfOperatorIterator graphicalIterator(bool forwardDir=true)

Return PDF Graphical Operator iterator, initialialized from this operator Graphical iterator iterate only through Graphical operators in content stream

###
PdfOperatorIterator inlineImageIterator(bool forwardDir=true)

Return PDF Inline Image Operator iterator, initialialized from this operator Inline Image iterator iterate only through inline image operators in content stream

###
PdfOperatorIterator textIterator(bool forwardDir=true)

Return PDF Text Operator iterator, initialialized from this operator Text iterator iterate only through text operators in content stream

###
PdfOperatorIterator changeableIterator(bool forwardDir=true)

Return PDF Changeable Operator iterator, initialialized from this operator Font iterator iterate only through changeable operators in content stream

###
PdfOperatorIterator strokingIterator(bool forwardDir=true)

Return PDF Stroking Operator iterator, initialialized from this operator Font iterator iterate only through stroking operators in content stream

###
PdfOperatorIterator nonStrokingIterator(bool forwardDir=true)

Return PDF Non stroking Operator iterator, initialialized from this operator Font iterator iterate only through non-stroking operators in content stream

###
PdfOperatorIterator fontIterator(bool forwardDir=true)

Return PDF Font Operator iterator, initialialized from this operator Font iterator iterate only through font operators in content stream

###
PdfOperatorStack childs()

Returns stack with all child operators

###
int childCount()

Returns number of child operators under this pdf operator

###
string getText()

Return text representation of this pdf operator

###
string getEncodedText()

Returns encoded text from text operator. Returns an empty string for all other operators.

###
string getName()

Return name of this pdf operator

###
IPropertyArray params()

Returns parameters of this operator in array

###
int paramCount()

Returns number of parameters in this pdf operator

###
void pushBack(PdfOperator op,PdfOperator prev)

Add an operator oper to the end of composite operator prev The operator will be added after operator prev. Second parameter is optional and will default to null operator if not specified

###
void remove()

Remove this PDF operator from its ContentStream. After calling this function, this object became invalid and must not be used further, doing so may result in an exception

###
void setNext(PdfOperator op)

Set next operator

###
void setPrev(PdfOperator op)

Set previous operator

###
PdfOperator clone()

Clone this object

###
ContentStream stream()

Return content stream in which this operator is contained May return NULL if the stream is not known or if this operator is not contained in any content stream

## PdfOperatorIterator

Ancestor type: CObject

This type of object represents pdf operator in content stream

###
PdfOperator current()

Returns current operator from this iterator, or NULL if the iterator is at invalid position (after end, before beginning)

###
PdfOperatorIterator copy()

Create and return copy of this iterator, initially pointing to the same item

###
PdfOperatorIterator next()

Move the iterator to next operator. Return reference to itself, or NULL, if we are after last valid item

###
PdfOperatorIterator prev()

Move the iterator to previous operator Return reference to itself, or NULL, if we are before first valid item

###
ContentStream stream()

Return content stream in which the initial operator used to construct the iterator was contained. May return NULL, if operator is not contained in any content stream or if content stream is not known at time of creation

###
bool isEnd()

Return true, if we are at the end of the operator list (this means after last valid item, so calling current() will return NULL )

###
bool isBegin()

Return true, if we are at the beginning of the operator list (this means before first valid item, so calling current() will return NULL )

###
bool valid()

Return true, if current position is valid (not before beginning or after end of list) (calling current() will return valid item, not NULL)

## PdfOperatorStack

Ancestor type: CObject

This type represents arbitrary array of PDFOperator items It hold zero or more values indexed by positive integer, starting from zero. You can add pdf operators to beginning or end of the array, so the array can behave like double-ended stack

###
int count()

Return size of the stack (number of operators)

###
void append(PdfOperator prop)

append one PdfOperator element to end of stack.

###
void prepend(PdfOperator prop)

prepend one PdfOperator element at beginning of stack.

###
CObject first()

Return first element in stack (from beginning of stack)

###
CObject last()

Return last element in stack (from end of stack)

###
void removeFirst()

Remove first element from stack (from beginning of stack)

###
void removeLast()

Remove last element from stack (from end of stack)

###
CObject element(int index)

Get PdfOperator element with given index from stack

## Stream

Ancestor type: IProperty

This type of object represents stream in document (in page)

###
void setBuffer(ByteArray a)

Sets buffer of this stream from given byte array

###
void setBuffer(string s)

Sets buffer of this stream from given string (overloaded method)

###
void setRawBuffer(ByteArray a)

Sets raw buffer of this stream from given byte array

###
void setRawBuffer(string s)

Sets raw buffer of this stream from given string (overloaded method)

###
bool loadBuffer(string fileName)

Loads buffer of this stream from given file. Return true on success, false on failure while loading

###
bool loadRawBuffer(string fileName)

Loads raw buffer of this stream from given file. Return true on success, false on failure while loading

###
string getBufferString()

Gets buffer of this stream as string

###
ByteArray getBuffer()

Gets buffer of this stream

###
bool saveBuffer(string fileName)

Saves buffer of this stream to given file. Return true on success, false on failure while saving

###
string getDecoded()

Return decoded text representation of this property

###
ByteArray getRawDecoded()

Return decoded raw bytes representation of this property

###
void add(string name,IProperty ip)

Add property with given name to stream dictionary

###
void add(string name,string ip)

Add string property with given name to stream dictionary

###
void add(string name,int ip)

Add integer property with given name to stream dictionary

###
int count()

Return number of properties held in stream dictionary

###
void delProperty(string name)

Delete property with given name from stream dictionary

###
bool exist(string name)

Check for existence of property with given name in stream dictionary. If it exists, returns true

###
CObject property(string name)

Get property with given name from stream dictionary

###
string[] propertyNames()

Return array containing names of all properties in stream dictionary

## Chapter 7. Object types (GUI objects)

These object types do not have direct corespondence to any object inside PDF document, but some of them may allow you to manipulate them indirectly. Main focus of these types is to interact with user.

## Menu

Ancestor type: CObject

This type of object represent one popup menu. You can add menu items and submenus to it and you can execute the menu, which will then return the action picked by user (if any) To create new popup menu object, use the popupMenu function

###
string popup()

Invoke popup menu near position of mouse pointer. Return script for action selected in menu

###
void reset()

Reset the menu, removing all items from it

###
void addItemDef(string def)

Append item (only item, not a list) to menu using its definition

###
void addItem(string name)

Append item or submenu (list) to menu using its name (it will be loaded from configuration)

###
void addSeparator()

Add separator to the menu

## TreeItem

Ancestor type: CObject

This type of object represents one item in treeview. One item in tree usually corespond to one object in PDF document

###
void setSelected(bool selected=true)

Select or unselect this item (true to select, false to unselect)

###
bool selected()

Check if this item is selected Return true if the item is selected, false if not

###
bool valid()

Check if the tree item wrapper is valid, i.e. if corresponding tree item still exist in the tree view. Using most of invalid wrapper's functions will result in exception Return true if valid, false if not

###
void setOpen(bool opened)

Set the item to be opened or closed. Specify true if the item is to be opened, false if closed.

###
CObject item()

Get object contained in this tree item

###
CObject itemref()

Get object inside this tree item, as item() does, but with one exception: If the object is reference, return reference target instead of the reference

###
string itemtype()

Get type of object contained in this tree item (shortcut for .item().type())

###
TreeItem child(string name)

Return child of this tree item with given name, or NULL if this item have no child with such name

###
string[] getChildNames()

Get names of all visible childs items of this treeitem Childs that are not shown in tree (because of treeview settings, etc ...) are not returned. Childs that are "not yet known" (unopened references) are not returned too.

###
TreeItem parent()

Return parent of this tree item, or NULL if this item have no parent

###
string id()

Return name of this tree item

###
string text()

Return caption of this tree item (sometimes can differ from name)

###
string path()

Return path of this tree item (sequence of names from root item to this item, separated by slashes: "/" )

###
void reload()

Explicitly reload contents of this item and its subtree from current state of PDF document

###
void remove()

Remove object in this tree item (and also any possible subitems) from document

## TreeItemContentStream

Ancestor type: TreeItem

This type of object represents one item in treeview representing content stream.

###
void setMode(string newMode)

Set mode of this tree item, i.e. what operators to show as children. Can be:

all | Show all operators
text | Show only text operators
font | Show only font operators
graphic | Show only graphic operators

###
string getMode()

Get mode of this tree item, i.e. what operators to show as children. See setMode for list of modes it can return.