PDF Toolbox SDK

Dokumentation & Codebeispiele

Linux
MacOS
Windows Client
API
GUI
.NET Core
NuGet
C/C++
Java
PDF Toolkit Java-Referenz

PDF Toolkit Java-Referenz

Sehen Sie sich die Referenzdokumentation für Java an, um mit der Entwicklung des PDF Toolkit SDK zu beginnen.

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 samples for
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 PdfToolboxException, 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 samples for

Content Addition

Add barcode 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 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 samples for
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 PdfToolboxException, 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 PdfToolboxException, 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 samples for
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"), szInPath, szErrorBuff, Ptx_GetLastError());
7
8// Create file stream
9pFontStream = _tfopen(szFontPath, _T("rb"));
10GOTO_CLEANUP_IF_NULL(pFontStream, _T("Failed to open font file."));
11PtxSysCreateFILEStreamDescriptor(&fontDescriptor, pFontStream, 0);
12
13// Create output document
14pOutStream = _tfopen(szOutPath, _T("wb+"));
15GOTO_CLEANUP_IF_NULL(pOutStream, _T("Failed to open output file \"%s\".\n"), szOutPath);
16PtxSysCreateFILEStreamDescriptor(&outDescriptor, pOutStream, 0);
17iConformance = PtxPdf_Document_GetConformance(pInDoc);
18pOutDoc = PtxPdf_Document_Create(&outDescriptor, &iConformance, NULL);
19GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("Output file \"%s\" cannot be created. %s (ErrorCode: 0x%08x).\n"), szOutPath, szErrorBuff, Ptx_GetLastError());
20pFont = PtxPdfContent_Font_Create(pOutDoc, &fontDescriptor, TRUE);
21GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pFont, _T("Failed to create font. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
22
23// Copy document-wide data
24GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(copyDocumentData(pInDoc, pOutDoc), _T("Failed to copy document-wide data. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
25
26// Configure copy options
27pCopyOptions = PtxPdf_PageCopyOptions_New();
28
29// Get page lists of input and output document
30pInPageList = PtxPdf_Document_GetPages(pInDoc);
31GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPageList, _T("Failed to get the pages of the input document. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
32pOutPageList = PtxPdf_Document_GetPages(pOutDoc);
33GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPageList, _T("Failed to get the pages of the output document. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
34
35// Copy first page
36pInPage = PtxPdf_PageList_Get(pInPageList, 0);
37GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPage, _T("Failed to get the first page. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
38pOutPage = PtxPdf_Page_Copy(pOutDoc, pInPage, pCopyOptions);
39GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPage, _T("Failed to copy page. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
40
41// Add barcode image to copied page
42if (addBarcode(pOutDoc, pOutPage, szBarcode, pFont, 50) != 0)
43    goto cleanup;
44
45// Add page to output document
46GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_PageList_Add(pOutPageList, pOutPage), _T("Failed to add page to output document. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
47
48// Get remaining pages from input
49pInPageRange = PtxPdf_PageList_GetRange(pInPageList, 1, PtxPdf_PageList_GetCount(pInPageList) - 1);
50GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPageRange, _T("Failed to get page range from input document. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
51
52// Copy remaining pages to output
53pOutPageRange = PtxPdf_PageList_Copy(pOutDoc, pInPageRange, pCopyOptions);
54GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPageRange, _T("Failed to copy page range to output document. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
55
56// Add the copied pages to the output document
57GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_PageList_AddRange(pOutPageList, pOutPageRange), _T("Failed to add page range to output page list. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
58
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(pOutDoc, PtxPdf_Document_GetOutputIntent(pInDoc))) == FALSE)
9            return FALSE;
10
11    // Metadata
12    if (PtxPdf_Document_SetMetadata(pOutDoc, PtxPdf_Metadata_Copy(pOutDoc, PtxPdf_Document_GetMetadata(pInDoc))) == FALSE)
13        return FALSE;
14
15    // Viewer settings
16    if (PtxPdf_Document_SetViewerSettings(pOutDoc, PtxPdfNav_ViewerSettings_Copy(pOutDoc, PtxPdf_Document_GetViewerSettings(pInDoc))) == FALSE)
17        return FALSE;
18
19    // Associated files (for PDF/A-3 and PDF 2.0 only)
20    pInFileRefList = PtxPdf_Document_GetAssociatedFiles(pInDoc);
21    pOutFileRefList = PtxPdf_Document_GetAssociatedFiles(pOutDoc);
22    if (pInFileRefList == NULL || pOutFileRefList == NULL)
23        return FALSE;
24    for (int iFileRef = 0; iFileRef < PtxPdf_FileReferenceList_GetCount(pInFileRefList); iFileRef++)
25        if (PtxPdf_FileReferenceList_Add(pOutFileRefList, PtxPdf_FileReference_Copy(pOutDoc, PtxPdf_FileReferenceList_Get(pInFileRefList, iFileRef))) == FALSE)
26            return FALSE;
27
28    // Plain embedded files
29    pInFileRefList = PtxPdf_Document_GetPlainEmbeddedFiles(pInDoc);
30    pOutFileRefList = PtxPdf_Document_GetPlainEmbeddedFiles(pOutDoc);
31    if (pInFileRefList == NULL || pOutFileRefList == NULL)
32        return FALSE;
33    for (int iFileRef = 0; iFileRef < PtxPdf_FileReferenceList_GetCount(pInFileRefList); iFileRef++)
34        if (PtxPdf_FileReferenceList_Add(pOutFileRefList, PtxPdf_FileReference_Copy(pOutDoc, PtxPdf_FileReferenceList_Get(pInFileRefList, iFileRef))) == FALSE)
35            return FALSE;
36
37    return TRUE;
38}
1int addBarcode(TPtxPdf_Document* pOutDoc, TPtxPdf_Page* pOutPage, TCHAR* szBarcode, TPtxPdfContent_Font* pFont, double dFontSize)
2{
3    TPtxPdfContent_Content* pContent = NULL;
4    TPtxPdfContent_ContentGenerator* pGenerator = NULL;
5    TPtxPdfContent_Text* pBarcodeText = NULL;
6    TPtxPdfContent_TextGenerator* pTextGenerator = NULL;
7
8    pContent = PtxPdf_Page_GetContent(pOutPage);
9
10    // Create content generator
11    pGenerator = PtxPdfContent_ContentGenerator_New(pContent, FALSE);
12    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pGenerator, _T("Failed to create a content generator. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
13
14    // Create text object
15    pBarcodeText = PtxPdfContent_Text_Create(pOutDoc);
16    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pBarcodeText, _T("Failed to create a text object. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
17
18    // Create text generator
19    pTextGenerator = PtxPdfContent_TextGenerator_New(pBarcodeText, pFont, dFontSize, NULL);
20    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pTextGenerator, _T("Failed to create a text generator. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
21
22    // Calculate position
23    TPtxGeomReal_Size size;
24    PtxPdf_Page_GetSize(pOutPage, &size);
25    TPtxGeomReal_Point position;
26    double dTextWidth = PtxPdfContent_TextGenerator_GetWidth(pTextGenerator, szBarcode);
27    GOTO_CLEANUP_IF_NEGATIVE_PRINT_ERROR(dTextWidth, _T("%s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
28    double dFontAscent = PtxPdfContent_Font_GetAscent(pFont);
29    GOTO_CLEANUP_IF_NEGATIVE_PRINT_ERROR(dFontAscent, _T("%s(ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
30    double dFontDescent = PtxPdfContent_Font_GetDescent(pFont);
31    GOTO_CLEANUP_IF_NEGATIVE_PRINT_ERROR(dFontDescent, _T("%s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
32    position.dX = size.dWidth - (dTextWidth + dBorder);
33    position.dY = size.dHeight - (dFontSize * (dFontAscent + dFontDescent) + dBorder);
34
35    // Move to position
36    GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdfContent_TextGenerator_MoveTo(pTextGenerator, &position), _T("Failed to move to position %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
37    // Add given barcode string
38    GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdfContent_TextGenerator_ShowLine(pTextGenerator, szBarcode), _T("Failed to add barcode string. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
39
40    // Close text generator
41    if (pTextGenerator != NULL)
42        PtxPdfContent_TextGenerator_Close(pTextGenerator);
43
44    // Paint the positioned barcode text
45    GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdfContent_ContentGenerator_PaintText(pGenerator, pBarcodeText), _T("Failed to paint the positioned barcode text. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
46
47cleanup:
48    if (pGenerator != NULL)
49        PtxPdfContent_ContentGenerator_Close(pGenerator);
50
51    return iReturnValue;
52}
Download code samples for

Add Data Matrix 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
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 samples for
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 PdfToolboxException, 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 PdfToolboxException, 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 samples for
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"), szInPath, szErrorBuff, Ptx_GetLastError());
7
8// Create output document
9pOutStream = _tfopen(szOutPath, _T("wb+"));
10GOTO_CLEANUP_IF_NULL(pOutStream, _T("Failed to open output file \"%s\".\n"), szOutPath);
11PtxSysCreateFILEStreamDescriptor(&outDescriptor, pOutStream, 0);
12iConformance = PtxPdf_Document_GetConformance(pInDoc);
13pOutDoc = PtxPdf_Document_Create(&outDescriptor, &iConformance, NULL);
14GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("Output file \"%s\" cannot be created. %s (ErrorCode: 0x%08x).\n"), szOutPath, szErrorBuff, Ptx_GetLastError());
15
16// Create embedded font in output document
17pFont = PtxPdfContent_Font_CreateFromSystem(pOutDoc, _T("Arial"), _T("Italic"), TRUE);
18GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pFont, _T("Failed to create font. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
19
20// Copy document-wide data
21GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(copyDocumentData(pInDoc, pOutDoc), _T("Failed to copy document-wide data. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
22
23// Configure copy options
24pCopyOptions = PtxPdf_PageCopyOptions_New();
25
26// Get page lists of input and output document
27pInPageList = PtxPdf_Document_GetPages(pInDoc);
28GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPageList, _T("Failed to get the pages of the input document. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
29pOutPageList = PtxPdf_Document_GetPages(pOutDoc);
30GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPageList, _T("Failed to get the pages of the output document. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
31
32// Copy first page
33pInPage = PtxPdf_PageList_Get(pInPageList, 0);
34GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPage, _T("Failed to get the first page. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
35pOutPage = PtxPdf_Page_Copy(pOutDoc, pInPage, pCopyOptions);
36GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPage, _T("Failed to copy page. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
37
38// Add datamatrix image to copied page
39if (addDataMatrix(pOutDoc, pOutPage, szDatamatrixPath) != 0)
40    goto cleanup;
41
42// Add page to output document
43GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_PageList_Add(pOutPageList, pOutPage), _T("Failed to add page to output document. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
44
45// Get remaining pages from input
46pInPageRange = PtxPdf_PageList_GetRange(pInPageList, 1, PtxPdf_PageList_GetCount(pInPageList) - 1);
47GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPageRange, _T("Failed to get page range from input document. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
48
49// Copy remaining pages to output
50pOutPageRange = PtxPdf_PageList_Copy(pOutDoc, pInPageRange, pCopyOptions);
51GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPageRange, _T("Failed to copy page range to output document. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
52
53// Add the copied pages to the output document
54GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_PageList_AddRange(pOutPageList, pOutPageRange), _T("Failed to add page range to output page list. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
55
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(pOutDoc, PtxPdf_Document_GetOutputIntent(pInDoc))) == FALSE)
9            return FALSE;
10
11    // Metadata
12    if (PtxPdf_Document_SetMetadata(pOutDoc, PtxPdf_Metadata_Copy(pOutDoc, PtxPdf_Document_GetMetadata(pInDoc))) == FALSE)
13        return FALSE;
14
15    // Viewer settings
16    if (PtxPdf_Document_SetViewerSettings(pOutDoc, PtxPdfNav_ViewerSettings_Copy(pOutDoc, PtxPdf_Document_GetViewerSettings(pInDoc))) == FALSE)
17        return FALSE;
18
19    // Associated files (for PDF/A-3 and PDF 2.0 only)
20    pInFileRefList = PtxPdf_Document_GetAssociatedFiles(pInDoc);
21    pOutFileRefList = PtxPdf_Document_GetAssociatedFiles(pOutDoc);
22    if (pInFileRefList == NULL || pOutFileRefList == NULL)
23        return FALSE;
24    for (int iFileRef = 0; iFileRef < PtxPdf_FileReferenceList_GetCount(pInFileRefList); iFileRef++)
25        if (PtxPdf_FileReferenceList_Add(pOutFileRefList, PtxPdf_FileReference_Copy(pOutDoc, PtxPdf_FileReferenceList_Get(pInFileRefList, iFileRef))) == FALSE)
26            return FALSE;
27
28    // Plain embedded files
29    pInFileRefList = PtxPdf_Document_GetPlainEmbeddedFiles(pInDoc);
30    pOutFileRefList = PtxPdf_Document_GetPlainEmbeddedFiles(pOutDoc);
31    if (pInFileRefList == NULL || pOutFileRefList == NULL)
32        return FALSE;
33    for (int iFileRef = 0; iFileRef < PtxPdf_FileReferenceList_GetCount(pInFileRefList); iFileRef++)
34        if (PtxPdf_FileReferenceList_Add(pOutFileRefList, PtxPdf_FileReference_Copy(pOutDoc, PtxPdf_FileReferenceList_Get(pInFileRefList, iFileRef))) == FALSE)
35            return FALSE;
36
37    return TRUE;
38}
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"), szErrorBuff, Ptx_GetLastError());
14
15    // Import data matrix
16    pDatamatrixStream = _tfopen(szDataMatrixPath, _T("rb"));
17    GOTO_CLEANUP_IF_NULL(pDatamatrixStream, _T("Failed to open data matrix file \"%s\".\n"), szDataMatrixPath);
18    PtxSysCreateFILEStreamDescriptor(&datamatrixDescriptor, pDatamatrixStream, 0);
19
20    // Create image object for data matrix
21    pDatamatrix = PtxPdfContent_Image_Create(pOutDoc, &datamatrixDescriptor);
22    GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pDatamatrix, _T("Failed to create image object. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
23
24    // Data matrix size
25    double dDatamatrixSize = 85.0;
26
27    // Calculate Rectangle for data matrix
28    TPtxGeomReal_Size size;
29    PtxPdf_Page_GetSize(pOutPage, &size);
30    TPtxGeomReal_Rectangle rect;
31    rect.dLeft = dBorder;
32    rect.dBottom = size.dHeight - (dDatamatrixSize + dBorder);
33    rect.dRight = dDatamatrixSize + dBorder;
34    rect.dTop = size.dHeight - dBorder;
35
36    // Paint image of data matrix into the specified rectangle
37    GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdfContent_ContentGenerator_PaintImage(pGenerator, pDatamatrix, &rect), _T("Failed to paint data matrix into the specified rectangle. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
38
39cleanup:
40    if (pGenerator != NULL)
41        PtxPdfContent_ContentGenerator_Close(pGenerator);
42    if (pContent != NULL)
43        Ptx_Release(pContent);
44
45    return iReturnValue;
46}
Download code samples for

Add image 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
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 pages preceding selected page and append do output document
16    PageList inPageRange = inDoc.Pages.GetRange(0, pageNumber - 1);
17    PageList copiedPages = PageList.Copy(outDoc, inPageRange, copyOptions);
18    outDoc.Pages.AddRange(copiedPages);
19
20    // Copy selected page, add image, and append to output document
21    Page outPage = Page.Copy(outDoc, inDoc.Pages[pageNumber - 1], copyOptions);
22    AddImage(outDoc, outPage, imagePath, 150, 150);
23    outDoc.Pages.Add(outPage);
24
25    // Copy remaining pages and append to output document
26    inPageRange = inDoc.Pages.GetRange(pageNumber, inDoc.Pages.Count - pageNumber);
27    copiedPages = PageList.Copy(outDoc, inPageRange, copyOptions);
28    outDoc.Pages.AddRange(copiedPages);
29}
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 AddImage(Document document, Page page, string imagePath, double x, double y)
2{
3    // Create content generator 
4    using ContentGenerator generator = new ContentGenerator(page.Content, false);
5
6    // Load image from input path
7    using Stream inImage = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
8
9    // Create image object
10    Image image = Image.Create(document, inImage);
11    double resolution = 150;
12
13    // Calculate rectangle for image 
14    PdfTools.FourHeights.PdfToolbox.Geometry.Integer.Size size = image.Size;
15    Rectangle rect = new Rectangle
16    {
17        Left = x,
18        Bottom = y,
19        Right = x + size.Width * 72 / resolution,
20        Top = y + size.Height * 72 / resolution
21    };
22
23    // Paint image into the specified rectangle 
24    generator.PaintImage(image, rect);
25}
Download code samples for
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 pages preceding selected page and append to output document
15        PageList inPageRange = inDoc.getPages().subList(0, pageNumber - 1);
16        PageList copiedPages = PageList.copy(outDoc, inPageRange, copyOptions);
17        outDoc.getPages().addAll(copiedPages);
18
19        // Copy selected page, add image, and append to output document
20        Page outPage = Page.copy(outDoc, inDoc.getPages().get(pageNumber - 1), copyOptions);
21        addImage(outDoc, outPage, imagePath, 150, 150);
22        outDoc.getPages().add(outPage);
23
24        // Copy remaining pages and append to output document
25        inPageRange = inDoc.getPages().subList(pageNumber, inDoc.getPages().size());
26        copiedPages = PageList.copy(outDoc, inPageRange, copyOptions);
27        outDoc.getPages().addAll(copiedPages);
28    }
29}
1private static void copyDocumentData(Document inDoc, Document outDoc) throws PdfToolboxException, 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 addImage(Document document, Page outPage, String imagePath, double x, double y)
2        throws PdfToolboxException, IOException {
3    try (// Create content generator
4        ContentGenerator generator = new ContentGenerator(outPage.getContent(), false);
5        // Load image from input path
6        FileStream inImage = new FileStream(imagePath, FileStream.Mode.READ_ONLY)) {
7        // Create image object
8        Image image = Image.create(document, inImage);
9
10        double resolution = 150;
11
12        // Calculate rectangle for image
13        Size size = image.getSize();
14        Rectangle rect = new Rectangle(x, y, x + size.getWidth() * 72 / resolution,
15                y + size.getHeight() * 72 / resolution);
16
17        // Paint image into the specified rectangle
18        generator.paintImage(image, rect);
19    }
20}
Download code samples for
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"), szInPath, szErrorBuff, Ptx_GetLastError());
7
8// Create output document
9pOutStream = _tfopen(szOutPath, _T("wb+"));
10GOTO_CLEANUP_IF_NULL(pOutStream, _T("Failed to open output file \"%s\".\n"), szOutPath);
11PtxSysCreateFILEStreamDescriptor(&outDescriptor, pOutStream, 0);
12iConformance = PtxPdf_Document_GetConformance(pInDoc);
13pOutDoc = PtxPdf_Document_Create(&outDescriptor, &iConformance, NULL);
14GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutDoc, _T("Output file \"%s\" cannot be created. %s (ErrorCode: 0x%08x).\n"), szOutPath, szErrorBuff, Ptx_GetLastError());
15
16// Copy document-wide data
17GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(copyDocumentData(pInDoc, pOutDoc), _T("Failed to copy document-wide data. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, Ptx_GetLastError());
18
19