Chapter 6: Reusing existing PDF documents
Which version?
This Tutorial was written with iText 7.0.x in mind, however, if you go to the linked Examples you will find them for the latest available version of iText. If you are looking for a specific version, you can always download these examples from our GitHub repo (Java/.NET).
In this chapter, we'll do some more document manipulation, but there will be a subtle difference in approach. In the examples of the previous chapter, we created one PdfDocument
instance that linked a PdfReader
to a PdfWriter
. We manipulated a single document.
In this chapter, we'll always create at least two PdfDocument
instances: one or more for the source document(s), and one for the destination document.
Scaling, tiling, and N-upping
Let's start with some examples that scale and tile a document.
Scaling PDF pages
Suppose that we have a PDF file with a single page, measuring 16.54 by 11.69 in. See Figure 6.1.
Now we want to create a PDF file with three pages. In page one, the original page is scaled down to 11.69 x 8.26 in as shown in Figure 6.2. On page 2, the original page size is preserved. On page 3, the original page is scaled up to 23.39 x 16.53 in as shown in Figure 6.3.
The TheGoldenGateBridge_Scale_Shrink example shows how it's done.
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfDocument origPdf = new PdfDocument(new PdfReader(src));
PdfPage origPage = origPdf.getPage(1);
Rectangle orig = origPage.getPageSizeWithRotation();
//Add A4 page
PdfPage page = pdf.addNewPage(PageSize.A4.rotate());
//Shrink original page content using transformation matrix
PdfCanvas canvas = new PdfCanvas(page);
AffineTransform transformationMatrix = AffineTransform.getScaleInstance(
page.getPageSize().getWidth() / orig.getWidth(),
page.getPageSize().getHeight() / orig.getHeight());
canvas.concatMatrix(transformationMatrix);
PdfFormXObject pageCopy = origPage.copyAsFormXObject(pdf);
canvas.addXObject(pageCopy, 0, 0);
//Add page with original size
pdf.addPage(origPage.copyTo(pdf));
//Add A2 page
page = pdf.addNewPage(PageSize.A2.rotate());
//Scale original page content using transformation matrix
canvas = new PdfCanvas(page);
transformationMatrix = AffineTransform.getScaleInstance(
page.getPageSize().getWidth() / orig.getWidth(),
page.getPageSize().getHeight() / orig.getHeight());
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, 0, 0);
pdf.close();
origPdf.close();
In this code snippet, we create a PdfDocument
instance that will create a new PDF document (line 1); and we create a PdfDocument
instance that will read an existing PDF document (line 2). We get a PdfPage
instance for the first page of the existing PDF (line 3), and we get its dimensions (line 4). We then add three pages to the new PDF document:
We add an A4 page using landscape orientation (line 7) and we create a
PdfCanvas
object for that page. Instead of calculating thea
,b
,c
,d
,e
, andf
value for a transformation matrix that will scale the coordinate system, we use anAffineTransform
instance using thegetScaleInstance()
method (line 9-12). We apply that transformation (line 13), we create a Form XObject containing the original page (line 14) and we add that XObject to the new page (line 15).Adding the original page in its original dimensions is much easier. We just create a new page by copying the
origPage
to the newPdfDocument
instance, and we add it to thepdf
using theaddPage()
method (line 18).Scaling up and shrinking is done in the exact same way. This time, we add a new A2 page using landscape orientation (line 21) and we use the exact same code we had before to scale the coordinate system (line 23-27). We reuse the
pageCopy
object and add it to thecanvas
(line 29).
We close the pdf
to finalize the new document (line 30) and we close the origPdf
to release the resources of the original document.
We can use the same functionality to tile a PDF page.
Tiling PDF pages
Tiling a PDF page means that you distribute the content of one page over different pages. For instance: if you have a PDF with a single page of size A3, you can create a PDF with four pages of a different size –or even the same size–, each showing one quarter of the original A3 page. This is what we've done in Figure 6.4.
Let's take a look at the TheGoldenGateBridge_Tiles example.
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfDocument sourcePdf = new PdfDocument(new PdfReader(src));
PdfPage origPage = sourcePdf.getPage(1);
PdfFormXObject pageCopy = origPage.copyAsFormXObject(pdf);
Rectangle orig = origPage.getPageSize();
//Tile size
Rectangle tileSize = PageSize.A4.rotate();
AffineTransform transformationMatrix = AffineTransform.getScaleInstance(
tileSize.getWidth() / orig.getWidth() * 2f,
tileSize.getHeight() / orig.getHeight() * 2f);
//The first tile
PdfPage page = pdf.addNewPage(PageSize.A4.rotate());
PdfCanvas canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, 0, -orig.getHeight() / 2f);
//The second tile
page = pdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, -orig.getWidth() / 2f, -orig.getHeight() / 2f);
//The third tile
page = pdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, 0, 0);
//The fourth tile
page = pdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, -orig.getWidth() / 2f, 0);
// closing the documents
pdf.close();
sourcePdf.close();
We've seen lines 1-5 before; we already used them in the previous example. In line 7, we define a tile size, and we create a transformationMatrix
to scale the coordinate system depending on the original size and the tile size. Then we add the tiles, one by one: line 12-15, line 17-20, line 22-25, and line 27-30 are identical, except for one detail: the offset used in the addXObject()
method.
Let's use the PDF with the Golden Gate Bridge for one more example. Let's do the opposite of tiling: let's N-up a PDF.
N-upping a PDF
Figure 6.5 shows what we mean by N-upping. In the next example, we're going to put N pages on one single page.
In the TheGoldenGateBridge_N_up example, N is equal to 4. We will put 4 pages on one single page.
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfDocument sourcePdf = new PdfDocument(new PdfReader(SRC));
//Original page
PdfPage origPage = sourcePdf.getPage(1);
Rectangle orig = origPage.getPageSize();
PdfFormXObject pageCopy = origPage.copyAsFormXObject(pdf);
//N-up page
PageSize nUpPageSize = PageSize.A4.rotate();
PdfPage page = pdf.addNewPage(nUpPageSize);
PdfCanvas canvas = new PdfCanvas(page);
//Scale page
AffineTransform transformationMatrix = AffineTransform.getScaleInstance(
nUpPageSize.getWidth() / orig.getWidth() / 2f,
nUpPageSize.getHeight() / orig.getHeight() / 2f);
canvas.concatMatrix(transformationMatrix);
//Add pages to N-up page
canvas.addXObject(pageCopy, 0, orig.getHeight());
canvas.addXObject(pageCopy, orig.getWidth(), orig.getHeight());
canvas.addXObject(pageCopy, 0, 0);
canvas.addXObject(pageCopy, orig.getWidth(), 0);
// close the documents
pdf.close();
sourcePdf.close();
So far, we've only reused a single page from a single PDF in this chapter. In the next series of examples, we'll assemble different PDF files into one.
Assembling documents
Let's go from San Francisco to Los Angeles, and take a look at Figure 6.6 where we'll find three documents about the Oscars.
The documents are:
88th_reminder_list.pdf: a 32-page document, entitled "Reminder List of Productions Eligible for the 88th Academy Awards",
88th_noms_announcement.pdf: a 15-page document, entitled "Oscars"
oscars_movies_checklist_2016.pdf: a 1-page document, entitled "Oscars Movie Checklist 2016"
In the next couple of examples, we'll merge these documents.
Merging documents with PdfMerger
Figure 6.7 shows a PDF that was created by merging the first 32-page document with the second 15-page document, resulting in a 47-page document.
The code of the 88th_Oscar_Combine example is almost self-explanatory.
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfMerger merger = new PdfMerger(pdf);
//Add pages from the first document
PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(SRC1));
merger.merge(firstSourcePdf, 1, firstSourcePdf.getNumberOfPages());
//Add pages from the second pdf document
PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(SRC2));
merger.merge(secondSourcePdf, 1, secondSourcePdf.getNumberOfPages());
// merge and close
merger.close();
firstSourcePdf.close();
secondSourcePdf.close();
pdf.close();
We create a PdfDocument
to create a new PDF (line 1). The PdfMerger
class is new. It's a class that will make it easier for us to reuse pages from existing documents (line 2). Just like before, we create a PdfDocument
for the source file (line 4, line 7); we then add all the pages to the merger
instance (line 5, line 8). Once we're done adding pages, we merge()
(line 10) and close()
(line 11-13).
We don't need to add all the pages if we don't want to. We can easily add only a limited selection of pages. See for instance the 88th_Oscar_CombineXofY example.
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfMerger merger = new PdfMerger(pdf);
PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(SRC1));
merger.merge(firstSourcePdf, Arrays.asList(1, 5, 7, 1));
PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(SRC2));
merger.merge(secondSourcePdf, Arrays.asList(1, 15));
merger.close();
firstSourcePdf.close();
secondSourcePdf.close();
pdf.close();
Now the resulting document only has six pages. Pages 1, 5, 7, 1 from the first document (the first page is repeated), and pages 1 and 15 from the second document. PdfMerger
is a convenience class that makes merging documents a no-brainer. In some cases however, you'll want to add pages one by one.
Adding pages to a PdfDocument
Figure 6.8 shows the result of the merging of specific pages based on a Table of Contents (TOC) that we'll create on the fly. This TOC contains link annotations that allow you to jump to a specific page if you click an entry of the TOC.
The 88th_Oscar_Combine_AddTOC example is more complex than the two previous examples. Let's examine it step by step.
Suppose that we have a TreeMap
of all the categories the movie "The Revenant" was nominated for, where the key is the nomination and the value is the page number of the document where the nomination is mentioned.
public static final Map TheRevenantNominations =
new TreeMap();
static {
TheRevenantNominations.put("Performance by an actor in a leading role", 4);
TheRevenantNominations.put(
"Performance by an actor in a supporting role", 4);
TheRevenantNominations.put("Achievement in cinematography", 4);
TheRevenantNominations.put("Achievement in costume design", 5);
TheRevenantNominations.put("Achievement in directing", 5);
TheRevenantNominations.put("Achievement in film editing", 6);
TheRevenantNominations.put("Achievement in makeup and hairstyling", 7);
TheRevenantNominations.put("Best motion picture of the year", 8);
TheRevenantNominations.put("Achievement in production design", 8);
TheRevenantNominations.put("Achievement in sound editing", 9);
TheRevenantNominations.put("Achievement in sound mixing", 9);
TheRevenantNominations.put("Achievement in visual effects", 10);
}
The first lines of the code that creates the PDF are pretty simple.
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document document = new Document(pdfDoc);
document.add(new Paragraph(new Text("The Revenant nominations list"))
.setTextAlignment(TextAlignment.CENTER));
But we need to take a really close look once we start to loop over the entries in the TreeMap
.
PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(SRC1));
for (Map.Entry entry : TheRevenantNominations.entrySet()) {
//Copy page
PdfPage page = firstSourcePdf.getPage(entry.getValue()).copyTo(pdfDoc);
pdfDoc.addPage(page);
//Overwrite page number
Text text = new Text(String.format(
"Page %d", pdfDoc.getNumberOfPages() - 1));
text.setBackgroundColor(Color.WHITE);
document.add(new Paragraph(text).setFixedPosition(
pdfDoc.getNumberOfPages(), 549, 742, 100));
//Add destination
String destinationKey = "p" + (pdfDoc.getNumberOfPages() - 1);
PdfArray destinationArray = new PdfArray();
destinationArray.add(page.getPdfObject());
destinationArray.add(PdfName.XYZ);
destinationArray.add(new PdfNumber(0));
destinationArray.add(new PdfNumber(page.getMediaBox().getHeight()));
destinationArray.add(new PdfNumber(1));
pdfDoc.addNameDestination(destinationKey, destinationArray);
//Add TOC line with bookmark
Paragraph p = new Paragraph();
p.addTabStops(
new TabStop(540, TabAlignment.RIGHT, new DottedLine()));
p.add(entry.getKey());
p.add(new Tab());
p.add(String.valueOf(pdfDoc.getNumberOfPages() - 1));
p.setProperty(Property.ACTION, PdfAction.createGoTo(destinationKey));
document.add(p);
}
firstSourcePdf.close();
Here we go:
Line 1: we create a
PdfDocument
with the source file containing all the info about all the nominations.Line 2: we loop over an alphabetic list of the nominations for "The Revenant".
Line 3-4: we get the page that corresponds with the nomination, and we add a copy to the
PdfDocument
.Line 7-8: we create an iText
Text
element containing the page number. We subtract 1 from that page number, because the first page in our document is the unnumbered page containing the TOC.Line 9: we set the background color to
Color.WHITE
. This will cause an opaque white rectangle to be drawn with the same size of theText
. We do this to cover the original page number.Line 10-11: we add this
text
at a fixed position on the the current page in thePdfDocument
. The fixed position is: X = 549, Y = 742, and the width of the text is 100 user units.Line 13: we create a key we'll use to name the destination.
Line 14-19: we create a
PdfArray
containing information about the destination. We'll refer to the page we've just added (line 15), we'll define the destination using an X,Y coordinate and a zoom factor (line 16), we add the values of X (line 17), Y (line 18), and the zoom factor (line 19).Line 20: we add the named destination to the
PdfDocument
.Line 22: we create an empty
Paragraph
.Line 23-24: we add a tab stop at position X = 540, we define that the tab needs to be right aligned, and the space preceding the tab needs to be a
DottedLine
.Line 25: we add the nomination to the
Paragraph
.Line 26: we introduce a
Tab
.Line 27: we add the page number minus 1 (because the page with the TOC is page 0).
Line 28: we add an action that will be triggered when someone clicks on the
Paragraph
.Line 29: we add the
Paragraph
to thedocument
.Line 31: we close the source document.
We've been introducing a lot of new functionality that really requires a more in-depth tutorial, but we're looking at this example for one main reason: to show that there's a significant difference between the PdfDocument
object, to which a new page is added with every pass through the loop, and the Document
object, to which we keep adding Paragraph
objects on the first page.
Let's go through some of these steps one more time to add the checklist.
//Add the last page
PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(SRC2));
PdfPage page = secondSourcePdf.getPage(1).copyTo(pdfDoc);
pdfDoc.addPage(page);
//Add destination
PdfArray destinationArray = new PdfArray();
destinationArray.add(page.getPdfObject());
destinationArray.add(PdfName.XYZ);
destinationArray.add(new PdfNumber(0));
destinationArray.add(new PdfNumber(page.getMediaBox().getHeight()));
destinationArray.add(new PdfNumber(1));
pdfDoc.addNameDestination("checklist", destinationArray);
//Add TOC line with bookmark
Paragraph p = new Paragraph();
p.addTabStops(new TabStop(540, TabAlignment.RIGHT, new DottedLine()));
p.add("Oscars\u00ae 2016 Movie Checklist");
p.add(new Tab());
p.add(String.valueOf(pdfDoc.getNumberOfPages() - 1));
p.setProperty(Property.ACTION, PdfAction.createGoTo("checklist"));
document.add(p);
secondSourcePdf.close();
// close the document
document.close();
This code snippet adds the check list with the overview of all the nominations. An extra line saying "Oscars® 2016 Movie Checklist" is added to the TOC.
This example introduces a couple of new concepts for educational purposes. It shouldn't be used in a real-world application, because it contains a major flaw. We make the assumption that the TOC will consist of only one page. Suppose that we added more lines to the document
object, then you would see a strange phenomenon: the text that doesn't fit on the first page, would be added on the second page. This second page wouldn't be a new page, it would be the first page that we added in the loop. In other words: the content of the first imported page would be overwritten. This is a problem that can be fixed, but it's outside the scope of this short introductory tutorial.
We'll finish this chapter with some examples in which we merge forms.
Merging forms
Merging forms is special. In HTML, it's possible to have more than one form in a single HTML file. That's not the case for PDF. In a PDF file, there can be only one form. If you want to merge two forms and you want to preserve the forms, you need to use a special method and a special IPdfPageExtraCopier
implementation.
Figure 6.9 shows the combination of two different forms, subscribe.pdf and state.pdf
The Combine_Forms example is different from what we had before.
PdfDocument destPdfDocument = new PdfDocument(new PdfWriter(dest));
PdfDocument[] sources = new PdfDocument[] {
new PdfDocument(new PdfReader(SRC1)),
new PdfDocument(new PdfReader(SRC2))
};
for (PdfDocument sourcePdfDocument : sources) {
sourcePdfDocument.copyPagesTo(
1, sourcePdfDocument.getNumberOfPages(),
destPdfDocument, new PdfPageFormCopier());
sourcePdfDocument.close();
}
destPdfDocument.close();
In this code snippet, we use the copyPageTo()
method. The first two parameters define the from/to range for the pages of the source document. The third parameter defines the destination document. The fourth parameter indicates that we are copying forms and that the two different forms in the two different documents should be merged into a single form. PdfPageFormCopier
is an implementation of the IPdfPageExtraCopier
interface that makes sure that the two different forms are merged into one single form.
Merging two forms isn't always trivial, because the name of each field needs to be unique. Suppose that we would merge the same form twice. Then we would have two widget annotations for each field. A field with a specific name, for instance "name"
, can be visualized using different widget annotations, but it can only have one value. Suppose that you would have a widget annotation for the field "name"
on page one, and a widget annotation for the same field on page two, then changing the value shown in the widget annotation on one page would automatically also change the value shown in the widget annotations on the other page.
In the next example, we are going to fill out and merge the same form, state.pdf, as many times as there are entries in the CSV file united_states.csv; see Figure 6.10.
If we'd keep the names of the fields the way they are in the original form, changing the value of the state "ALABAMA" into "CALIFORNIA", would also change the name "ALASKA" on the second page, and the name of all the other states on the other pages. We made sure that this doesn't happen by renaming all the fields before merging the forms.
Let's take a look at the FillOutAndMergeForms example.
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(dest));
BufferedReader bufferedReader = new BufferedReader(new FileReader(DATA));
String line;
boolean headerLine = true;
int i = 1;
while ((line = bufferedReader.readLine()) != null) {
if (headerLine) {
headerLine = false;
continue;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfDocument sourcePdfDocument = new PdfDocument(
new PdfReader(SRC), new PdfWriter(baos));
//Rename fields
i++;
PdfAcroForm form = PdfAcroForm.getAcroForm(sourcePdfDocument, true);
form.renameField("name", "name_" + i);
form.renameField("abbr", "abbr_" + i);
// ... (removed repetitive lines)
form.renameField("dst", "dst_" + i);
//Fill out fields
StringTokenizer tokenizer = new StringTokenizer(line, ";");
Map fields = form.getFormFields();
fields.get("name_" + i).setValue(tokenizer.nextToken());
fields.get("abbr_" + i).setValue(tokenizer.nextToken());
// ... (removed repetitive lines)
fields.get("dst_" + i).setValue(tokenizer.nextToken());
// close the source document and use it to create a new PdfDocument
sourcePdfDocument.close();
sourcePdfDocument = new PdfDocument(
new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
//Copy pages
sourcePdfDocument.copyPagesTo(
1, sourcePdfDocument.getNumberOfPages(),
pdfDocument, new PdfPageFormCopier());
sourcePdfDocument.close();
}
bufferedReader.close();
pdfDocument.close();
Let's start by looking at the code inside the while
loop. We're looping over the different states of the USA stored in a CSV file (line 6). We skip the first line that contains the information for the column headers (line 7-10). The next couple of lines are interesting. So far, we've always been writing PDF files to disk. In this example, we are creating PDF files in memory using a ByteArrayOutputStream
(line 11-13).
As mentioned before, we start by renaming all the fields. We get the PdfAcroForm
instance (line 16) and we use the renameField()
method to rename fields such as "name"
to "name_1"
, "name_2"
, and so on. Note that we've skipped some lines for brevity in the code snippet. Once we've renamed all the fields, we set their value (line 23-27).
When we close the sourcePdfDocument
(line 29), we have a complete PDF file in memory. We create a new sourcePdfDocument
using a ByteArrayInputStream
created with that file in memory (line 30-31). We can now copy the pages of that new sourcePdfDocument
to our destination pdfDocument
.
This is a rather artificial example, but it's a good example to explain some of the usual pitfalls when merging forms:
Without the
PdfPageFormCopier
, the forms won't be correctly merged.One field can only have one value, no matter how many times that field is visualized using a widget annotation.
A more common use case, is to fill out and flatten the same form multiple times in memory, simultaneously merging all the resulting documents in one PDF.
Merging flattened forms
Figure 6.11 shows two PDF documents that were the result of the same procedure: we filled out a form in memory as many times as there are states in the USA. We flattened these filled out forms, and we merged them into one single document.
From the outside, these documents look identical, but if we look at their file size in Figure 12, we see a huge difference.
What is causing this difference in file size? We need to take a look at the FillOutFlattenAndMergeForms example to find out.
PdfDocument destPdfDocument =
new PdfDocument(new PdfWriter(dest1));
PdfDocument destPdfDocumentSmartMode =
new PdfDocument(new PdfWriter(dest2).setSmartMode(true));
BufferedReader bufferedReader = new BufferedReader(new FileReader(DATA));
String line;
boolean headerLine = true;
while ((line = bufferedReader.readLine()) != null) {
if (headerLine) {
headerLine = false;
continue;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfDocument sourcePdfDocument =
new PdfDocument(new PdfReader(SRC), new PdfWriter(baos));
//Fill out fields
PdfAcroForm form = PdfAcroForm.getAcroForm(sourcePdfDocument, true);
StringTokenizer tokenizer = new StringTokenizer(line, ";");
Map fields = form.getFormFields();
fields.get("name").setValue(tokenizer.nextToken());
fields.get("abbr").setValue(tokenizer.nextToken());
// ... (removed repetitive lines)
fields.get("dst").setValue(tokenizer.nextToken());
//Flatten fields
form.flattenFields();
sourcePdfDocument.close();
sourcePdfDocument = new PdfDocument(
new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
//Copy pages
sourcePdfDocument.copyPagesTo(
1, sourcePdfDocument.getNumberOfPages(), destPdfDocument, null);
sourcePdfDocument.copyPagesTo(
1, sourcePdfDocument.getNumberOfPages(), destPdfDocumentSmartMode, null);
sourcePdfDocument.close();
}
bufferedReader.close();
destPdfDocument.close();
destPdfDocumentSmartMode.close();
In this code snippet, we create two documents simultaneously:
The
destPdfDocument
instance (line 1-2) is created the same way we've been creatingPdfDocument
instances all along.The
destPdfDocumentSmartMode
instance (line 3-4) is also created that way, but we've turned on the smart mode.
We loop over the lines of the CSV file like we did before (line 8), but since we're going to flatten the forms, we no longer have to rename the fields. The fields will be lost due to the flattening process anyway. We create a new PDF document in memory (line 12-15) and we fill out the fields (line 17-23). We flatten the fields (line 25) and close the document created in memory (line 26). We use the file created in memory to create a new source file. We add all the pages of this source file to the two PdfDocument
instances, one working in normal mode, the other in smart mode. We no longer need to use a PdfPageFormCopier
instance, because the forms have been flattened; they are no longer forms.
What is the difference between these normal and smart modes?
When we copy the pages of the filled out forms to the
PdfDocument
working in normal mode, thePdfDocument
processes each document as if it's totally unrelated to the other documents that are being added. In this case, the resulting document will be bloated, because the documents are related: they all share the same template. That template is added to the PDF document as many times as there are states in the USA. In this case, the result is a file of about 12 MBytes.When we copy the pages of the filled out forms to the
PdfDocument
working in smart mode, thePdfDocument
will take the time to compare the resources of each document. If two separate documents share the same resources (e.g. a template), then that resource is copied to the new file only once. In this case, the result can be limited to 365 KBytes.
Both the 12 MBytes and the 365 KBytes files look exactly the same when opened in a PDF viewer or when printed, but it goes without saying that the 365 KBytes files is to be preferred over the 12 MBytes file.
Summary
In this chapter, we've been scaling, tiling, N-upping one file with a different file as result. We've also assembled files in many different ways. We discovered that there are quite some pitfalls when merging interactive forms. Much more remains to be said about reusing content from existing PDF documents.
In the next chapter, we'll discuss PDF documents that comply to special PDF standards such as PDF/UA and PDF/A. We'll discover that merging PDF/A documents also requires some special attention.