Code samples
Here you'll find some samples to get you started with the PDF Toolbox SDK.
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}
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}
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}
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}
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}
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}
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}
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}
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}
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}
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 = PtxPdf_PageList_GetRange(pInPageList, 0, iPageNumber - 1);
38GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPageRange, _T("Failed to get page range. %s (ErrorCode: 0x%08x).\n"),
39 szErrorBuff, Ptx_GetLastError());
40pOutPageRange = PtxPdf_PageList_Copy(pOutDoc, pInPageRange, pCopyOptions);
41GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPageRange, _T("Failed to copy page range. %s (ErrorCode: 0x%08x).\n"),
42 szErrorBuff, Ptx_GetLastError());
43GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_PageList_AddRange(pOutPageList, pOutPageRange),
44 _T("Failed to add page range. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
45 Ptx_GetLastError());
46Ptx_Release(pInPageRange);
47pInPageRange = NULL;
48Ptx_Release(pOutPageRange);
49pOutPageRange = NULL;
50
51// Copy selected page an add image
52pInPage = PtxPdf_PageList_Get(pInPageList, iPageNumber - 1);
53GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPage, _T("Failed to get page. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
54 Ptx_GetLastError());
55pOutPage = PtxPdf_Page_Copy(pOutDoc, pInPage, pCopyOptions);
56GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPage, _T("Failed to copy page. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
57 Ptx_GetLastError());
58if (addImage(pOutDoc, pOutPage, szImagePath, 150.0, 150.0) != 0)
59 goto cleanup;
60GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_PageList_Add(pOutPageList, pOutPage),
61 _T("Failed to add page. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
62 Ptx_GetLastError());
63
64// Copy remaining pages
65pInPageRange = PtxPdf_PageList_GetRange(pInPageList, 1, PtxPdf_PageList_GetCount(pInPageList) - 1);
66GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPageRange,
67 _T("Failed to get page range from input document. %s (ErrorCode: 0x%08x).\n"),
68 szErrorBuff, Ptx_GetLastError());
69pOutPageRange = PtxPdf_PageList_Copy(pOutDoc, pInPageRange, pCopyOptions);
70GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPageRange,
71 _T("Failed to copy page range to output document. %s (ErrorCode: 0x%08x).\n"),
72 szErrorBuff, Ptx_GetLastError());
73GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_PageList_AddRange(pOutPageList, pOutPageRange),
74 _T("Failed to add page range to output page list. %s (ErrorCode: 0x%08x).\n"),
75 szErrorBuff, Ptx_GetLastError());
76
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 addImage(TPtxPdf_Document* pOutDoc, TPtxPdf_Page* pOutPage, TCHAR* szImagePath, double x, double y)
2{
3 TPtxPdfContent_Content* pContent = NULL;
4 TPtxPdfContent_ContentGenerator* pGenerator = NULL;
5 TPtxSys_StreamDescriptor imageDescriptor;
6 FILE* pImageStream = NULL;
7 TPtxPdfContent_Image* pImage = NULL;
8
9 pContent = PtxPdf_Page_GetContent(pOutPage);
10
11 // Create content generator
12 pGenerator = PtxPdfContent_ContentGenerator_New(pContent, FALSE);
13
14 // Load image from input path
15 pImageStream = _tfopen(szImagePath, _T("rb"));
16 PtxSysCreateFILEStreamDescriptor(&imageDescriptor, pImageStream, 0);
17
18 // Create image object
19 pImage = PtxPdfContent_Image_Create(pOutDoc, &imageDescriptor);
20
21 double dResolution = 150.0;
22
23 TPtxGeomInt_Size size;
24 GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdfContent_Image_GetSize(pImage, &size),
25 _T("Failed to get image size. %s(ErrorCode: 0x%08x).\n"), szErrorBuff,
26 Ptx_GetLastError());
27
28 // Calculate Rectangle for data matrix
29 TPtxGeomReal_Rectangle rect;
30 rect.dLeft = x;
31 rect.dBottom = y;
32 rect.dRight = x + (double)size.iWidth * 72.0 / dResolution;
33 rect.dTop = y + (double)size.iHeight * 72.0 / dResolution;
34
35 // Paint image into the specified rectangle
36 GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdfContent_ContentGenerator_PaintImage(pGenerator, pImage, &rect),
37 _T("Failed to paint image. %s(ErrorCode: 0x%08x).\n"), szErrorBuff,
38 Ptx_GetLastError());
39
40cleanup:
41 if (pGenerator != NULL)
42 PtxPdfContent_ContentGenerator_Close(pGenerator);
43 if (pContent != NULL)
44 Ptx_Release(pContent);
45
46 return iReturnValue;
47}
Add image mask 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 // Get the device color space
13 ColorSpace colorSpace = ColorSpace.CreateProcessColorSpace(outDoc, ProcessColorSpaceType.Rgb);
14
15 // Create paint object
16 paint = Paint.Create(outDoc, colorSpace, new double[] { 1.0, 0.0, 0.0 }, null);
17
18 // Define page copy options
19 PageCopyOptions copyOptions = new PageCopyOptions();
20
21 // Copy first page, add image mask, and append to output document
22 Page outPage = Page.Copy(outDoc, inDoc.Pages[0], copyOptions);
23 AddImageMask(outDoc, outPage, imageMaskPath, 250, 150);
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}
1 private static void AddImageMask(Document document, Page outPage, string imagePath,
2 double x, double y)
3 {
4 // Create content generator
5 using ContentGenerator generator = new ContentGenerator(outPage.Content, false);
6
7 // Load image from input path
8 using Stream inImage = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
9
10 // Create image mask object
11 ImageMask imageMask = ImageMask.Create(document, inImage);
12 double resolution = 150;
13
14 // Calculate rectangle for image
15 PdfTools.FourHeights.PdfToolbox.Geometry.Integer.Size size = imageMask.Size;
16 Rectangle rect = new Rectangle
17 {
18 Left = x,
19 Bottom = y,
20 Right = x + size.Width * 72 / resolution,
21 Top = y + size.Height * 72 / resolution
22 };
23
24 // Paint image mask into the specified rectangle
25 generator.PaintImageMask(imageMask, rect, paint);
26 }
27}
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 // Get the device color space
15 ColorSpace colorSpace = ColorSpace.createProcessColorSpace(outDoc, ProcessColorSpaceType.RGB);
16
17 // Create paint object
18 paint = Paint.create(outDoc, colorSpace, new double[] { 1.0, 0.0, 0.0 }, null);
19
20 // Copy first page, add image mask, and append to output document
21 Page outPage = Page.copy(outDoc, inDoc.getPages().get(0), copyOptions);
22 addImageMask(outDoc, outPage, imageMaskPath, 250, 150);
23 outDoc.getPages().add(outPage);
24
25 // Copy remaining pages and append to output document
26 PageList inPageRange = inDoc.getPages().subList(1, inDoc.getPages().size());
27 PageList copiedPages = PageList.copy(outDoc, inPageRange, copyOptions);
28 outDoc.getPages().addAll(copiedPages);
29 }
30}
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 addImageMask(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 mask object
8 ImageMask imageMask = ImageMask.create(document, inImage);
9
10 double resolution = 150;
11
12 // Calculate rectangle for image
13 Size size = imageMask.getSize();
14 Rectangle rect = new Rectangle(x, y, x + size.getWidth() * 72 / resolution,
15 y + size.getHeight() * 72 / resolution);
16
17 // Paint image mask into the specified rectangle
18 generator.paintImageMask(imageMask, rect, paint);
19 }
20}
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(_T("Input file \"%s\" cannot be opened. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
7 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(_T("Output file \"%s\" cannot be created. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
16 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// Get the device color space
24TPtxPdfContent_ColorSpace* pColorSpace =
25 PtxPdfContent_ColorSpace_CreateProcessColorSpace(pOutDoc, ePtxPdfContent_ProcessColorSpaceType_Rgb);
26GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pColorSpace, _T("Failed to get the device color space. %s (ErrorCode: 0x%08x).\n"),
27 szErrorBuff, Ptx_GetLastError());
28
29// Chose the RGB color value
30double color[] = {1.0, 0.0, 0.0};
31size_t nColor = sizeof(color) / sizeof(double);
32
33// Create paint object
34pPaint = PtxPdfContent_Paint_Create(pOutDoc, pColorSpace, color, nColor, NULL);
35GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pPaint, _T("Failed to create a transparent paint. %s (ErrorCode: 0x%08x).\n"),
36 szErrorBuff, Ptx_GetLastError());
37
38// Configure copy options
39pCopyOptions = PtxPdf_PageCopyOptions_New();
40
41// Get input and output page lists
42pInPageList = PtxPdf_Document_GetPages(pInDoc);
43GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPageList,
44 _T("Failed to get the pages of the input document. %s (ErrorCode: 0x%08x).\n"),
45 szErrorBuff, Ptx_GetLastError());
46pOutPageList = PtxPdf_Document_GetPages(pOutDoc);
47GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPageList,
48 _T("Failed to get the pages of the output document. %s (ErrorCode: 0x%08x).\n"),
49 szErrorBuff, Ptx_GetLastError());
50
51// Copy first page an add image mask
52pInPage = PtxPdf_PageList_Get(pInPageList, 0);
53GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPage, _T("Failed to get page. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
54 Ptx_GetLastError());
55pOutPage = PtxPdf_Page_Copy(pOutDoc, pInPage, pCopyOptions);
56GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPage, _T("Failed to copy page. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
57 Ptx_GetLastError());
58if (addImageMask(pOutDoc, pOutPage, szImageMaskPath, 250, 150) != 0)
59 goto cleanup;
60GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_PageList_Add(pOutPageList, pOutPage),
61 _T("Failed to add page. %s (ErrorCode: 0x%08x).\n"), szErrorBuff,
62 Ptx_GetLastError());
63
64// Copy remaining pages
65pInPageRange = PtxPdf_PageList_GetRange(pInPageList, 1, PtxPdf_PageList_GetCount(pInPageList) - 1);
66GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pInPageRange,
67 _T("Failed to get page range from input document. %s (ErrorCode: 0x%08x).\n"),
68 szErrorBuff, Ptx_GetLastError());
69pOutPageRange = PtxPdf_PageList_Copy(pOutDoc, pInPageRange, pCopyOptions);
70GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pOutPageRange,
71 _T("Failed to copy page range to output document. %s (ErrorCode: 0x%08x).\n"),
72 szErrorBuff, Ptx_GetLastError());
73GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdf_PageList_AddRange(pOutPageList, pOutPageRange),
74 _T("Failed to add page range to output page list. %s (ErrorCode: 0x%08x).\n"),
75 szErrorBuff, Ptx_GetLastError());
76
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 addImageMask(TPtxPdf_Document* pOutDoc, TPtxPdf_Page* pOutPage, TCHAR* szImageMaskPath, double x, double y)
2{
3 TPtxPdfContent_Content* pContent = NULL;
4 TPtxPdfContent_ContentGenerator* pGenerator = NULL;
5 FILE* pImageStream = NULL;
6 TPtxSys_StreamDescriptor imageDescriptor;
7 TPtxPdfContent_ImageMask* pImageMask = 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 // Load image from input path
17 pImageStream = _tfopen(szImageMaskPath, _T("rb"));
18 GOTO_CLEANUP_IF_NULL(pImageStream, _T("Failed to open image mask file \"%s\".\n"), szImageMaskPath);
19 PtxSysCreateFILEStreamDescriptor(&imageDescriptor, pImageStream, 0);
20
21 // Create image mask object
22 pImageMask = PtxPdfContent_ImageMask_Create(pOutDoc, &imageDescriptor);
23 GOTO_CLEANUP_IF_NULL_PRINT_ERROR(pImageMask, _T("Failed to create image mask obejct. %s (ErrorCode: 0x%08x).\n"),
24 szErrorBuff, Ptx_GetLastError());
25
26 double dResolution = 150.0;
27 TPtxGeomInt_Size size;
28 GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(PtxPdfContent_ImageMask_GetSize(pImageMask, &size),
29 _T("Failed to get image mask size. %s(ErrorCode: 0x%08x).\n"), szErrorBuff,
30 Ptx_GetLastError());
31
32 // Calculate Rectangle for data matrix
33 TPtxGeomReal_Rectangle rect;
34 rect.dLeft = x;
35 rect.dBottom = y;
36 rect.dRight = x + (double)size.iWidth * 72.0 / dResolution;
37 rect.dTop = y + (double)size.iHeight * 72.0 / dResolution;
38
39 // Paint image mask into the specified rectangle
40 GOTO_CLEANUP_IF_FALSE_PRINT_ERROR(
41 PtxPdfContent_ContentGenerator_PaintImageMask(pGenerator, pImageMask, &rect, pPaint),
42 _T("Failed to paint image mask. %s (ErrorCode: 0x%08x).\n"), szErrorBuff, 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}
Add line numbers to PDF
1 // Open input document
2 using Stream inStream = new FileStream(inPath, FileMode.Open, FileAccess.Read);
3 using 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 // Copy document-wide data
9 CopyDocumentData(inDoc, outDoc);
10
11 // Create a font for the line numbers
12 var lineNumberFont = Font.CreateFromSystem(outDoc, "Arial", null, true);
13
14 // Define page copy options
15 PageCopyOptions pageCopyOptions = new();
16
17 // Copy all pages from input to output document
18 var inPages = inDoc.Pages;
19 var outPages = PageList.Copy(outDoc, inPages, pageCopyOptions);
20
21 // Iterate over all input-output page pairs
22 var pages = inPages.Zip(outPages);
23 foreach (var pair in pages)
24 AddLineNumbers(outDoc, lineNumberFont, pair);
25
26 // Add the finished pages to the output document's page list
27 outDoc.Pages.AddRange(outPages);
28 }
29 catch (Exception ex)
30 {
31 Console.WriteLine(ex.Message);
32 }
33}
34
1private static void AddLineNumbers(Document outDoc, Font lineNumberFont, (Page first, Page second) pair)
2{
3 // Add line numbers to all text found in the input page to the output page
4
5 // The input and output page
6 var inPage = pair.first;
7 var outPage = pair.second;
8
9 // Extract all text fragments
10 var extractor = new ContentExtractor(inPage.Content)
11 {
12 Ungrouping = UngroupingSelection.All
13 };
14
15 // The left-most horizontel position of all text fragments
16 double leftX = inPage.Size.Width;
17
18 // A comparison for doubles that considers distances smaller than the font size as equal
19 var comparison = new Comparison<double>(
20 (a, b) =>
21 {
22 var d = b - a;
23 if (Math.Abs(d) < fontSize)
24 return 0;
25 return Math.Sign(d);
26 });
27
28 // A container to hold the vertical positions of all text fragments, sorted and without duplicates
29 SortedSet<double> lineYPositions = new(Comparer<double>.Create(comparison));
30
31 // Iterate over all content elements of the input page
32 foreach (var element in extractor)
33 {
34 // Process only text elements
35 if (element is TextElement textElement)
36 {
37 // Iterate over all text fragments
38 foreach (var fragment in textElement.Text)
39 {
40 // Get the fragments base line starting point
41 var point = fragment.Transform.TransformPoint(new Point { X = fragment.BoundingBox.Left, Y = 0 });
42
43 // Update the left-most position
44 leftX = Math.Min(leftX, point.X);
45
46 // Add the vertical position
47 lineYPositions.Add(point.Y);
48 }
49 }
50 }
51
52 // If at least text fragment was found: add line numbers
53 if (lineYPositions.Count > 0)
54 {
55 // Create a text object and use a text generator
56 var text = Text.Create(outDoc);
57 using (var textGenerator = new TextGenerator(text, lineNumberFont, fontSize, null))
58 {
59 // Iterate over all vertical positions found in the input
60 foreach (var y in lineYPositions)
61 {
62 // The line number string
63 var lineNumberString = string.Format("{0}", ++lineNumber);
64
65 // The width of the line number string when shown on the page
66 var width = textGenerator.GetWidth(lineNumberString);
67
68 // Position line numbers right aligned
69 // with a given distance to the right-most horizontal position
70 // and at the vertical position of the current text fragment
71 textGenerator.MoveTo(new Point { X = leftX - width - distance, Y = y });
72
73 // Show the line number string
74 textGenerator.Show(lineNumberString);
75 }
76 }
77
78 // Use a content generator to paint the text onto the page
79 using var contentGenerator = new ContentGenerator(outPage.Content, false);
80 contentGenerator.PaintText(text);
81 }
82}
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}
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 (Document outDoc = Document.create(outStream, inDoc.getConformance(), null)) {
6 // Copy document-wide data
7 copyDocumentData(inDoc, outDoc);
8
9 // Create embedded font in output document
10 Font font = Font.createFromSystem(outDoc, "Arial", null, true);
11
12 // Define page copy options
13 PageCopyOptions copyOptions = new PageCopyOptions();
14
15 // Copy all pages from input to output document
16 PageList inPages = inDoc.getPages();
17 PageList outPages = PageList.copy(outDoc, inPages, copyOptions);
18
19 // Iterate over all input-output page pairs and add line numbers
20 for (int i = 0; i < inPages.size(); ++i) {
21 addLineNumbers(outDoc, font, new SimpleEntry<>(inPages.get(i), outPages.get(i)));
22 }
23
24 // Add the finished pages to the output document's page list
25 outDoc.getPages().addAll(outPages);
26 }
27}
1private static void addLineNumbers(Document outDoc, Font lineNumberFont, Entry<Page, Page> pair) throws IOException, PdfToolboxException {
2 // Add line numbers to all text found in the input page to the output page
3
4 // The input and output page
5 Page inPage = pair.getKey();
6 Page outPage = pair.getValue();
7
8 // Extract all text fragments
9 ContentExtractor extractor = new ContentExtractor(inPage.getContent());
10 extractor.setUngrouping(UngroupingSelection.ALL);
11 // The left-most horizontal position of all text fragments
12 double leftX = inPage.getSize().getWidth();
13
14 Comparator<Double> comparator = new Comparator<Double>() {
15 @Override
16 public int compare(Double d1, Double d2) {
17 Double diff = d2 - d1;
18 if (Math.abs(diff) < fontSize)
19 return 0;
20 return (int) Math.signum(diff);
21 }
22 };
23
24 SortedSet<Double> lineYPositions = new TreeSet<>(comparator);
25
26 for (ContentElement element : extractor) {
27
28 // Process only text elements
29 if (element instanceof TextElement) {
30 TextElement textElement = (TextElement) element;
31 // Iterate over all text fragments
32 for (TextFragment fragment : textElement.getText()) {
33
34 // Get the fragments base line starting point
35 Point point = fragment.getTransform().transformPoint(new Point(fragment.getBoundingBox().left, 0));
36
37 // Update the left-most position
38 leftX = Math.min(leftX, point.x);
39
40 // Add the vertical position
41 lineYPositions.add(point.y);
42 }
43 }
44 }
45
46 // If at least one text fragment was found: add line numbers
47 if (lineYPositions.size() > 0) {
48
49 // Create a text object and use a text generator
50 Text text = Text.create(outDoc);
51 try (TextGenerator textGenerator = new TextGenerator(text, lineNumberFont, fontSize, null)) {
52 // Iterate over all vertical positions found in the input
53 for(double y : lineYPositions) {
54 // The line number string
55 String lineNumberString = String.valueOf(++lineNumber);
56
57 // The width of the line number string when shown on the page
58 double width = textGenerator.getWidth(lineNumberString);
59
60 // Position line numbers right aligned
61 // with a given distance to the right-most horizontal position
62 // and at the vertical position of the current text fragment
63 textGenerator.moveTo(new Point (leftX - width - distance, y));
64
65 // Show the line number string
66 textGenerator.show(lineNumberString);
67 }
68 }
69 try (ContentGenerator contentGenerator = new ContentGenerator(outPage.getContent(), false)) {
70 // Use a content generator to paint the text onto the page
71 contentGenerator.paintText(text);
72 }
73 }
74}
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}
Add stamp 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 font = Font.CreateFromSystem(outDoc, "Arial", "Italic", true);
13
14 // Get the color space
15 ColorSpace colorSpace = ColorSpace.CreateProcessColorSpace(outDoc, ProcessColorSpaceType.Rgb);
16
17 // Choose the RGB color value
18 double[] color = { 1.0, 0.0, 0.0 };
19 Transparency transparency = new Transparency(alpha);
20
21 // Create paint object with the choosen RGB color
22 paint = Paint.Create(outDoc, colorSpace, color, transparency);
23
24 // Define copy options
25 PageCopyOptions copyOptions = new PageCopyOptions();
26
27 // Copy all pages from input document
28 foreach (Page inPage in inDoc.Pages)
29 {
30 // Copy page from input to output
31 Page outPage = Page.Copy(outDoc, inPage, copyOptions);
32
33 // Add text to page
34 AddStamp(outDoc, outPage, stampString);
35
36 // Add page to document
37 outDoc.Pages.Add(outPage);
38 }
39}
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 AddStamp(Document outputDoc, Page outPage, string stampString)
2{
3 // Create content generator and text object
4 using ContentGenerator gen = new ContentGenerator(outPage.Content, false);
5 Text text = Text.Create(outputDoc);
6
7 // Create text generator
8 using (TextGenerator textgenerator = new TextGenerator(text, font, fontSize, null))
9 {
10 // Calculate point and angle of rotation
11 Point rotationCenter = new Point
12 {
13 X = outPage.Size.Width / 2.0,
14 Y = outPage.Size.Height / 2.0
15 };
16 double rotationAngle = Math.Atan2(outPage.Size.Height,
17 outPage.Size.Width) / Math.PI * 180.0;
18
19 // Rotate textinput around the calculated position
20 AffineTransform trans = AffineTransform.Identity;
21 trans.Rotate(rotationAngle, rotationCenter);
22 gen.Transform(trans);
23
24 // Calculate position
25 Point position = new Point
26 {
27 X = (outPage.Size.Width - textgenerator.GetWidth(stampString)) / 2.0,
28 Y = (outPage.Size.Height - font.Ascent * fontSize) / 2.0
29 };
30
31 // Move to position