How do I reduce size of dynamically generated PDF from a set of PDF form templates?

Q: We use PDFNet SDK to fill PDF forms and save them so that they can
be printed. Our use case is very similar to one I found in the FAQ
(http://www.pdftron.com/kb/questions.php?questionid=952) but we have
one big difference in that there are several template files we could
be using in essentially random order and some pages are not using any
template and are created entirely in memory.

We are currently loading the template page, filling it in (using
doc.getField(“fieldName”).setValue(“value”)), then flatten the
template and add it to the final document.
If the page is not from a template we just create a new doc with a
single page, fill in the page and then add the page to the final
document. Then repeat until all pages have been added to the document.

The problem we are having is that the resulting file size is far too
large. When I use Adobe Acrobat to look at the space usage I see that
21% is fonts, 26% is X Object Forms and 24% is ContentStreams with a
total file size of about 3.3MB. If I use Acrobat to optimize the pdf
it shrinks to .94MB with 48% content streams, 11% X object Forms and
17% Fonts.

What would you recommend we do to make the resulting file as small a
possible?


A: Instead of importing a source template in the destination document
multiple times (doc.PagePushBack(src_page)) you can import the live
page only once, then clone it as many times as necessary.

For example:

doc.PagePushFront(src_page);
Page p = doc.GetPage(1);
doc.PagePushBack§;
doc.PagePushBack§;
doc.PagePushBack§;

This way all pages will be sharing the same resources (fonts, images,
etc) and will not be replicated.

The only problem is that all widget annotations will also have the
same name so changing a value on one page will change the
corresponding value on all other pages. To fix this you can traverse
all Widget annotations (e.g. Annotation sample -
http://www.pdftron.com/pdfnet/samplecode.html#Annotation) and rename
associated field (annot.GetField().Rename("…")). Alternatively please
take a look at RenameAllFields() utility function in InteractiveForms
sample (http://www.pdftron.com/pdfnet/
samplecode.html#InteractiveForms) .