Skip to main content
Version: Version 1.7

Toolbox add-on code samples

Start using the Toolbox add-on library with code samples. Integrate low-level access to the content of PDF files into your application in Java, .NET, and C.

info

Select a code sample in a specific language and download it. The code samples illustrate how to integrate the SDK into your projects for specific use cases. Each code sample includes a README file that gives instructions on how to run the code sample to process one or multiple files.

tip

Do you miss a specific sample and want us to include it here? Let us know through the Contact page, and we'll add it to our sample backlog.

Annotations

Add annotations to PDF

1// Open input document
2using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
3using (Document inDoc = Document.Open(inStream, null))
4{
5    // Create output document
6    using Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite);
7    using Document outDoc = Document.Create(outStream, inDoc.Conformance, null);
8
9    // Copy document-wide data
10    CopyDocumentData(inDoc, outDoc);
11
12    // Define page copy options
13    PageCopyOptions copyOptions = new PageCopyOptions();
14
15    // Copy first page and add annotations
16    Page outPage = CopyAndAddAnnotations(outDoc, inDoc.Pages[0], copyOptions);
17
18    // Add the page to the output document's page list
19    outDoc.Pages.Add(outPage);
20
21    // Copy the remaining pages and add to the output document's page list
22    PageList inPages = inDoc.Pages.GetRange(1, inDoc.Pages.Count - 1);
23    PageList outPages = PageList.Copy(outDoc, inPages, copyOptions);
24    outDoc.Pages.AddRange(outPages);
25}
1private static void CopyDocumentData(Document inDoc, Document outDoc)
2{
3    // Copy document-wide data
4
5    // Output intent
6    if (inDoc.OutputIntent != null)
7        outDoc.OutputIntent = IccBasedColorSpace.Copy(outDoc, inDoc.OutputIntent);
8
9    // Metadata
10    outDoc.Metadata = Metadata.Copy(outDoc, inDoc.Metadata);
11
12    // Viewer settings
13    outDoc.ViewerSettings = ViewerSettings.Copy(outDoc, inDoc.ViewerSettings);
14
15    // Associated files (for PDF/A-3 and PDF 2.0 only)
16    FileReferenceList outAssociatedFiles = outDoc.AssociatedFiles;
17    foreach (FileReference inFileRef in inDoc.AssociatedFiles)
18        outAssociatedFiles.Add(FileReference.Copy(outDoc, inFileRef));
19
20    // Plain embedded files
21    FileReferenceList outEmbeddedFiles = outDoc.PlainEmbeddedFiles;
22    foreach (FileReference inFileRef in inDoc.PlainEmbeddedFiles)
23        outEmbeddedFiles.Add(FileReference.Copy(outDoc, inFileRef));
24}
1private static Page CopyAndAddAnnotations(Document outDoc, Page inPage, PageCopyOptions copyOptions)
2{
3    // Copy page to output document
4    Page outPage = Page.Copy(outDoc, inPage, copyOptions);
5
6    // Make a RGB color space
7    ColorSpace rgb = ColorSpace.CreateProcessColorSpace(outDoc, ProcessColorSpaceType.Rgb);
8
9    // Get the page size for positioning annotations
10    Size pageSize = outPage.Size;
11
12    // Get the output page's list of annotations for adding annotations
13    AnnotationList annotations = outPage.Annotations;
14
15    // Create a sticky note and add to output page's annotations
16    Paint green = Paint.Create(outDoc, rgb, new double[] { 0, 1, 0 }, null);
17    Point stickyNoteTopLeft = new Point() { X = 10, Y = pageSize.Height - 10 };
18    StickyNote stickyNote = StickyNote.Create(outDoc, stickyNoteTopLeft, "Hello world!", green);
19    annotations.Add(stickyNote);
20
21    // Create an ellipse and add to output page's annotations
22    Paint blue = Paint.Create(outDoc, rgb, new double[] { 0, 0, 1 }, null);
23    Paint yellow = Paint.Create(outDoc, rgb, new double[] { 1, 1, 0 }, null);
24    Rectangle ellipseBox = new Rectangle() { Left = 10, Bottom = pageSize.Height - 60, Right = 70, Top = pageSize.Height - 20 };
25    EllipseAnnotation ellipse = EllipseAnnotation.Create(outDoc, ellipseBox, new Stroke(blue, 1.5), yellow);
26    annotations.Add(ellipse);
27
28    // Create a free text and add to output page's annotations
29    Paint yellowTransp = Paint.Create(outDoc, rgb, new double[] { 1, 1, 0 }, new Transparency(0.5));
30    Rectangle freeTextBox = new Rectangle() { Left = 10, Bottom = pageSize.Height - 170, Right = 120, Top = pageSize.Height - 70 };
31    FreeText freeText = FreeText.Create(outDoc, freeTextBox, "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", yellowTransp);
32    annotations.Add(freeText);
33
34    // A highlight and a web-link to be fitted on existing page content elements
35    Highlight highlight = null;
36    WebLink webLink = null;
37    // Extract content elements from the input page
38    ContentExtractor extractor = new ContentExtractor(inPage.Content);
39    foreach (ContentElement element in extractor)
40    {
41        // Take the first text element
42        if (highlight == null && element is TextElement textElement)
43        {
44            // Get the quadrilaterals of this text element
45            QuadrilateralList quadrilaterals = new QuadrilateralList();
46            foreach (TextFragment fragment in textElement.Text)
47                quadrilaterals.Add(fragment.Transform.TransformRectangle(fragment.BoundingBox));
48
49            // Create a highlight and add to output page's annotations
50            highlight = Highlight.CreateFromQuadrilaterals(outDoc, quadrilaterals, yellow);
51            annotations.Add(highlight);
52        }
53
54        // Take the first image element
55        if (webLink == null && element is ImageElement)
56        {
57            // Get the quadrilateral of this image
58            QuadrilateralList quadrilaterals = new QuadrilateralList();
59            quadrilaterals.Add(element.Transform.TransformRectangle(element.BoundingBox));
60
61            // Create a web-link and add to the output page's links
62            webLink = WebLink.CreateFromQuadrilaterals(outDoc, quadrilaterals, "https://www.pdf-tools.com");
63            Paint red = Paint.Create(outDoc, rgb, new double[] { 1, 0, 0 }, null);
64            webLink.BorderStyle = new Stroke(red, 1.5);
65            outPage.Links.Add(webLink);
66        }
67
68        // Exit loop if highlight and webLink have been created
69        if (highlight != null && webLink != null)
70            break;
71    }
72
73    // return the finished page
74    return outPage;
75}
Download code sample
1try (// Open input document
2    FileStream inStream = new FileStream(inPath, FileStream.Mode.READ_ONLY);
3    Document inDoc = Document.open(inStream, null);
4    // Create file stream
5    FileStream outStream = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW)) {
6    try (// Create output document
7        Document outDoc = Document.create(outStream, inDoc.getConformance(), null)) {
8
9        // Copy document-wide data
10        copyDocumentData(inDoc, outDoc);
11
12        // Define page copy options
13        PageCopyOptions copyOptions = new PageCopyOptions();
14
15        // Copy first page and add annotations
16        Page outPage = copyAndAddAnnotations(outDoc, inDoc.getPages().get(0), copyOptions);
17
18        // Add the page to the output document's page list
19        outDoc.getPages().add(outPage);
20
21        // Copy the remaining pages and add to the output document's page list
22        PageList inPages = inDoc.getPages().subList(1, inDoc.getPages().size());
23        PageList outPages = PageList.copy(outDoc, inPages, copyOptions);
24        outDoc.getPages().addAll(outPages);
25    }
26}
1private static void copyDocumentData(Document inDoc, Document outDoc) throws ToolboxException, IOException {
2    // Copy document-wide data
3
4    // Output intent
5    if (inDoc.getOutputIntent() != null)
6        outDoc.setOutputIntent(IccBasedColorSpace.copy(outDoc, inDoc.getOutputIntent()));
7
8    // Metadata
9    outDoc.setMetadata(Metadata.copy(outDoc, inDoc.getMetadata()));
10
11    // Viewer settings
12    outDoc.setViewerSettings(ViewerSettings.copy(outDoc, inDoc.getViewerSettings()));
13
14    // Associated files (for PDF/A-3 and PDF 2.0 only)
15    FileReferenceList outAssociatedFiles = outDoc.getAssociatedFiles();
16    for (FileReference inFileRef : inDoc.getAssociatedFiles())
17        outAssociatedFiles.add(FileReference.copy(outDoc, inFileRef));
18
19    // Plain embedded files
20    FileReferenceList outEmbeddedFiles = outDoc.getPlainEmbeddedFiles();
21    for (FileReference inFileRef : inDoc.getPlainEmbeddedFiles())
22        outEmbeddedFiles.add(FileReference.copy(outDoc, inFileRef));
23}
1private static Page copyAndAddAnnotations(Document outDoc, Page inPage, PageCopyOptions copyOptions) throws ConformanceException, CorruptException, IOException, UnsupportedFeatureException {
2    // Copy page to output document
3    Page outPage = Page.copy(outDoc, inPage, copyOptions);
4
5    // Make a RGB color space
6    ColorSpace rgb = ColorSpace.createProcessColorSpace(outDoc, ProcessColorSpaceType.RGB);
7
8    // Get the page size for positioning annotations
9    Size pageSize = outPage.getSize();
10
11    // Get the output page's list of annotations for adding annotations
12    AnnotationList annotations = outPage.getAnnotations();
13
14    // Create a sticky note and add to output page's annotations
15    Paint green = Paint.create(outDoc, rgb, new double[] { 0, 1, 0 }, null);
16    Point stickyNoteTopLeft = new Point(10, pageSize.height - 10 );
17    StickyNote stickyNote = StickyNote.create(outDoc, stickyNoteTopLeft, "Hello world!", green);
18    annotations.add(stickyNote);
19
20    // Create an ellipse and add to output page's annotations
21    Paint blue = Paint.create(outDoc, rgb, new double[] { 0, 0, 1 }, null);
22    Paint yellow = Paint.create(outDoc, rgb, new double[] { 1, 1, 0 }, null);
23    Rectangle ellipseBox = new Rectangle(10, pageSize.height - 60, 70, pageSize.height - 20);
24    EllipseAnnotation ellipse = EllipseAnnotation.create(outDoc, ellipseBox, new Stroke(blue, 1.5), yellow);
25    annotations.add(ellipse);
26
27    // Create a free text and add to output page's annotations
28    Paint yellowTransp = Paint.create(outDoc, rgb, new double[] { 1, 1, 0 }, new Transparency(0.5));
29    Rectangle freeTextBox = new Rectangle(10, pageSize.height - 170, 120, pageSize.height - 70);
30    FreeText freeText = FreeText.create(outDoc, freeTextBox, "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", yellowTransp);
31    annotations.add(freeText);
32
33    // A highlight and a web-link to be fitted on existing page content elements
34    Highlight highlight = null;
35    WebLink webLink = null;
36    // Extract content elements from the input page
37    ContentExtractor extractor = new ContentExtractor(inPage.getContent());
38    for (ContentElement element : extractor) {
39        // Take the first text element
40        if (highlight == null && element instanceof TextElement) {
41            TextElement textElement = (TextElement)element;
42            // Get the quadrilaterals of this text element
43            QuadrilateralList quadrilaterals = new QuadrilateralList();
44            for (TextFragment fragment : textElement.getText())
45                quadrilaterals.add(fragment.getTransform().transformRectangle(fragment.getBoundingBox()));
46
47                // Create a highlight and add to output page's annotations
48                highlight = Highlight.createFromQuadrilaterals(outDoc, quadrilaterals, yellow);
49                annotations.add(highlight);
50            }
51
52        // Take the first image element
53        if (webLink == null && element instanceof ImageElement) {
54            // Get the quadrilateral of this image
55            QuadrilateralList quadrilaterals = new QuadrilateralList();
56            quadrilaterals.add(element.getTransform().transformRectangle(element.getBoundingBox()));
57
58            // Create a web-link and add to the output page's links
59            webLink = WebLink.createFromQuadrilaterals(outDoc, quadrilaterals, "https://www.pdf-tools.com");
60            Paint red = Paint.create(outDoc, rgb, new double[] { 1, 0, 0 }, null);
61            webLink.setBorderStyle(new Stroke(red, 1.5));
62            outPage.getLinks().add(webLink);
63        }
64
65        // Exit loop if highlight and webLink have been created
66        if (highlight != null && webLink != null)
67            break;
68    }
69
70    // return the finished page
71    return outPage;
72}
Download code sample

