How to reduce the file size after altering PDF page content?


We use PDFNet SDK to alter PDF files. In particuar we want to shift
and scale the content of every page in a document (we do this by using
a Matrix2D object and ElementReader/Writer objects). Works as

However, the size of the resulting pdf file is much larger than it's
original size. We tried to follow the advice we found in the PDFNet
FAQ about using the ImportPages method and used
SaveOptions.e_remove_unused when saving.

The code is as follows:

public void Process(string fileName, string outFileName, double
  double shiftY, double scaleX, double scaleY) {
    Page newPage, srcPage;
    int nPageNum = 1;

    PDFDoc inDoc = new PDFDoc(fileName);
    PDFDoc docOut = new PDFDoc();

    ElementReader reader = new ElementReader();
    ElementWriter writer = new ElementWriter();

    PageIterator itrLastPage = inDoc.PageEnd();
    for (PageIterator itrDocPage = inDoc.PageBegin();
        itrDocPage!=itrLastPage; itrDocPage.Next()) {
        srcPage = itrDocPage.Current();
        Rect media_box = srcPage.GetMediaBox();
        newPage = docOut.PageCreate(media_box);


        newPage = docOut.PageFind(nPageNum).Current();
        srcPage = docOut.PageFind(nPageNum + 1).Current();


        Matrix2D pos_mtx = new Matrix2D(scaleX, 0, 0, scaleY, shiftX,

        Element element;
        int cnt = 0;
        while ((element = reader.Next()) != null) {
            if (cnt++ == 0)


        docOut.PageRemove(docOut.PageFind(nPageNum + 1));


    // now use ImportPages to bring down file size
    CompactFile(fileName, outFileName);

public void CompactFile(string inFile, string outFile) {
    PDFDoc inDoc = new PDFDoc(inFile);

    PDFDoc outDoc = new PDFDoc();
    ArrayList copy_pages = new ArrayList();

    PageIterator begin = inDoc.PageBegin();
    PageIterator end = inDoc.PageEnd();
    for (PageIterator itr = begin; itr!=end; itr.Next()) {

    ArrayList imported_pages = outDoc.ImportPages(copy_pages);
    for (int i=0; i != imported_pages.Count; ++i) {

    outDoc.Save(outFile, pdftron.SDF.Doc.SaveOptions.e_remove_unused);


The problem is in the code. In Process() function you are first
copying each page from input to output document. This results in
replication of all resources (for more info see

To avoid this you can do all editing in the directly original document
(i.e. directly inDoc) or you can call first your method CompactFile to
copy all pages from one document to another and then Process() to edit
page content (but without additional copying from inDoc to outDoc).