How do I reduce file size during PDF merging or stamping operations?

Q: We are trying to stamp some text on all pages in the document and
merge this document with another document using the code below.

For some reason the resulting PDF file is significantly larger. I know
that font embedding makes file larger, but in some cases we
significant increase in file size. Please advise.

------------Start Sample code----------------

PDFDoc doc=null;
PDFDoc tempDoc=null;

string sourceFile=@"F:\test\input.pdf";
string destFile=@"F:\test\output.pdf";

try
{
doc=new PDFDoc(sourceFile);
tempDoc=new PDFDoc();

int numPages=doc.GetPagesCount();

Element element=null;
ElementBuilder eb=new ElementBuilder();
ElementWriter writer = new ElementWriter();
Obj form=null;

for(int start=1;start<=numPages;start++)
{
  Page page=doc.PageFind(start).Current();
  writer.Begin(page);

  element
=eb.CreateTextBegin(pdftron.PDF.Font.CreateTrueTypeFontdoc,"font.fft" ,true,false),
12);
  element.SetTextMatrix(1, 0, 0, 1, 200,200);
  writer.WriteElement(element);
  element = eb.CreateTextRun("Hello World");
  writer.WriteElement(element);
  writer.WriteElement(eb.CreateTextEnd());
  form = writer.End();
  form.Put("Subtype", Obj.CreateName("Form"));
  form.Put("txt", Obj.CreateBool(true));
  form.Put("single", Obj.CreateBool(true));
  element=eb.CreateForm(form);
  writer.WriteElement(element);
  writer.End();

  tempDoc.PagePushBack(page);
}

tempDoc.Save(destFile,0);
}
catch(PDFNetException pex)
{
MessageBox.Show(pex.ToString());
}
------
A: The file size is getting larger because you are creating a new font
for every PDF page you stamp. You can speed us the code and cut down
on the file size by creating the font only once (before the ‘for’
loop). For example:

...
pdftron.PDF.Font fnt =
pdftron.PDF.Font.CreateTrueTypeFontdoc,"font.fft" ,true,false);
for(int start=1;start<=numPages;start++) {
  Page page=doc.PageFind(start).Current();
  writer.Begin(page);

  element =eb.CreateTextBegin(fnt,12);
  element.SetTextMatrix(1, 0, 0, 1, 200,200);
  ...
}
...

Q: Thanks. This was helpful. Now we are facing a similar issue when
moving/merging pages from one document to another:


PDFDoc doc=new PDFDoc(sourceFile);
PDFDoctempDoc=new PDFDoc();
int numPages=doc.GetPageCount();
for(int i=1;i<=numPages;i++) {
Page page=doc.GetPage(i);
tempDoc.PagePushBack(page);
}
tempDoc.Save(destFile,0);

After page copy from ‘doc’ to ‘tempDoc’, the filesize increased
significantly.


A: If you need to copy more than one page, you should use
pdfdoc.ImportPages() before inserting the pages in the destination
page sequence. If pdfdoc.ImportPages() is not called, all shared
resources will be duplicated for each page and the resulting in the
increase of file size. For more info, please see
http://www.pdftron.com/net/usermanual.html#copy_pg as well as the last
code sample in PDFPage sample project - http://www.pdftron.com/net/samplecode.html#PDFPage).