Annotations and Form Fields

Add Form Field

1using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
2using (Document inDoc = Document.Open(inStream, null))
3
4// Create output document
5using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
6using (Document outDoc = Document.Create(outStream, inDoc.Conformance, null))
7{
8    // Copy document-wide data
9    CopyDocumentData(inDoc, outDoc);
10
11    // Copy all form fields
12    FieldNodeMap inFormFields = inDoc.FormFields;
13    FieldNodeMap outFormFields = outDoc.FormFields;
14    foreach (KeyValuePair<string, FieldNode> inPair in inFormFields)
15    {
16        FieldNode outFormFieldNode = FieldNode.Copy(outDoc, inPair.Value);
17        outFormFields.Add(inPair.Key, outFormFieldNode);
18    }
19
20    // Define page copy options
21    PageCopyOptions copyOptions = new PageCopyOptions
22    {
23        FormFields = FormFieldCopyStrategy.CopyAndUpdateWidgets,
24        UnsignedSignatures = CopyStrategy.Remove,
25    };
26
27    // Copy first page
28    Page inPage = inDoc.Pages[0];
29    Page outPage = Page.Copy(outDoc, inPage, copyOptions);
30
31    // Add different types of form fields to the output page
32    AddCheckBox(outDoc, "Check Box ID", true, outPage, new Rectangle { Left = 50, Bottom = 300, Right = 70, Top = 320 });
33    AddComboBox(outDoc, "Combo Box ID", new string[] { "item 1", "item 2" }, "item 1", outPage, new Rectangle { Left = 50, Bottom = 260, Right = 210, Top = 280 });
34    AddListBox(outDoc, "List Box ID", new string[] { "item 1", "item 2", "item 3" }, new string[] { "item 1", "item 3" }, outPage, new Rectangle { Left = 50, Bottom = 160, Right = 210, Top = 240 });
35    AddRadioButtonGroup(outDoc, "Radio Button ID", new string[] { "A", "B", "C" }, 0, outPage, new Rectangle { Left = 50, Bottom = 120, Right = 210, Top = 140 });
36    AddGeneralTextField(outDoc, "Text ID", "Text", outPage, new Rectangle { Left = 50, Bottom = 80, Right = 210, Top = 100 });
37
38    // Add page to output document
39    outDoc.Pages.Add(outPage);
40
41    // Copy remaining pages and append to output document
42    PageList inPageRange = inDoc.Pages.GetRange(1, inDoc.Pages.Count - 1);
43    PageList copiedPages = PageList.Copy(outDoc, inPageRange, copyOptions);
44    outDoc.Pages.AddRange(copiedPages);
45}
1private static void CopyDocumentData(Document inDoc, Document outDoc)
2{
3    // Copy document-wide data
4
5    // Output intent
6    if (inDoc.OutputIntent != null)
7        outDoc.OutputIntent = IccBasedColorSpace.Copy(outDoc, inDoc.OutputIntent);
8
9    // Metadata
10    outDoc.Metadata = Metadata.Copy(outDoc, inDoc.Metadata);
11
12    // Viewer settings
13    outDoc.ViewerSettings = ViewerSettings.Copy(outDoc, inDoc.ViewerSettings);
14
15    // Associated files (for PDF/A-3 and PDF 2.0 only)
16    FileReferenceList outAssociatedFiles = outDoc.AssociatedFiles;
17    foreach (FileReference inFileRef in inDoc.AssociatedFiles)
18        outAssociatedFiles.Add(FileReference.Copy(outDoc, inFileRef));
19
20    // Plain embedded files
21    FileReferenceList outEmbeddedFiles = outDoc.PlainEmbeddedFiles;
22    foreach (FileReference inFileRef in inDoc.PlainEmbeddedFiles)
23        outEmbeddedFiles.Add(FileReference.Copy(outDoc, inFileRef));
24}
1private static void AddCheckBox(Document doc, string id, bool isChecked, Page page, Rectangle rectangle)
2{
3    // Create a check box
4    CheckBox checkBox = CheckBox.Create(doc);
5
6    // Add the check box to the document
7    doc.FormFields.Add(id, checkBox);
8
9    // Set the check box's state
10    checkBox.Checked = isChecked;
11
12    // Create a widget and add it to the page's widgets
13    page.Widgets.Add(checkBox.AddNewWidget(rectangle));
14}
1private static void AddComboBox(Document doc, string id, string[] itemNames, string value, Page page, Rectangle rectangle)
2{
3    // Create a combo box
4    ComboBox comboBox = ComboBox.Create(doc);
5
6    // Add the combo box to the document
7    doc.FormFields.Add(id, comboBox);
8
9    // Loop over all given item names
10    foreach (string itemName in itemNames)
11    {
12        // Create a new choice item
13        ChoiceItem item = comboBox.AddNewItem(itemName);
14
15        // Check whether this is the chosen item name
16        if (value.Equals(itemName))
17            comboBox.ChosenItem = item;
18    }
19    if (comboBox.ChosenItem == null && !string.IsNullOrEmpty(value))
20    {
21        // If no item has been chosen then assume we want to set the editable item
22        comboBox.CanEdit = true;
23        comboBox.EditableItemName = value;
24    }
25
26    // Create a widget and add it to the page's widgets
27    page.Widgets.Add(comboBox.AddNewWidget(rectangle));
28}
1private static void AddListBox(Document doc, string id, string[] itemNames, string[] chosenNames, Page page, Rectangle rectangle)
2{
3    // Create a list box
4    ListBox listBox = ListBox.Create(doc);
5
6    // Add the list box to the document
7    doc.FormFields.Add(id, listBox);
8
9    // Allow multiple selections
10    listBox.AllowMultiSelect = true;
11    ChoiceItemList chosenItems = listBox.ChosenItems;
12
13    // Loop over all given item names
14    foreach (string itemName in itemNames)
15    {
16        // Create a new choice item
17        ChoiceItem item = listBox.AddNewItem(itemName);
18
19        // Check whether to add to the chosen items
20        if (chosenNames.Contains(itemName))
21            chosenItems.Add(item);
22    }
23
24    // Create a widget and add it to the page's widgets
25    page.Widgets.Add(listBox.AddNewWidget(rectangle));
26}
1private static void AddRadioButtonGroup(Document doc, string id, string[] buttonNames, int chosen, Page page, Rectangle rectangle)
2{
3    // Create a radio button group
4    RadioButtonGroup group = RadioButtonGroup.Create(doc);
5
6    // Get the page's widgets
7    WidgetList widgets = page.Widgets;
8
9    // Add the radio button group to the document
10    doc.FormFields.Add(id, group);
11
12    // We partition the given rectangle horizontally into sub-rectangles, one for each button
13    // Compute the width of the sub-rectangles
14    double buttonWidth = (rectangle.Right - rectangle.Left) / buttonNames.Length;
15
16    // Loop over all button names
17    for (int i = 0; i < buttonNames.Length; i++)
18    {
19        // Compute the sub-rectangle for this button
20        Rectangle buttonRectangle = new Rectangle()
21        {
22            Left = rectangle.Left + i * buttonWidth,
23            Bottom = rectangle.Bottom,
24            Right = rectangle.Left + (i + 1) * buttonWidth,
25            Top = rectangle.Top
26        };
27
28        // Create the button and an associated widget
29        RadioButton button = group.AddNewButton(buttonNames[i]);
30        Widget widget = button.AddNewWidget(buttonRectangle);
31
32        // Check if this is the chosen button
33        if (i == chosen)
34            group.ChosenButton = button;
35
36        // Add the widget to the page's widgets
37        widgets.Add(widget);
38    }
39}
1private static void AddGeneralTextField(Document doc, string id, string value, Page page, Rectangle rectangle)
2{
3    // Create a general text field
4    GeneralTextField field = GeneralTextField.Create(doc);
5
6    // Add the field to the document
7    doc.FormFields.Add(id, field);
8
9    // Set the text value
10    field.Text = value;
11
12    // Create a widget and add it to the page's widgets
13    page.Widgets.Add(field.AddNewWidget(rectangle));
14}
Download code sample
1try (// Open input document
2    FileStream inStream = new FileStream(inPath, FileStream.Mode.READ_ONLY);
3    Document inDoc = Document.open(inStream, null);
4    FileStream outStream = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW)) {
5    try (// Create output document
6        Document outDoc = Document.create(outStream, inDoc.getConformance(), null)) {
7
8        // Copy document-wide data
9        copyDocumentData(inDoc, outDoc);
10
11        // Copy all form fields
12        FieldNodeMap inFormFields = inDoc.getFormFields();
13        FieldNodeMap outFormFields = outDoc.getFormFields();
14        for (Entry<String, FieldNode> entry : inFormFields.entrySet())
15            outFormFields.put(entry.getKey(), FieldNode.copy(outDoc, entry.getValue()));
16
17        // Define page copy options
18        PageCopyOptions copyOptions = new PageCopyOptions();
19        copyOptions.setFormFields(FormFieldCopyStrategy.COPY_AND_UPDATE_WIDGETS);
20        copyOptions.setUnsignedSignatures(CopyStrategy.REMOVE);
21
22        // Copy first page
23        Page inPage = inDoc.getPages().get(0);
24        Page outPage = Page.copy(outDoc, inPage, copyOptions);
25
26        // Add different types of form fields to the output page
27        addCheckBox(outDoc, "Check Box ID", true, outPage, new Rectangle(50, 300, 70, 320));
28        addComboBox(outDoc, "Combo Box ID", new String[] { "item 1", "item 2" }, "item 1", outPage,
29                new Rectangle(50, 260, 210, 280));
30        addListBox(outDoc, "List Box ID", new String[] { "item 1", "item 2", "item 3" },
31                new String[] { "item 1", "item 3" }, outPage, new Rectangle(50, 160, 210, 240));
32        addRadioButtonGroup(outDoc, "Radio Button ID", new String[] { "A", "B", "C" }, 0, outPage,
33                new Rectangle(50, 120, 210, 140));
34        addGeneralTextField(outDoc, "Text ID", "Text", outPage, new Rectangle(50, 80, 210, 100));
35
36        // Add page to output document
37        outDoc.getPages().add(outPage);
38
39        // Copy remaining pages and append to output document
40        PageList inPageRange = inDoc.getPages().subList(1, inDoc.getPages().size());
41        PageList copiedPages = PageList.copy(outDoc, inPageRange, copyOptions);
42        outDoc.getPages().addAll(copiedPages);
43    }
44}
1private static void copyDocumentData(Document inDoc, Document outDoc) throws ToolboxException, IOException {
2    // Copy document-wide data
3
4    // Output intent
5    if (inDoc.getOutputIntent() != null)
6        outDoc.setOutputIntent(IccBasedColorSpace.copy(outDoc, inDoc.getOutputIntent()));
7
8    // Metadata
9    outDoc.setMetadata(Metadata.copy(outDoc, inDoc.getMetadata()));
10
11    // Viewer settings
12    outDoc.setViewerSettings(ViewerSettings.copy(outDoc, inDoc.getViewerSettings()));
13
14    // Associated files (for PDF/A-3 and PDF 2.0 only)
15    FileReferenceList outAssociatedFiles = outDoc.getAssociatedFiles();
16    for (FileReference inFileRef : inDoc.getAssociatedFiles())
17        outAssociatedFiles.add(FileReference.copy(outDoc, inFileRef));
18
19    // Plain embedded files
20    FileReferenceList outEmbeddedFiles = outDoc.getPlainEmbeddedFiles();
21    for (FileReference inFileRef : inDoc.getPlainEmbeddedFiles())
22        outEmbeddedFiles.add(FileReference.copy(outDoc, inFileRef));
23}
1private static void addCheckBox(Document doc, String id, boolean isChecked, Page page, Rectangle rectangle)
2        throws ToolboxException {
3    // Create a check box
4    CheckBox checkBox = CheckBox.create(doc);
5
6    // Add the check box to the document
7    doc.getFormFields().put(id, checkBox);
8
9    // Set the check box's state
10    checkBox.setChecked(isChecked);
11
12    // Create a widget and add it to the page's widgets
13    page.getWidgets().add(checkBox.addNewWidget(rectangle));
14}
15
1private static void addListBox(Document doc, String id, String[] itemNames, String[] chosenNames, Page page,
2        Rectangle rectangle) throws ToolboxException {
3    List<String> chosenNamesList = Arrays.asList(chosenNames);
4
5    // Create a list box
6    ListBox listBox = ListBox.create(doc);
7
8    // Add the list box to the document
9    doc.getFormFields().put(id, listBox);
10
11    // Allow multiple selections
12    listBox.setAllowMultiSelect(true);
13
14    // Get the list of chosen items
15    ChoiceItemList chosenItems = listBox.getChosenItems();
16
17    // Loop over all given item names
18    for (String itemName : itemNames) {
19        ChoiceItem item = listBox.addNewItem(itemName);
20        // Check whether to add to the chosen items
21        if (chosenNamesList.contains(itemName))
22            chosenItems.add(item);
23    }
24
25    // Create a widget and add it to the page's widgets
26    page.getWidgets().add(listBox.addNewWidget(rectangle));
27}
28
1private static void addComboBox(Document doc, String id, String[] itemNames, String value, Page page,
2        Rectangle rectangle) throws ToolboxException {
3    // Create a combo box
4    ComboBox comboBox = ComboBox.create(doc);
5
6    // Add the combo box to the document
7    doc.getFormFields().put(id, comboBox);
8
9    // Loop over all given item names
10    for (String itemName : itemNames) {
11        ChoiceItem item = comboBox.addNewItem(itemName);
12        // Check whether to add to the chosen items
13        if (value.equals(itemName))
14            comboBox.setChosenItem(item);
15    }
16    if (comboBox.getChosenItem() == null && !(value == null || value.isEmpty())) {
17        // If no item has been chosen then assume we want to set the editable item
18        comboBox.setCanEdit(true);
19        comboBox.setEditableItemName(value);
20    }
21
22    // Create a widget and add it to the page's widgets
23    page.getWidgets().add(comboBox.addNewWidget(rectangle));
24}
25
1private static void addRadioButtonGroup(Document doc, String id, String[] buttonNames, int chosen, Page page,
2        Rectangle rectangle) throws ToolboxException {
3    // Create a radio button group
4    RadioButtonGroup group = RadioButtonGroup.create(doc);
5
6    // Add the radio button group to the document
7    doc.getFormFields().put(id, group);
8
9    // We partition the given rectangle horizontally into sub-rectangles, one for
10    // each button
11    // Compute the width of the sub-rectangles
12    double buttonWidth = (rectangle.right - rectangle.left) / buttonNames.length;
13
14    // Get the page's widgets
15    WidgetList widgets = page.getWidgets();
16
17    // Loop over all button names
18    for (int i = 0; i < buttonNames.length; i++) {
19        // Compute the sub-rectangle for this button
20        Rectangle buttonRectangle = new Rectangle(rectangle.left + i * buttonWidth, rectangle.bottom,
21                rectangle.left + (i + 1) * buttonWidth, rectangle.top);
22
23        // Create the button and an associated widget
24        RadioButton button = group.addNewButton(buttonNames[i]);
25        Widget widget = button.addNewWidget(buttonRectangle);
26
27        // Check if this is the chosen button
28        if (i == chosen)
29            group.setChosenButton(button);
30
31        // Add the widget to the page's widgets
32        widgets.add(widget);
33    }
34}
35
1private static void addGeneralTextField(Document doc, String id, String value, Page page, Rectangle rectangle)
2        throws ToolboxException {
3    // Create a general text field
4    GeneralTextField field = GeneralTextField.create(doc);
5
6    // Add the field to the document
7    doc.getFormFields().put(id, field);
8
9    // Set the check box's state
10    field.setText(value);
11
12    // Create a widget and add it to the page's widgets
13    page.getWidgets().add(field.addNewWidget(rectangle));
14}
Download code sample

