Merge PDF files while preserving their annotations
Product Version | Product | Author |
---|---|---|
2023.2.713 | PdfProcessing | Yoan Karamanov |
Description
This article describes how to merge PDF documents without loss of supported annotations with the help of the PdfStreamWriter and PdfFileSource.
Solution
The following approach takes a collection of paths, creates a new RadFixedDocument instance, appends the documents from those paths to the newly created RadFixedDocument and returns it as a result.
Merge PDF files
public static RadFixedDocument MergeDocuments(string[] pathsCollection)
{
RadFixedDocument resultFile;
Telerik.Windows.Documents.Fixed.FormatProviders.Pdf.PdfFormatProvider pdfFormatProvider = new Telerik.Windows.Documents.Fixed.FormatProviders.Pdf.PdfFormatProvider();
using (MemoryStream stream = new MemoryStream())
{
using (PdfStreamWriter fileWriter = new PdfStreamWriter(stream, leaveStreamOpen: true))
{
foreach (string path in pathsCollection)
{
using (PdfFileSource fileSource = new PdfFileSource(new MemoryStream(File.ReadAllBytes(path))))
{
for (int i = 0; i < fileSource.Pages.Length; i++)
{
PdfPageSource sourcePage = fileSource.Pages[i];
using (PdfPageStreamWriter resultPage = fileWriter.BeginPage(sourcePage.Size))
{
// set content
resultPage.WriteContent(sourcePage);
}
}
}
}
}
resultFile = pdfFormatProvider.Import(stream);
}
return resultFile;
}