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

Merging two pages from different documents into a single page

Product Version Product Author
2021.2.615 RadPdfProcessing Martin Velikov

Description

This article shows how to merge two pages from different documents into a single page.

Solution

The provided code snippet demonstrates how to import two PDF documents using the PdfFileSource, get their first pages using the PdfPageSource, and merge them on a single page using the PdfStreamWriter.

Merge two pages from different documents into a single page

string firstDocument = "SampleDocument1.pdf"; 
string secondDocument = "SampleDocument2.pdf"; 
string mergedPdf = "Merged.pdf"; 
 
using (FileStream fileStream = File.OpenWrite(mergedPdf)) 
{ 
    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); 
            } 
        } 
    } 
} 
In this article