Fill Form Fields

1int copyDocumentData(TPtxPdf_Document* pInDoc, TPtxPdf_Document* pOutDoc)
2{
3    // Objects that need releasing or closing
4    TPtxPdfContent_IccBasedColorSpace* pInOutputIntent    = NULL;
5    TPtxPdfContent_IccBasedColorSpace* pOutOutputIntent   = NULL;
6    TPtxPdf_Metadata*                  pInMetadata        = NULL;
7    TPtxPdf_Metadata*                  pOutMetadata       = NULL;
8    TPtxPdfNav_ViewerSettings*         pInViewerSettings  = NULL;
9    TPtxPdfNav_ViewerSettings*         pOutViewerSettings = NULL;
10    TPtxPdf_FileReferenceList*         pInFileRefList     = NULL;
11    TPtxPdf_FileReferenceList*         pOutFileRefList    = NULL;
12    TPtxPdf_FileReference*             pInFileRef         = NULL;
13    TPtxPdf_FileReference*             pOutFileRef        = NULL;
14
15    iReturnValue = 0;
16
17    // Output intent
18    pInOutputIntent = PtxPdf_Document_GetOutputIntent(pInDoc);
19    if (pInOutputIntent != NULL)
20    {
21        pOutOutputIntent = PtxPdfContent_IccBasedColorSpace_Copy(pOutDoc, pInOutputIntent);
22        GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutOutputIntent,
23                                         _T("Failed to copy ICC-based color space. %s (ErrorCode: 0x%08x)\n"),
24                                         szErrorBuff, Ptx_GetLastError());
25        GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_Document_SetOutputIntent(pOutDoc, pOutOutputIntent),
26                                          _T("Failed to set output intent. %s (ErrorCode: 0x%08x)\n"), szErrorBuff,
27                                          Ptx_GetLastError());
28    }
29    else
30        GOTO_CLEANUP_IF_ERROR_PRINT_ERROR(_T("Failed to get output intent. %s (ErrorCode: 0x%08x)\n"), szErrorBuff,
31                                          Ptx_GetLastError());
32
33    // Metadata
34    pInMetadata = PtxPdf_Document_GetMetadata(pInDoc);
35    if (pInMetadata != NULL)
36    {
37        pOutMetadata = PtxPdf_Metadata_Copy(pOutDoc, pInMetadata);
38        GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutMetadata, _T("Failed to copy metadata. %s (ErrorCode: 0x%08x)\n"),
39                                         szErrorBuff, Ptx_GetLastError());
40        GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_Document_SetMetadata(pOutDoc, pOutMetadata),
41                                          _T("Failed to set metadata. %s (ErrorCode: 0x%08x)\n"), szErrorBuff,
42                                          Ptx_GetLastError());
43    }
44    else
45        GOTO_CLEANUP_IF_ERROR_PRINT_ERROR(_T("Failed to get metadata. %s (ErrorCode: 0x%08x)\n"), szErrorBuff,
46                                          Ptx_GetLastError());
47
48    // Viewer settings
49    pInViewerSettings = PtxPdf_Document_GetViewerSettings(pInDoc);
50    if (pInViewerSettings != NULL)
51    {
52        pOutViewerSettings = PtxPdfNav_ViewerSettings_Copy(pOutDoc, pInViewerSettings);
53        GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutViewerSettings,
54                                         _T("Failed to copy viewer settings. %s (ErrorCode: 0x%08x)\n"), szErrorBuff,
55                                         Ptx_GetLastError());
56        GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_Document_SetViewerSettings(pOutDoc, pOutViewerSettings),
57                                          _T("Failed to set viewer settings. %s (ErrorCode: 0x%08x)\n"), szErrorBuff,
58                                          Ptx_GetLastError());
59    }
60    else
61        GOTO_CLEANUP_IF_ERROR_PRINT_ERROR(_T("Failed to get viewer settings. %s (ErrorCode: 0x%08x)"), szErrorBuff,
62                                          Ptx_GetLastError());
63
64    // Associated files (for PDF/A-3 and PDF 2.0 only)
65    pInFileRefList = PtxPdf_Document_GetAssociatedFiles(pInDoc);
66    GOTO_CLEANUP_IF_ERROR_PRINT_ERROR(_T("Failed to get associated files of input document. %s (ErrorCode: 0x%08x)\n"),
67                                      szErrorBuff, Ptx_GetLastError());
68    pOutFileRefList = PtxPdf_Document_GetAssociatedFiles(pOutDoc);
69    GOTO_CLEANUP_IF_ERROR_PRINT_ERROR(_T("Failed to get associated files of output document. %s (ErrorCode: 0x%08x)\n"),
70                                      szErrorBuff, Ptx_GetLastError());
71    int nFileRefs = PtxPdf_FileReferenceList_GetCount(pInFileRefList);
72    GOTO_CLEANUP_IF_ERROR_PRINT_ERROR(_T("Failed to get count of associated files. %s (ErrorCode: 0x%08x)\n"),
73                                      szErrorBuff, Ptx_GetLastError());
74    for (int iFileRef = 0; iFileRef < nFileRefs; iFileRef++)
75    {
76        pInFileRef = PtxPdf_FileReferenceList_Get(pInFileRefList, iFileRef);
77        GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInFileRef, _T("Failed to get file reference. %s (ErrorCode: 0x%08x)\n"),
78                                         szErrorBuff, Ptx_GetLastError());
79        pOutFileRef = PtxPdf_FileReference_Copy(pOutDoc, pInFileRef);
80        GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutFileRef, _T("Failed to copy file reference. %s (ErrorCode: 0x%08x)\n"),
81                                         szErrorBuff, Ptx_GetLastError());
82        GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_FileReferenceList_Add(pOutFileRefList, pOutFileRef),
83                                          _T("Failed to add file reference. %s (ErrorCode: 0x%08x)\n"), szErrorBuff,
84                                          Ptx_GetLastError());
85        Ptx_Release(pInFileRef);
86        pInFileRef = NULL;
87        Ptx_Release(pOutFileRef);
88        pOutFileRef = NULL;
89    }
90    Ptx_Release(pInFileRefList);
91    pInFileRefList = NULL;
92    Ptx_Release(pOutFileRefList);
93    pOutFileRefList = NULL;
94
95    // Plain embedded files
96    pInFileRefList = PtxPdf_Document_GetPlainEmbeddedFiles(pInDoc);
97    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(
98        pInFileRefList, _T("Failed to get plain embedded files of input document %s (ErrorCode: 0x%08x)\n"),
99        szErrorBuff, Ptx_GetLastError());
100    pOutFileRefList = PtxPdf_Document_GetPlainEmbeddedFiles(pOutDoc);
101    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(
102        pInFileRefList, _T("Failed to get plain embedded files of output document %s (ErrorCode: 0x%08x)\n"),
103        szErrorBuff, Ptx_GetLastError());
104    nFileRefs = PtxPdf_FileReferenceList_GetCount(pInFileRefList);
105    GOTO_CLEANUP_IF_ERROR_PRINT_ERROR(_T("Failed to get count of plain embedded files. %s (ErrorCode: 0x%08x)\n"),
106                                      szErrorBuff, Ptx_GetLastError());
107    for (int iFileRef = 0; iFileRef < nFileRefs; iFileRef++)
108    {
109        pInFileRef = PtxPdf_FileReferenceList_Get(pInFileRefList, iFileRef);
110        GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInFileRef, _T("Failed to get file reference. %s (ErrorCode: 0x%08x)\n"),
111                                         szErrorBuff, Ptx_GetLastError());
112        pOutFileRef = PtxPdf_FileReference_Copy(pOutDoc, pInFileRef);
113        GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutFileRef, _T("Failed to copy file reference. %s (ErrorCode: 0x%08x)\n"),
114                                         szErrorBuff, Ptx_GetLastError());
115        GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_FileReferenceList_Add(pOutFileRefList, pOutFileRef),
116                                          _T("Failed to add file reference. %s (ErrorCode: 0x%08x)\n"), szErrorBuff,
117                                          Ptx_GetLastError());
118        Ptx_Release(pInFileRef);
119        pInFileRef = NULL;
120        Ptx_Release(pOutFileRef);
121        pOutFileRef = NULL;
122    }
123
124cleanup:
125    if (pInOutputIntent != NULL)
126        Ptx_Release(pInOutputIntent);
127    if (pOutOutputIntent != NULL)
128        Ptx_Release(pOutOutputIntent);
129    if (pInMetadata != NULL)
130        Ptx_Release(pInMetadata);
131    if (pOutMetadata != NULL)
132        Ptx_Release(pOutMetadata);
133    if (pInViewerSettings != NULL)
134        Ptx_Release(pInViewerSettings);
135    if (pOutViewerSettings != NULL)
136        Ptx_Release(pOutViewerSettings);
137    if (pInFileRefList != NULL)
138        Ptx_Release(pInFileRefList);
139    if (pOutFileRefList != NULL)
140        Ptx_Release(pOutFileRefList);
141    if (pInFileRef != NULL)
142        Ptx_Release(pInFileRef);
143    if (pOutFileRef != NULL)
144        Ptx_Release(pOutFileRef);
145    return iReturnValue;
146}
1int copyFields(TPtxPdf_Document* pInDoc, TPtxPdf_Document* pOutDoc)
2{
3    // Objects that need releasing or closing
4    TPtxPdfForms_FieldNodeMap* pInFields     = NULL;
5    TPtxPdfForms_FieldNodeMap* pOutFields    = NULL;
6    TCHAR*                     szFieldKey    = NULL;
7    TPtxPdfForms_FieldNode*    pInFieldNode  = NULL;
8    TPtxPdfForms_FieldNode*    pOutFieldNode = NULL;
9
10    iReturnValue = 0;
11
12    pInFields = PtxPdf_Document_GetFormFields(pInDoc);
13    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInFields,
14                                     _T("Failed to get form fields of the input document. %s (ErrorCode: 0x%08x).\n"),
15                                     szErrorBuff, Ptx_GetLastError());
16
17    pOutFields = PtxPdf_Document_GetFormFields(pOutDoc);
18    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutFields,
19                                     _T("Failed to get form fields of the output document. %s (ErrorCode: 0x%08x).\n"),
20                                     szErrorBuff, Ptx_GetLastError());
21
22    for (int iField = PtxPdfForms_FieldNodeMap_GetBegin(pInFields);
23         iField != PtxPdfForms_FieldNodeMap_GetEnd(pInFields);
24         iField = PtxPdfForms_FieldNodeMap_GetNext(pInFields, iField))
25    {
26        if (iField == 0)
27            GOTO_CLEANUP_IF_ERROR_PRINT_ERROR(_T("Failed to get form field. %s (ErrorCode: 0x%08x)\n"), szErrorBuff,
28                                              Ptx_GetLastError());
29        // Get key
30        size_t nKey = PtxPdfForms_FieldNodeMap_GetKey(pInFields, iField, szFieldKey, 0);
31        GOTO_CLEANUP_IF_ZERO(nKey, _T("Failed to get form field key\n"));
32        szFieldKey = (TCHAR*)malloc(nKey * sizeof(TCHAR*));
33        GOTO_CLEANUP_IF_NULL(szFieldKey, _T("Failed to allocate memory for field key\n"));
34        if (PtxPdfForms_FieldNodeMap_GetKey(pInFields, iField, szFieldKey, nKey) != nKey)
35        {
36            GOTO_CLEANUP_IF_ERROR_PRINT_ERROR(_T("Failed to get form field key. %s (ErrorCode: 0x%08x)\n"), szErrorBuff,
37                                              Ptx_GetLastError());
38        }
39        // Get input field node
40        pInFieldNode = PtxPdfForms_FieldNodeMap_GetValue(pInFields, iField);
41        GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInFieldNode, _T("Failed to get form field. %s (ErrorCode: 0x%08x)\n"),
42                                         szErrorBuff, Ptx_GetLastError());
43        // Copy field node to output document
44        pOutFieldNode = PtxPdfForms_FieldNode_Copy(pOutDoc, pInFieldNode);
45        GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutFieldNode, _T("Failed to copy form field. %s (ErrorCode: 0x%08x)\n"),
46                                         szErrorBuff, Ptx_GetLastError());
47        // Add copied field node to output fields
48        GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdfForms_FieldNodeMap_Set(pOutFields, szFieldKey, pOutFieldNode),
49                                          _T("Failed to add form field \"%s\". %s (ErrorCode: 0x%08x)\n"), szFieldKey,
50                                          szErrorBuff, Ptx_GetLastError());
51        // Clean up for next iteration
52        free(szFieldKey);
53        szFieldKey = NULL;
54        Ptx_Release(pOutFieldNode);
55        pOutFieldNode = NULL;
56        Ptx_Release(pInFieldNode);
57        pInFieldNode = NULL;
58    }
59
60cleanup:
61    if (pOutFieldNode != NULL)
62        Ptx_Release(pOutFieldNode);
63    if (pInFieldNode != NULL)
64        Ptx_Release(pInFieldNode);
65    if (szFieldKey != NULL)
66        free(szFieldKey);
67    if (pOutFields != NULL)
68        Ptx_Release(pOutFields);
69    if (pInFields != NULL)
70        Ptx_Release(pInFields);
71    return iReturnValue;
72}
1int fillFormField(TPtxPdfForms_Field* pField, const TCHAR* szValue)
2{
3    // Objects that need releasing or closing
4    TPtxPdfForms_RadioButtonList* pButtonList     = NULL;
5    TPtxPdfForms_RadioButton*     pButton         = NULL;
6    TPtxPdfForms_ChoiceItemList*  pChoiceItemList = NULL;
7    TPtxPdfForms_ChoiceItem*      pItem           = NULL;
8    TCHAR*                        szName          = NULL;
9
10    // Other variables
11    TPtxPdfForms_FieldType         iType             = 0;
12    TPtxPdfForms_CheckBox*         pCheckBox         = NULL;
13    TPtxPdfForms_RadioButtonGroup* pRadioButtonGroup = NULL;
14
15    iReturnValue = 0;
16    iType        = PtxPdfForms_Field_GetType(pField);
17
18    if (iType == ePtxPdfForms_FieldType_GeneralTextField || iType == ePtxPdfForms_FieldType_CombTextField)
19    {
20        GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdfForms_TextField_SetText((TPtxPdfForms_TextField*)pField, szValue),
21                                          _T("Failed to set text field value. %s (ErrorCode: 0x%08x)\n"), szErrorBuff,
22                                          Ptx_GetLastError());
23    }
24    else if (iType == ePtxPdfForms_FieldType_CheckBox)
25    {
26        pCheckBox = (TPtxPdfForms_CheckBox*)pField;
27        if (_tcscmp(szValue, _T("on")) == 0)
28        {
29            GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdfForms_CheckBox_SetChecked(pCheckBox, TRUE),
30                                              _T("Failed to set check box. %s (ErrorCode: 0x%08x)\n"), szErrorBuff,
31                                              Ptx_GetLastError());
32        }
33        else
34        {
35            GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdfForms_CheckBox_SetChecked(pCheckBox, FALSE),
36                                              _T("Failed to set check box. %s (ErrorCode: 0x%08x)\n"), szErrorBuff,
37                                              Ptx_GetLastError());
38        }
39    }
40    else if (iType == ePtxPdfForms_FieldType_RadioButtonGroup)
41    {
42        pRadioButtonGroup = (TPtxPdfForms_RadioButtonGroup*)pField;
43        pButtonList       = PtxPdfForms_RadioButtonGroup_GetButtons(pRadioButtonGroup);
44        for (int iButton = 0; iButton < PtxPdfForms_RadioButtonList_GetCount(pButtonList); iButton++)
45        {
46            pButton = PtxPdfForms_RadioButtonList_Get(pButtonList, iButton);
47            GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pButton, _T("Failed to get radio button. %s (ErrorCode: 0x%08x)\n"),
48                                             szErrorBuff, Ptx_GetLastError())
49            size_t nName = PtxPdfForms_RadioButton_GetExportName(pButton, szName, 0);
50            GOTO_CLEANUP_IF_ZERO(nName, _T("Failed to get radio button name\n"));
51            szName = (TCHAR*)malloc(nName * sizeof(TCHAR*));
52            GOTO_CLEANUP_IF_NULL(szName, _T("Failed to allocate memory for radio button name\n"));
53            if (PtxPdfForms_RadioButton_GetExportName(pButton, szName, nName) != nName)
54            {
55                GOTO_CLEANUP_IF_ERROR_PRINT_ERROR(_T("Failed to get radio button name. %s (ErrorCode: 0x%08x)\n"),
56                                                  szErrorBuff, Ptx_GetLastError());
57            }
58            if (_tcscmp(szValue, szName) == 0)
59            {
60                GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(
61                    PtxPdfForms_RadioButtonGroup_SetChosenButton(pRadioButtonGroup, pButton),
62                    _T("Failed to set radio button. %s (ErrorCode: 0x%08x)\n"), szErrorBuff, Ptx_GetLastError());
63            }
64            free(szName);
65            szName = NULL;
66            Ptx_Release(pButton);
67            pButton = NULL;
68        }
69    }
70    else if (iType == ePtxPdfForms_FieldType_ComboBox || iType == ePtxPdfForms_FieldType_ListBox)
71    {
72        pChoiceItemList = PtxPdfForms_ChoiceField_GetItems((TPtxPdfForms_ChoiceField*)pField);
73        for (int iItem = 0; iItem < PtxPdfForms_ChoiceItemList_GetCount(pChoiceItemList); iItem++)
74        {
75            pItem = PtxPdfForms_ChoiceItemList_Get(pChoiceItemList, iItem);
76            GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pItem,
77                                             _T("Failed to get item from choice field. %s (ErrorCode: 0x%08x)\n"),
78                                             szErrorBuff, Ptx_GetLastError());
79            size_t nName = PtxPdfForms_ChoiceItem_GetDisplayName(pItem, szName, 0);
80            GOTO_CLEANUP_IF_ZERO(nName, _T("Failed to get choice item name\n"));
81            szName = (TCHAR*)malloc(nName * sizeof(TCHAR*));
82            GOTO_CLEANUP_IF_NULL(szName, _T("Failed to allocate memory for choice item name\n"));
83            if (PtxPdfForms_ChoiceItem_GetDisplayName(pItem, szName, nName) != nName)
84            {
85                GOTO_CLEANUP_IF_ERROR_PRINT_ERROR(_T("Failed to get choice item name. %s (ErrorCode: 0x%08x)\n"),
86                                                  szErrorBuff, Ptx_GetLastError());
87            }
88            if (_tcscmp(szValue, szName) == 0)
89            {
90                break;
91            }
92            free(szName);
93            szName = NULL;
94            Ptx_Release(pItem);
95            pItem = NULL;
96        }
97        if (pItem != NULL)
98        {
99            free(szName);
100            szName = NULL;
101            if (iType == ePtxPdfForms_FieldType_ComboBox)
102            {
103                GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(
104                    PtxPdfForms_ComboBox_SetChosenItem((TPtxPdfForms_ComboBox*)pField, pItem),
105                    _T("Failed to set choice item for combo box. %s (ErrorCode: 0x%08x)\n"), szErrorBuff,
106                    Ptx_GetLastError());
107            }
108            else // iType == ePtxPdfForms_FieldType_ListBox
109            {
110                Ptx_Release(pChoiceItemList);
111                pChoiceItemList = PtxPdfForms_ListBox_GetChosenItems((TPtxPdfForms_ListBox*)pField);
112                GOTO_CLEANUP_IF_NULL_PRINT_ERROR(
113                    pChoiceItemList, _T("Failed to get list of chosen items for list box. %s (ErrorCode: 0x%08x)\n"),
114                    szErrorBuff, Ptx_GetLastError());
115                GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(
116                    PtxPdfForms_ChoiceItemList_Clear(pChoiceItemList),
117                    _T("Failed to clear list of chosen items for list box. %s (ErrorCode: 0x%08x)\n"), szErrorBuff,
118                    Ptx_GetLastError());
119                GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(
120                    PtxPdfForms_ChoiceItemList_Add(pChoiceItemList, pItem),
121                    _T("Failed to add item to list of chosen items for list box. %s (ErrorCode: 0x%08x)\n"),
122                    szErrorBuff, Ptx_GetLastError());
123            }
124        }
125    }
126
127cleanup:
128    if (szName != NULL)
129        free(szName);
130    if (pItem == NULL)
131        Ptx_Release(pItem);
132    if (pChoiceItemList == NULL)
133        Ptx_Release(pChoiceItemList);
134    if (pButton != NULL)
135        Ptx_Release(pButton);
136    if (pButtonList != NULL)
137        Ptx_Release(pButton);
138
139    return iReturnValue;
140}
Download code sample
1// Open input document
2using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
3using (Document inDoc = Document.Open(inStream, null))
4
5// Create output document
6using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
7using (Document outDoc = Document.Create(outStream, inDoc.Conformance, null))
8{
9    // Copy document-wide data
10    CopyDocumentData(inDoc, outDoc);
11
12    FieldNodeMap outFields = outDoc.FormFields;
13
14    // Copy all form fields
15    FieldNodeMap inFields = inDoc.FormFields;
16    foreach (var inPair in inFields)
17    {
18        FieldNode inFieldNode = inPair.Value;
19        FieldNode outFormFieldNode = FieldNode.Copy(outDoc, inFieldNode);
20        outFields.Add(inPair.Key, outFormFieldNode);
21    }
22
23    // Find the given field, exception thrown if not found
24    var selectedNode = outFields.Lookup(fieldIdentifier);
25    if (selectedNode is Field selectedField)
26        FillFormField(selectedField, fieldValue);
27
28    // Configure copying options for updating existing widgets and removing signature fields
29    PageCopyOptions copyOptions = new PageCopyOptions
30    {
31        FormFields = FormFieldCopyStrategy.CopyAndUpdateWidgets,
32        UnsignedSignatures = CopyStrategy.Remove,
33    };
34
35    // Copy all pages and append to output document
36    PageList copiedPages = PageList.Copy(outDoc, inDoc.Pages, copyOptions);
37    outDoc.Pages.AddRange(copiedPages);
38}
1private static void CopyDocumentData(Document inDoc, Document outDoc)
2{
3    // Copy document-wide data
4
5    // Output intent
6    if (inDoc.OutputIntent != null)
7        outDoc.OutputIntent = IccBasedColorSpace.Copy(outDoc, inDoc.OutputIntent);
8
9    // Metadata
10    outDoc.Metadata = Metadata.Copy(outDoc, inDoc.Metadata);
11
12    // Viewer settings
13    outDoc.ViewerSettings = ViewerSettings.Copy(outDoc, inDoc.ViewerSettings);
14
15    // Associated files (for PDF/A-3 and PDF 2.0 only)
16    FileReferenceList outAssociatedFiles = outDoc.AssociatedFiles;
17    foreach (FileReference inFileRef in inDoc.AssociatedFiles)
18        outAssociatedFiles.Add(FileReference.Copy(outDoc, inFileRef));
19
20    // Plain embedded files
21    FileReferenceList outEmbeddedFiles = outDoc.PlainEmbeddedFiles;
22    foreach (FileReference inFileRef in inDoc.PlainEmbeddedFiles)
23        outEmbeddedFiles.Add(FileReference.Copy(outDoc, inFileRef));
24}
1static void FillFormField(Field formField, string value)
2{
3    // Apply the value, depending on the field type
4    if (formField is TextField textField)
5    {
6        // Set the text
7        textField.Text = value;
8    }
9    else if (formField is CheckBox checkBox)
10    {
11        // Check or un-check
12        checkBox.Checked = "on".Equals(value, StringComparison.CurrentCultureIgnoreCase);
13    }
14    else if (formField is RadioButtonGroup group)
15    {
16        // Search the buttons for given name
17        foreach (var button in group.Buttons)
18        {
19            if (value.Equals(button.ExportName))
20            {
21                // Found: Select this button
22                group.ChosenButton = button;
23                break;
24            }
25        }
26    }
27    else if (formField is ComboBox comboBox)
28    {
29        // Search for the given item
30        foreach (var item in comboBox.Items)
31        {
32            if (value.Equals(item.DisplayName))
33            {
34                // Found: Select this item.
35                comboBox.ChosenItem = item;
36                break;
37            }
38        }
39    }
40    else if (formField is ListBox listBox)
41    {
42        // Search for the given item
43        foreach (var item in listBox.Items)
44        {
45            if (value.Equals(item.DisplayName))
46            {
47                // Found: Set this item as the only selected item
48                var itemList = listBox.ChosenItems;
49                itemList.Clear();
50                itemList.Add(item);
51                break;
52            }
53        }
54    }
55}
Download code sample
1try (// Open input document
2    FileStream inStream = new FileStream(inPath, FileStream.Mode.READ_ONLY);
3    Document inDoc = Document.open(inStream, null);
4    FileStream outStream = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW)) {
5    try (// Create output document
6        Document outDoc = Document.create(outStream, inDoc.getConformance(), null)) {
7
8        // Copy document-wide data
9        copyDocumentData(inDoc, outDoc);
10
11        // Copy all form fields
12        FieldNodeMap inFormFields = inDoc.getFormFields();
13        FieldNodeMap outFormFields = outDoc.getFormFields();
14        for (Entry<String, FieldNode> entry : inFormFields.entrySet())
15            outFormFields.put(entry.getKey(), FieldNode.copy(outDoc, entry.getValue()));
16
17        // Find the given field, exception thrown if not found
18        Field selectedField = (Field) outFormFields.lookup(fieldIdentifier);
19        fillFormField(selectedField, fieldValue);
20
21        // Configure copying options for updating existing widgets and removing signature fields
22        PageCopyOptions copyOptions = new PageCopyOptions();
23        copyOptions.setFormFields(FormFieldCopyStrategy.COPY_AND_UPDATE_WIDGETS);
24        copyOptions.setUnsignedSignatures(CopyStrategy.REMOVE);
25
26        // Copy all pages and append to output document
27        PageList copiedPages = PageList.copy(outDoc, inDoc.getPages(), copyOptions);
28        outDoc.getPages().addAll(copiedPages);
29    }
30}
1private static void copyDocumentData(Document inDoc, Document outDoc) throws ToolboxException, IOException {
2    // Copy document-wide data
3
4    // Output intent
5    if (inDoc.getOutputIntent() != null)
6        outDoc.setOutputIntent(IccBasedColorSpace.copy(outDoc, inDoc.getOutputIntent()));
7
8    // Metadata
9    outDoc.setMetadata(Metadata.copy(outDoc, inDoc.getMetadata()));
10
11    // Viewer settings
12    outDoc.setViewerSettings(ViewerSettings.copy(outDoc, inDoc.getViewerSettings()));
13
14    // Associated files (for PDF/A-3 and PDF 2.0 only)
15    FileReferenceList outAssociatedFiles = outDoc.getAssociatedFiles();
16    for (FileReference inFileRef : inDoc.getAssociatedFiles())
17        outAssociatedFiles.add(FileReference.copy(outDoc, inFileRef));
18
19    // Plain embedded files
20    FileReferenceList outEmbeddedFiles = outDoc.getPlainEmbeddedFiles();
21    for (FileReference inFileRef : inDoc.getPlainEmbeddedFiles())
22        outEmbeddedFiles.add(FileReference.copy(outDoc, inFileRef));
23}
1private static void fillFormField(Field formField, String value) throws ToolboxException {
2    // Apply the value, depending on the field type
3    if (formField instanceof TextField) {
4        // Set the text
5        TextField textField = (TextField) formField;
6        textField.setText(value);
7    } else if (formField instanceof CheckBox) {
8        // Check or un-check
9        CheckBox checkBox = (CheckBox) formField;
10        checkBox.setChecked(value.equalsIgnoreCase("on"));
11    } else if (formField instanceof RadioButtonGroup) {
12        // Search the buttons for given name
13        RadioButtonGroup group = (RadioButtonGroup) formField;
14        for (RadioButton button : group.getButtons()) {
15            if (value.equals(button.getExportName())) {
16                // Found: Select this button
17                group.setChosenButton(button);
18                break;
19            }
20        }
21    } else if (formField instanceof ComboBox) {
22        // Search for the given item
23        ComboBox comboBox = (ComboBox) formField;
24        for (ChoiceItem item : comboBox.getItems()) {
25            if (value.equals(item.getDisplayName())) {
26                // Found: Select this item
27                comboBox.setChosenItem(item);
28                break;
29            }
30        }
31    } else if (formField instanceof ListBox) {
32        // Search for the given item
33        ListBox listBox = (ListBox) formField;
34        for (ChoiceItem item : listBox.getItems()) {
35            if (value.equals(item.getDisplayName())) {
36                // Found: Set this item as the only selected item
37                ChoiceItemList itemList = listBox.getChosenItems();
38                itemList.clear();
39                itemList.add(item);
40                break;
41            }
42        }
43    }
44}
Download code sample

