New to Telerik Document Processing? Download free 30-day trial

Merge two document pages into a new single page

Product Version Product Author
2021.2.614 RadPdfProcessing Martin Velikov

Description

This article describes how to import two PDF documents and merge their first pages into a new single page.

Solution

The following example demonstrates how to use the PdfStreamWriter in order to import and merge the first pages of two different documents into a new single page.

Example

string firstDocument = "SampleDocument1.pdf"; 
string secondDocument = "SampleDocument2.pdf"; 
 
string exportedPdf = "Merged.pdf"; 
if (File.Exists(exportedPdf)) 
{ 
    File.Delete(exportedPdf); 
} 
 
using (FileStream fileStream = File.OpenWrite(exportedPdf)) 
{ 
    using (PdfStreamWriter fileWriter = new PdfStreamWriter(fileStream)) 
    { 
        using (PdfFileSource firstDocumentToMerge = new PdfFileSource(File.OpenRead(firstDocument))) 
        using (PdfFileSource secondDocumentToMerge = new PdfFileSource(File.OpenRead(secondDocument))) 
        { 
            PdfPageSource firstDocumentPageToMerge = firstDocumentToMerge.Pages[0]; 
            PdfPageSource secondDocumentPageToMerge = secondDocumentToMerge.Pages[0]; 
 
            double largestPageHeight = Math.Max(firstDocumentPageToMerge.Size.Height, secondDocumentPageToMerge.Size.Height); 
            Size size = new Size(firstDocumentPageToMerge.Size.Width + secondDocumentPageToMerge.Size.Width, largestPageHeight); 
 
            using (PdfPageStreamWriter newPage = fileWriter.BeginPage(size)) 
            { 
                newPage.WriteContent(firstDocumentPageToMerge); 
 
                double offsetX = newPage.PageSize.Width / 2; 
                newPage.ContentPosition.Translate(offsetX, 0); 
                newPage.WriteContent(secondDocumentPageToMerge); 
            } 
        } 
    } 
} 
More information you can find in the PdfPageStreamWriter, PdfFileSource, and PdfPageSource help articles.
In this article