copy pages from one pdf document to another

From
Jump to: navigation, search

Introduction

In order to copy one or more pages from one PDF document to another you can just copy the actual content without copying the Page objects. Using this technique you can also create visual page thumbnails based on their content. The code below demonstrates both features.

Code

Let's assume we have a small console app and two PDF files: source.pdf and destination.pdf. We would like to copy one page from the first file to the second file and also create additional page tiled with the content from the first file's page.

static void Main(string[] args)
{
    // open source and destination docs
    using (FixedDocument sourceDocument = 
        new FixedDocument(File.OpenRead("../../data/source.pdf")), 
    destinationDocument = 
        new FixedDocument(File.OpenRead("../../data/destination.pdf")))
    {
        // just insert the desired source page to the
        // destination doc
        // TIP: you can use the same doc as source and destination
        destinationDocument.Pages.Add(sourceDocument.Pages[0]);

        // another nice trick is the ability to create page
        // thumbnails", e.g. as below.
        Page page = new Page();

        // we'll use for calculating transforms below
        double scaleFactor = 0.5;
        // number of thumbnails in a row and column
        int numberOfThumbnails = (int)Math.Round(1.0/scaleFactor);

        // generate the thumnails, basically fit the source page
        // as many times as we can based on scalefactor
        for (int j = 0; j <numberOfThumbnails; j++)
        {
            double xOffset = page.Boundary.MediaBox.Width*(scaleFactor*j);
            
            for (int i = 1; i <= numberOfThumbnails; ++i)
            {
                        page.Content.SaveGraphicsState();
                        page.Content.SetTranslate(xOffset, 
                            page.Boundary.MediaBox.Height*(1 - scaleFactor*i));
                        page.Content.SetScale(scaleFactor, scaleFactor);
                        page.Content.AppendContent(sourceDocument.Pages[0].Content);
                        page.Content.RestoreGraphicsState();
            }
        }

        // add new page
        destinationDocument.Pages.Add(page);

        // save and open for preview
        using (Stream outputStream = File.Create("combined.pdf"))
        {
            destinationDocument.Save(outputStream);
        }

        Process.Start("combined.pdf");
    }
}

The code above shows that you can actually manipulate the copied content the same way you would do it for e.g. newly generated content. So all possible transformations are at your service.

Output

The image below demonstrates the results produced by this code sample:

apitron pdf kit copy pages from pdf document and create thumbnails sample