Content Addition

Add barcode to PDF

1// Open input document
2pInStream = _tfopen(szInPath, _T("rb"));
3GOTO_CLEANUP_IF_NULL(pInStream, _T("Failed to open input file \"%s\".\n"), szInPath);
4PtxSysCreateFILEStreamDescriptor(&descriptor, pInStream, 0);
5pInDoc = PtxPdf_Document_Open(&descriptor, _T(""));
6GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInDoc, _T("Input file \"%s\" cannot be opened. %s (ErrorCode: 0x%08x).\n"),
7                                 szInPath, szErrorBuff, Ptx_GetLastError());
8
9// Create file stream
10pFontStream = _tfopen(szFontPath, _T("rb"));
11GOTO_CLEANUP_IF_NULL(pFontStream, _T("Failed to open font file."));
12PtxSysCreateFILEStreamDescriptor(&fontDescriptor, pFontStream, 0);
13
14// Create output document
15pOutStream = _tfopen(szOutPath, _T("wb+"));
16GOTO_CLEANUP_IF_NULL(pOutStream, _T("Failed to open output file \"%s\".\n"), szOutPath);
17PtxSysCreateFILEStreamDescriptor(&outDescriptor, pOutStream, 0);
18iConformance = PtxPdf_Document_GetConformance(pInDoc);
19pOutDoc      = PtxPdf_Document_Create(&outDescriptor, &iConformance, NULL);
20GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("Output file \"%s\" cannot be created. %s (ErrorCode: 0x%08x).\n"),
21                                 szOutPath, szErrorBuff, Ptx_GetLastError());
22pFont = PtxPdfContent_Font_Create(pOutDoc, &fontDescriptor, TRUE);
23GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pFont, _T("Failed to create font. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
24                                 Ptx_GetLastError());
25
26// Copy document-wide data
27GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(copyDocumentData(pInDoc, pOutDoc),
28                                  _T("Failed to copy document-wide data. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
29                                  Ptx_GetLastError());
30
31// Configure copy options
32pCopyOptions = PtxPdf_PageCopyOptions_New();
33
34// Get page lists of input and output document
35pInPageList = PtxPdf_Document_GetPages(pInDoc);
36GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPageList,
37                                 _T("Failed to get the pages of the input document. %s (ErrorCode: 0x%08x).\n"),
38                                 szErrorBuff, Ptx_GetLastError());
39pOutPageList = PtxPdf_Document_GetPages(pOutDoc);
40GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPageList,
41                                 _T("Failed to get the pages of the output document. %s (ErrorCode: 0x%08x).\n"),
42                                 szErrorBuff, Ptx_GetLastError());
43
44// Copy first page
45pInPage = PtxPdf_PageList_Get(pInPageList, 0);
46GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPage, _T("Failed to get the first page. %s (ErrorCode: 0x%08x).\n"),
47                                 szErrorBuff, Ptx_GetLastError());
48pOutPage = PtxPdf_Page_Copy(pOutDoc, pInPage, pCopyOptions);
49GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPage, _T("Failed to copy page. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
50                                 Ptx_GetLastError());
51
52// Add barcode image to copied page
53if (addBarcode(pOutDoc, pOutPage, szBarcode, pFont, 50) != 0)
54    goto cleanup;
55
56// Add page to output document
57GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_PageList_Add(pOutPageList, pOutPage),
58                                  _T("Failed to add page to output document. %s (ErrorCode: 0x%08x).\n"),
59                                  szErrorBuff, Ptx_GetLastError());
60
61// Get remaining pages from input
62pInPageRange = PtxPdf_PageList_GetRange(pInPageList, 1, PtxPdf_PageList_GetCount(pInPageList) - 1);
63GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPageRange,
64                                 _T("Failed to get page range from input document. %s (ErrorCode: 0x%08x).\n"),
65                                 szErrorBuff, Ptx_GetLastError());
66
67// Copy remaining pages to output
68pOutPageRange = PtxPdf_PageList_Copy(pOutDoc, pInPageRange, pCopyOptions);
69GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPageRange,
70                                 _T("Failed to copy page range to output document. %s (ErrorCode: 0x%08x).\n"),
71                                 szErrorBuff, Ptx_GetLastError());
72
73// Add the copied pages to the output document
74GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_PageList_AddRange(pOutPageList, pOutPageRange),
75                                  _T("Failed to add page range to output page list. %s (ErrorCode: 0x%08x).\n"),
76                                  szErrorBuff, Ptx_GetLastError());
77
1int copyDocumentData(TPtxPdf_Document* pInDoc, TPtxPdf_Document* pOutDoc)
2{
3    TPtxPdf_FileReferenceList* pInFileRefList;
4    TPtxPdf_FileReferenceList* pOutFileRefList;
5
6    // Output intent
7    if (PtxPdf_Document_GetOutputIntent(pInDoc) != NULL)
8        if (PtxPdf_Document_SetOutputIntent(pOutDoc, PtxPdfContent_IccBasedColorSpace_Copy(
9                                                         pOutDoc, PtxPdf_Document_GetOutputIntent(pInDoc))) == FALSE)
10            return FALSE;
11
12    // Metadata
13    if (PtxPdf_Document_SetMetadata(pOutDoc, PtxPdf_Metadata_Copy(pOutDoc, PtxPdf_Document_GetMetadata(pInDoc))) ==
14        FALSE)
15        return FALSE;
16
17    // Viewer settings
18    if (PtxPdf_Document_SetViewerSettings(
19            pOutDoc, PtxPdfNav_ViewerSettings_Copy(pOutDoc, PtxPdf_Document_GetViewerSettings(pInDoc))) == FALSE)
20        return FALSE;
21
22    // Associated files (for PDF/A-3 and PDF 2.0 only)
23    pInFileRefList  = PtxPdf_Document_GetAssociatedFiles(pInDoc);
24    pOutFileRefList = PtxPdf_Document_GetAssociatedFiles(pOutDoc);
25    if (pInFileRefList == NULL || pOutFileRefList == NULL)
26        return FALSE;
27    for (int iFileRef = 0; iFileRef < PtxPdf_FileReferenceList_GetCount(pInFileRefList); iFileRef++)
28        if (PtxPdf_FileReferenceList_Add(
29                pOutFileRefList,
30                PtxPdf_FileReference_Copy(pOutDoc, PtxPdf_FileReferenceList_Get(pInFileRefList, iFileRef))) == FALSE)
31            return FALSE;
32
33    // Plain embedded files
34    pInFileRefList  = PtxPdf_Document_GetPlainEmbeddedFiles(pInDoc);
35    pOutFileRefList = PtxPdf_Document_GetPlainEmbeddedFiles(pOutDoc);
36    if (pInFileRefList == NULL || pOutFileRefList == NULL)
37        return FALSE;
38    for (int iFileRef = 0; iFileRef < PtxPdf_FileReferenceList_GetCount(pInFileRefList); iFileRef++)
39        if (PtxPdf_FileReferenceList_Add(
40                pOutFileRefList,
41                PtxPdf_FileReference_Copy(pOutDoc, PtxPdf_FileReferenceList_Get(pInFileRefList, iFileRef))) == FALSE)
42            return FALSE;
43
44    return TRUE;
45}
1int addBarcode(TPtxPdf_Document* pOutDoc, TPtxPdf_Page* pOutPage, TCHAR* szBarcode, TPtxPdfContent_Font* pFont,
2               double dFontSize)
3{
4    TPtxPdfContent_Content*          pContent       = NULL;
5    TPtxPdfContent_ContentGenerator* pGenerator     = NULL;
6    TPtxPdfContent_Text*             pBarcodeText   = NULL;
7    TPtxPdfContent_TextGenerator*    pTextGenerator = NULL;
8
9    pContent = PtxPdf_Page_GetContent(pOutPage);
10
11    // Create content generator
12    pGenerator = PtxPdfContent_ContentGenerator_New(pContent, FALSE);
13    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pGenerator, _T("Failed to create a content generator. %s (ErrorCode: 0x%08x).\n"),
14                                     szErrorBuff, Ptx_GetLastError());
15
16    // Create text object
17    pBarcodeText = PtxPdfContent_Text_Create(pOutDoc);
18    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pBarcodeText, _T("Failed to create a text object. %s (ErrorCode: 0x%08x).\n"),
19                                     szErrorBuff, Ptx_GetLastError());
20
21    // Create text generator
22    pTextGenerator = PtxPdfContent_TextGenerator_New(pBarcodeText, pFont, dFontSize, NULL);
23    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pTextGenerator, _T("Failed to create a text generator. %s (ErrorCode: 0x%08x).\n"),
24                                     szErrorBuff, Ptx_GetLastError());
25
26    // Calculate position
27    TPtxGeomReal_Size size;
28    PtxPdf_Page_GetSize(pOutPage, &size);
29    TPtxGeomReal_Point position;
30    double             dTextWidth = PtxPdfContent_TextGenerator_GetWidth(pTextGenerator, szBarcode);
31    GOTO_CLEANUP_IF_NEGATIVE_PRINT_ERROR(dTextWidth, _T("%s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
32    double dFontAscent = PtxPdfContent_Font_GetAscent(pFont);
33    GOTO_CLEANUP_IF_NEGATIVE_PRINT_ERROR(dFontAscent, _T("%s(ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
34    double dFontDescent = PtxPdfContent_Font_GetDescent(pFont);
35    GOTO_CLEANUP_IF_NEGATIVE_PRINT_ERROR(dFontDescent, _T("%s (ErrorCode: 0x%08x).\n"), szErrorBuff,
36                                         Ptx_GetLastError());
37    position.dX = size.dWidth - (dTextWidth + dBorder);
38    position.dY = size.dHeight - (dFontSize * (dFontAscent + dFontDescent) + dBorder);
39
40    // Move to position
41    GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdfContent_TextGenerator_MoveTo(pTextGenerator, &position),
42                                      _T("Failed to move to position %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
43                                      Ptx_GetLastError());
44    // Add given barcode string
45    GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdfContent_TextGenerator_ShowLine(pTextGenerator, szBarcode),
46                                      _T("Failed to add barcode string. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
47                                      Ptx_GetLastError());
48
49    // Close text generator
50    if (pTextGenerator != NULL)
51        PtxPdfContent_TextGenerator_Close(pTextGenerator);
52
53    // Paint the positioned barcode text
54    GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdfContent_ContentGenerator_PaintText(pGenerator, pBarcodeText),
55                                      _T("Failed to paint the positioned barcode text. %s (ErrorCode: 0x%08x).\n"),
56                                      szErrorBuff, Ptx_GetLastError());
57
58cleanup:
59    if (pGenerator != NULL)
60        PtxPdfContent_ContentGenerator_Close(pGenerator);
61
62    return iReturnValue;
63}
Download code sample
1// Open input document
2using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
3using (Document inDoc = Document.Open(inStream, null))
4
5// Create file stream
6using (Stream fontStream = new FileStream(fontPath, FileMode.Open, FileAccess.Read))
7
8// Create output document
9using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
10using (Document outDoc = Document.Create(outStream, inDoc.Conformance, null))
11{
12    // Copy document-wide data
13    CopyDocumentData(inDoc, outDoc);
14
15    // Create embedded font in output document
16    Font font = Font.Create(outDoc, fontStream, true);
17
18    // Define page copy options
19    PageCopyOptions copyOptions = new PageCopyOptions();
20
21    // Copy first page, add barcode, and append to output document
22    Page outPage = Page.Copy(outDoc, inDoc.Pages[0], copyOptions);
23    AddBarcode(outDoc, outPage, barcode, font, 50);
24    outDoc.Pages.Add(outPage);
25
26    // Copy remaining pages and append to output document
27    PageList inPageRange = inDoc.Pages.GetRange(1, inDoc.Pages.Count - 1);
28    PageList copiedPages = PageList.Copy(outDoc, inPageRange, copyOptions);
29    outDoc.Pages.AddRange(copiedPages);
30}
1private static void CopyDocumentData(Document inDoc, Document outDoc)
2{
3    // Copy document-wide data
4
5    // Output intent
6    if (inDoc.OutputIntent != null)
7        outDoc.OutputIntent = IccBasedColorSpace.Copy(outDoc, inDoc.OutputIntent);
8
9    // Metadata
10    outDoc.Metadata = Metadata.Copy(outDoc, inDoc.Metadata);
11
12    // Viewer settings
13    outDoc.ViewerSettings = ViewerSettings.Copy(outDoc, inDoc.ViewerSettings);
14
15    // Associated files (for PDF/A-3 and PDF 2.0 only)
16    FileReferenceList outAssociatedFiles = outDoc.AssociatedFiles;
17    foreach (FileReference inFileRef in inDoc.AssociatedFiles)
18        outAssociatedFiles.Add(FileReference.Copy(outDoc, inFileRef));
19
20    // Plain embedded files
21    FileReferenceList outEmbeddedFiles = outDoc.PlainEmbeddedFiles;
22    foreach (FileReference inFileRef in inDoc.PlainEmbeddedFiles)
23        outEmbeddedFiles.Add(FileReference.Copy(outDoc, inFileRef));
24}
1private static void AddBarcode(Document outputDoc, Page outPage, string barcode,
2    Font font, double fontSize)
3{
4    // Create content generator 
5    using ContentGenerator gen = new ContentGenerator(outPage.Content, false);
6
7    // Create text object
8    Text barcodeText = Text.Create(outputDoc);
9
10    // Create text generator
11    using (TextGenerator textGenerator = new TextGenerator(barcodeText, font, fontSize, null))
12    {
13        // Calculate position
14        Point position = new Point
15        {
16            X = outPage.Size.Width - (textGenerator.GetWidth(barcode) + Border),
17            Y = outPage.Size.Height - (fontSize * (font.Ascent + font.Descent) + Border)
18        };
19
20        // Move to position
21        textGenerator.MoveTo(position);
22        // Add given barcode string
23        textGenerator.ShowLine(barcode);
24    }
25    // Paint the positioned barcode text
26    gen.PaintText(barcodeText);
27}
Download code sample
1try (// Open input document
2    FileStream inStream = new FileStream(inPath, FileStream.Mode.READ_ONLY);
3    Document inDoc = Document.open(inStream, null);
4    // Create file stream
5    FileStream fontStream = new FileStream(fontPath, FileStream.Mode.READ_ONLY);
6    FileStream outStream = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW)) {
7    try (// Create output document
8        Document outDoc = Document.create(outStream, inDoc.getConformance(), null)) {
9
10        // Copy document-wide data
11        copyDocumentData(inDoc, outDoc);
12
13        // Create embedded font in output document
14        Font font = Font.create(outDoc, fontStream, true);
15
16        // Define page copy options
17        PageCopyOptions copyOptions = new PageCopyOptions();
18
19        // Copy first page, add barcode, and append to output document
20        Page outPage = Page.copy(outDoc, inDoc.getPages().get(0), copyOptions);
21        addBarcode(outDoc, outPage, barcode, font, 50);
22        outDoc.getPages().add(outPage);
23
24        // Copy remaining pages and append to output document
25        PageList inPageRange = inDoc.getPages().subList(1, inDoc.getPages().size());
26        PageList copiedPages = PageList.copy(outDoc, inPageRange, copyOptions);
27        outDoc.getPages().addAll(copiedPages);
28    }
29}
1private static void copyDocumentData(Document inDoc, Document outDoc) throws ToolboxException, IOException {
2    // Copy document-wide data
3
4    // Output intent
5    if (inDoc.getOutputIntent() != null)
6        outDoc.setOutputIntent(IccBasedColorSpace.copy(outDoc, inDoc.getOutputIntent()));
7
8    // Metadata
9    outDoc.setMetadata(Metadata.copy(outDoc, inDoc.getMetadata()));
10
11    // Viewer settings
12    outDoc.setViewerSettings(ViewerSettings.copy(outDoc, inDoc.getViewerSettings()));
13
14    // Associated files (for PDF/A-3 and PDF 2.0 only)
15    FileReferenceList outAssociatedFiles = outDoc.getAssociatedFiles();
16    for (FileReference inFileRef : inDoc.getAssociatedFiles())
17        outAssociatedFiles.add(FileReference.copy(outDoc, inFileRef));
18
19    // Plain embedded files
20    FileReferenceList outEmbeddedFiles = outDoc.getPlainEmbeddedFiles();
21    for (FileReference inFileRef : inDoc.getPlainEmbeddedFiles())
22        outEmbeddedFiles.add(FileReference.copy(outDoc, inFileRef));
23}
1private static void addBarcode(Document outputDoc, Page outPage, String barcode, Font font, double fontSize) throws ToolboxException, IOException {
2    try (// Create content generator
3        ContentGenerator generator = new ContentGenerator(outPage.getContent(), false)) {
4        // Create text object
5        Text barcodeText = Text.create(outputDoc);
6
7        // Create a text generator
8        TextGenerator textgenerator = new TextGenerator(barcodeText, font, fontSize, null);
9
10        // Calculate position
11        Point position = new Point(outPage.getSize().width - (textgenerator.getWidth(barcode) + Border),
12                outPage.getSize().height - (fontSize * (font.getAscent() + font.getDescent()) + Border));
13
14        // Move to position
15        textgenerator.moveTo(position);
16        // Add given barcode string
17        textgenerator.showLine(barcode);
18        // Close text generator
19        textgenerator.close();
20
21        // Paint the positioned barcode text
22        generator.paintText(barcodeText);
23    }
24}
Download code sample

Add Data Matrix to PDF

1// Open input document
2pInStream = _tfopen(szInPath, _T("rb"));
3GOTO_CLEANUP_IF_NULL(pInStream, _T("Failed to open input file \"%s\".\n"), szInPath);
4PtxSysCreateFILEStreamDescriptor(&descriptor, pInStream, 0);
5pInDoc = PtxPdf_Document_Open(&descriptor, _T(""));
6GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInDoc, _T("Input file \"%s\" cannot be opened. %s (ErrorCode: 0x%08x).\n"),
7                                 szInPath, szErrorBuff, Ptx_GetLastError());
8
9// Create output document
10pOutStream = _tfopen(szOutPath, _T("wb+"));
11GOTO_CLEANUP_IF_NULL(pOutStream, _T("Failed to open output file \"%s\".\n"), szOutPath);
12PtxSysCreateFILEStreamDescriptor(&outDescriptor, pOutStream, 0);
13iConformance = PtxPdf_Document_GetConformance(pInDoc);
14pOutDoc      = PtxPdf_Document_Create(&outDescriptor, &iConformance, NULL);
15GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("Output file \"%s\" cannot be created. %s (ErrorCode: 0x%08x).\n"),
16                                 szOutPath, szErrorBuff, Ptx_GetLastError());
17
18// Create embedded font in output document
19pFont = PtxPdfContent_Font_CreateFromSystem(pOutDoc, _T("Arial"), _T("Italic"), TRUE);
20GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pFont, _T("Failed to create font. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
21                                 Ptx_GetLastError());
22
23// Copy document-wide data
24GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(copyDocumentData(pInDoc, pOutDoc),
25                                  _T("Failed to copy document-wide data. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
26                                  Ptx_GetLastError());
27
28// Configure copy options
29pCopyOptions = PtxPdf_PageCopyOptions_New();
30
31// Get page lists of input and output document
32pInPageList = PtxPdf_Document_GetPages(pInDoc);
33GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPageList,
34                                 _T("Failed to get the pages of the input document. %s (ErrorCode: 0x%08x).\n"),
35                                 szErrorBuff, Ptx_GetLastError());
36pOutPageList = PtxPdf_Document_GetPages(pOutDoc);
37GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPageList,
38                                 _T("Failed to get the pages of the output document. %s (ErrorCode: 0x%08x).\n"),
39                                 szErrorBuff, Ptx_GetLastError());
40
41// Copy first page
42pInPage = PtxPdf_PageList_Get(pInPageList, 0);
43GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPage, _T("Failed to get the first page. %s (ErrorCode: 0x%08x).\n"),
44                                 szErrorBuff, Ptx_GetLastError());
45pOutPage = PtxPdf_Page_Copy(pOutDoc, pInPage, pCopyOptions);
46GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPage, _T("Failed to copy page. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
47                                 Ptx_GetLastError());
48
49// Add datamatrix image to copied page
50if (addDataMatrix(pOutDoc, pOutPage, szDatamatrixPath) != 0)
51    goto cleanup;
52
53// Add page to output document
54GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_PageList_Add(pOutPageList, pOutPage),
55                                  _T("Failed to add page to output document. %s (ErrorCode: 0x%08x).\n"),
56                                  szErrorBuff, Ptx_GetLastError());
57
58// Get remaining pages from input
59pInPageRange = PtxPdf_PageList_GetRange(pInPageList, 1, PtxPdf_PageList_GetCount(pInPageList) - 1);
60GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPageRange,
61                                 _T("Failed to get page range from input document. %s (ErrorCode: 0x%08x).\n"),
62                                 szErrorBuff, Ptx_GetLastError());
63
64// Copy remaining pages to output
65pOutPageRange = PtxPdf_PageList_Copy(pOutDoc, pInPageRange, pCopyOptions);
66GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPageRange,
67                                 _T("Failed to copy page range to output document. %s (ErrorCode: 0x%08x).\n"),
68                                 szErrorBuff, Ptx_GetLastError());
69
70// Add the copied pages to the output document
71GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_PageList_AddRange(pOutPageList, pOutPageRange),
72                                  _T("Failed to add page range to output page list. %s (ErrorCode: 0x%08x).\n"),
73                                  szErrorBuff, Ptx_GetLastError());
74
1int copyDocumentData(TPtxPdf_Document* pInDoc, TPtxPdf_Document* pOutDoc)
2{
3    TPtxPdf_FileReferenceList* pInFileRefList;
4    TPtxPdf_FileReferenceList* pOutFileRefList;
5
6    // Output intent
7    if (PtxPdf_Document_GetOutputIntent(pInDoc) != NULL)
8        if (PtxPdf_Document_SetOutputIntent(pOutDoc, PtxPdfContent_IccBasedColorSpace_Copy(
9                                                         pOutDoc, PtxPdf_Document_GetOutputIntent(pInDoc))) == FALSE)
10            return FALSE;
11
12    // Metadata
13    if (PtxPdf_Document_SetMetadata(pOutDoc, PtxPdf_Metadata_Copy(pOutDoc, PtxPdf_Document_GetMetadata(pInDoc))) ==
14        FALSE)
15        return FALSE;
16
17    // Viewer settings
18    if (PtxPdf_Document_SetViewerSettings(
19            pOutDoc, PtxPdfNav_ViewerSettings_Copy(pOutDoc, PtxPdf_Document_GetViewerSettings(pInDoc))) == FALSE)
20        return FALSE;
21
22    // Associated files (for PDF/A-3 and PDF 2.0 only)
23    pInFileRefList  = PtxPdf_Document_GetAssociatedFiles(pInDoc);
24    pOutFileRefList = PtxPdf_Document_GetAssociatedFiles(pOutDoc);
25    if (pInFileRefList == NULL || pOutFileRefList == NULL)
26        return FALSE;
27    for (int iFileRef = 0; iFileRef < PtxPdf_FileReferenceList_GetCount(pInFileRefList); iFileRef++)
28        if (PtxPdf_FileReferenceList_Add(
29                pOutFileRefList,
30                PtxPdf_FileReference_Copy(pOutDoc, PtxPdf_FileReferenceList_Get(pInFileRefList, iFileRef))) == FALSE)
31            return FALSE;
32
33    // Plain embedded files
34    pInFileRefList  = PtxPdf_Document_GetPlainEmbeddedFiles(pInDoc);
35    pOutFileRefList = PtxPdf_Document_GetPlainEmbeddedFiles(pOutDoc);
36    if (pInFileRefList == NULL || pOutFileRefList == NULL)
37        return FALSE;
38    for (int iFileRef = 0; iFileRef < PtxPdf_FileReferenceList_GetCount(pInFileRefList); iFileRef++)
39        if (PtxPdf_FileReferenceList_Add(
40                pOutFileRefList,
41                PtxPdf_FileReference_Copy(pOutDoc, PtxPdf_FileReferenceList_Get(pInFileRefList, iFileRef))) == FALSE)
42            return FALSE;
43
44    return TRUE;
45}
1int addDataMatrix(TPtxPdf_Document* pOutDoc, TPtxPdf_Page* pOutPage, TCHAR* szDataMatrixPath)
2{
3    TPtxPdfContent_Content*          pContent   = NULL;
4    TPtxPdfContent_ContentGenerator* pGenerator = NULL;
5    TPtxSys_StreamDescriptor         datamatrixDescriptor;
6    FILE*                            pDatamatrixStream = NULL;
7    TPtxPdfContent_Image*            pDatamatrix       = NULL;
8
9    pContent = PtxPdf_Page_GetContent(pOutPage);
10
11    // Create content generator
12    pGenerator = PtxPdfContent_ContentGenerator_New(pContent, FALSE);
13    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pGenerator, _T("Failed to create a content generator. %s (ErrorCode: 0x%08x).\n"),
14                                     szErrorBuff, Ptx_GetLastError());
15
16    // Import data matrix
17    pDatamatrixStream = _tfopen(szDataMatrixPath, _T("rb"));
18    GOTO_CLEANUP_IF_NULL(pDatamatrixStream, _T("Failed to open data matrix file \"%s\".\n"), szDataMatrixPath);
19    PtxSysCreateFILEStreamDescriptor(&datamatrixDescriptor, pDatamatrixStream, 0);
20
21    // Create image object for data matrix
22    pDatamatrix = PtxPdfContent_Image_Create(pOutDoc, &datamatrixDescriptor);
23    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pDatamatrix, _T("Failed to create image object. %s (ErrorCode: 0x%08x).\n"),
24                                     szErrorBuff, Ptx_GetLastError());
25
26    // Data matrix size
27    double dDatamatrixSize = 85.0;
28
29    // Calculate Rectangle for data matrix
30    TPtxGeomReal_Size size;
31    PtxPdf_Page_GetSize(pOutPage, &size);
32    TPtxGeomReal_Rectangle rect;
33    rect.dLeft   = dBorder;
34    rect.dBottom = size.dHeight - (dDatamatrixSize + dBorder);
35    rect.dRight  = dDatamatrixSize + dBorder;
36    rect.dTop    = size.dHeight - dBorder;
37
38    // Paint image of data matrix into the specified rectangle
39    GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(
40        PtxPdfContent_ContentGenerator_PaintImage(pGenerator, pDatamatrix, &rect),
41        _T("Failed to paint data matrix into the specified rectangle. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
42        Ptx_GetLastError());
43
44cleanup:
45    if (pGenerator != NULL)
46        PtxPdfContent_ContentGenerator_Close(pGenerator);
47    if (pContent != NULL)
48        Ptx_Release(pContent);
49
50    return iReturnValue;
51}
Download code sample
1// Open input document 
2using (Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read))
3using (Document inDoc = Document.Open(inStream, null))
4
5// Create output document
6using (Stream outStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
7using (Document outDoc = Document.Create(outStream, inDoc.Conformance, null))
8{
9    // Copy document-wide data
10    CopyDocumentData(inDoc, outDoc);
11
12    // Define page copy options
13    PageCopyOptions copyOptions = new PageCopyOptions();
14
15    // Copy first page, add datamatrix image, and append to output document
16    Page outPage = Page.Copy(outDoc, inDoc.Pages[0], copyOptions);
17    AddDataMatrix(outDoc, outPage, datamatrixPath);
18    outDoc.Pages.Add(outPage);
19
20    // Copy remaining pages and append to output document
21    PageList inPageRange = inDoc.Pages.GetRange(1, inDoc.Pages.Count - 1);
22    PageList copiedPages = PageList.Copy(outDoc, inPageRange, copyOptions);
23    outDoc.Pages.AddRange(copiedPages);
24}
1private static void CopyDocumentData(Document inDoc, Document outDoc)
2{
3    // Copy document-wide data
4
5    // Output intent
6    if (inDoc.OutputIntent != null)
7        outDoc.OutputIntent = IccBasedColorSpace.Copy(outDoc, inDoc.OutputIntent);
8
9    // Metadata
10    outDoc.Metadata = Metadata.Copy(outDoc, inDoc.Metadata);
11
12    // Viewer settings
13    outDoc.ViewerSettings = ViewerSettings.Copy(outDoc, inDoc.ViewerSettings);
14
15    // Associated files (for PDF/A-3 and PDF 2.0 only)
16    FileReferenceList outAssociatedFiles = outDoc.AssociatedFiles;
17    foreach (FileReference inFileRef in inDoc.AssociatedFiles)
18        outAssociatedFiles.Add(FileReference.Copy(outDoc, inFileRef));
19
20    // Plain embedded files
21    FileReferenceList outEmbeddedFiles = outDoc.PlainEmbeddedFiles;
22    foreach (FileReference inFileRef in inDoc.PlainEmbeddedFiles)
23        outEmbeddedFiles.Add(FileReference.Copy(outDoc, inFileRef));
24}
1private static void AddDataMatrix(Document document, Page page, string datamatrixPath)
2{
3    // Create content generator
4    using ContentGenerator generator = new ContentGenerator(page.Content, false);
5
6    // Import data matrix
7    using Stream inMatrix = new FileStream(datamatrixPath, FileMode.Open, FileAccess.Read);
8
9    // Create image object for data matrix
10    Image datamatrix = Image.Create(document, inMatrix);
11
12    // Data matrix size
13    double datamatrixSize = 85;
14
15    // Calculate Rectangle for data matrix
16    Rectangle rect = new Rectangle
17    {
18        Left = Border,
19        Bottom = page.Size.Height - (datamatrixSize + Border),
20        Right = datamatrixSize + Border,
21        Top = page.Size.Height - Border
22    };
23
24    // Paint image of data matrix into the specified rectangle 
25    generator.PaintImage(datamatrix, rect);
26}
Download code sample
1try (// Open input document
2    FileStream inStream = new FileStream(inPath, FileStream.Mode.READ_ONLY);
3    Document inDoc = Document.open(inStream, null);
4    FileStream outStream = new FileStream(outPath, FileStream.Mode.READ_WRITE_NEW)) {
5    try (// Create output document
6        Document outDoc = Document.create(outStream, inDoc.getConformance(), null)) {
7
8        // Copy document-wide data
9        copyDocumentData(inDoc, outDoc);
10
11        // Define page copy options
12        PageCopyOptions copyOptions = new PageCopyOptions();
13
14        // Copy first page, add data matrix image, and append to output document
15        Page outPage = Page.copy(outDoc, inDoc.getPages().get(0), copyOptions);
16        addDatamatrix(outDoc, outPage, datamatrixPath);
17        outDoc.getPages().add(outPage);
18
19        // Copy remaining pages and append to output document
20        PageList inPageRange = inDoc.getPages().subList(1, inDoc.getPages().size());
21        PageList copiedPages = PageList.copy(outDoc, inPageRange, copyOptions);
22        outDoc.getPages().addAll(copiedPages);
23    }
24}
1private static void copyDocumentData(Document inDoc, Document outDoc) throws ToolboxException, IOException {
2    // Copy document-wide data
3
4    // Output intent
5    if (inDoc.getOutputIntent() != null)
6        outDoc.setOutputIntent(IccBasedColorSpace.copy(outDoc, inDoc.getOutputIntent()));
7
8    // Metadata
9    outDoc.setMetadata(Metadata.copy(outDoc, inDoc.getMetadata()));
10
11    // Viewer settings
12    outDoc.setViewerSettings(ViewerSettings.copy(outDoc, inDoc.getViewerSettings()));
13
14    // Associated files (for PDF/A-3 and PDF 2.0 only)
15    FileReferenceList outAssociatedFiles = outDoc.getAssociatedFiles();
16    for (FileReference inFileRef : inDoc.getAssociatedFiles())
17        outAssociatedFiles.add(FileReference.copy(outDoc, inFileRef));
18
19    // Plain embedded files
20    FileReferenceList outEmbeddedFiles = outDoc.getPlainEmbeddedFiles();
21    for (FileReference inFileRef : inDoc.getPlainEmbeddedFiles())
22        outEmbeddedFiles.add(FileReference.copy(outDoc, inFileRef));
23}
1private static void addDatamatrix(Document document, Page page, String datamatrixPath)
2        throws ToolboxException, IOException {
3    try (// Create content generator
4        ContentGenerator generator = new ContentGenerator(page.getContent(), false);
5        // Import data matrix
6        FileStream inMatrix = new FileStream(datamatrixPath, FileStream.Mode.READ_ONLY)) {
7
8        // Create image object for data matrix
9        Image datamatrix = Image.create(document, inMatrix);
10
11        // Data matrix size
12        double datamatrixSize = 85;
13
14        // Calculate Rectangle for data matrix
15        Rectangle rect = new Rectangle(Border, page.getSize().height - (datamatrixSize + Border),
16                datamatrixSize + Border, page.getSize().height - Border);
17
18        // Paint image of data matrix into the specified rectangle
19        generator.paintImage(datamatrix, rect);
20    }
21}
Download code sample

Add image to PDF

1// Open input document
2pInStream = _tfopen(szInPath, _T("rb"));
3GOTO_CLEANUP_IF_NULL(pInStream, _T("Failed to open input file \"%s\".\n"), szInPath);
4PtxSysCreateFILEStreamDescriptor(&descriptor, pInStream, 0);
5pInDoc = PtxPdf_Document_Open(&descriptor, _T(""));
6GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInDoc, _T("Input file \"%s\" cannot cannot be opened. %s (ErrorCode: 0x%08x).\n"),
7                                 szInPath, szErrorBuff, Ptx_GetLastError());
8
9// Create output document
10pOutStream = _tfopen(szOutPath, _T("wb+"));
11GOTO_CLEANUP_IF_NULL(pOutStream, _T("Failed to open output file \"%s\".\n"), szOutPath);
12PtxSysCreateFILEStreamDescriptor(&outDescriptor, pOutStream, 0);
13iConformance = PtxPdf_Document_GetConformance(pInDoc);
14pOutDoc      = PtxPdf_Document_Create(&outDescriptor, &iConformance, NULL);
15GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("Output file \"%s\" cannot be created. %s (ErrorCode: 0x%08x).\n"),
16                                 szOutPath, szErrorBuff, Ptx_GetLastError());
17
18// Copy document-wide data
19GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(copyDocumentData(pInDoc, pOutDoc),
20                                  _T("Failed to copy document-wide data. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
21                                  Ptx_GetLastError());
22
23// Configure copy options
24pCopyOptions = PtxPdf_PageCopyOptions_New();
25
26// Get input and output page lists
27pInPageList = PtxPdf_Document_GetPages(pInDoc);
28GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPageList,
29                                 _T("Failed to get the pages of the input document. %s (ErrorCode: 0x%08x).\n"),
30                                 szErrorBuff, Ptx_GetLastError());
31pOutPageList = PtxPdf_Document_GetPages(pOutDoc);
32GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPageList,
33                                 _T("Failed to get the pages of the output document. %s (ErrorCode: 0x%08x).\n"),
34                                 szErrorBuff, Ptx_GetLastError());
35
36// Copy pages preceding selected page
37pInPageRange =