Merge PDF Documents
RadPdfProcessing provides support for merging multiple PDF documents into one using the following approaches:
Using the RadFixedDocument.Merge Method
You can merge PDF documents out-of-the-box with the Merge method of RadFixedDocument. This method clones the source document and appends it to the current instance of RadFixedDocument:
int timeoutInterval = 100;
string pdfFolderPath = @"..\..\..\Pdf Files";
// Adjust this path to your PDF files directory
string[] pathsCollection = Directory.GetFiles(pdfFolderPath);
RadFixedDocument resultFile = new RadFixedDocument();
PdfFormatProvider pdfFormatProvider = new PdfFormatProvider();
foreach (string path in pathsCollection)
{
RadFixedDocument document;
using (Stream stream = File.OpenRead(path))
{
document = pdfFormatProvider.Import(stream, TimeSpan.FromSeconds(timeoutInterval));
resultFile.Merge(document);
}
}
string outputFilePath = "merged_by_RadFixedDocument.pdf";
File.Delete(outputFilePath);
using (Stream output = File.OpenWrite(outputFilePath))
{
pdfFormatProvider.Export(resultFile, output, TimeSpan.FromSeconds(timeoutInterval));
}
Process.Start(new ProcessStartInfo() { FileName = outputFilePath, UseShellExecute = true });
Using the PdfStreamWriter
An alternative approach is using the PdfStreamWriter allowing you to merge pages from different PDF documents:
int timeoutInterval = 100;
string pdfFolderPath = @"..\..\..\Pdf Files";
// Adjust this path to your PDF files directory
string[] pathsCollection = Directory.GetFiles(pdfFolderPath);
RadFixedDocument resultFile;
PdfFormatProvider pdfFormatProvider = new 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))
{
resultPage.WriteContent(sourcePage);
}
}
}
}
}
resultFile = pdfFormatProvider.Import(stream, TimeSpan.FromSeconds(timeoutInterval));
}
string outputFilePath = "merged_by_PdfStreamWriter.pdf";
File.Delete(outputFilePath);
using (Stream output = File.OpenWrite(outputFilePath))
{
pdfFormatProvider.Export(resultFile, output, TimeSpan.FromSeconds(timeoutInterval));
}
Process.Start(new ProcessStartInfo() { FileName = outputFilePath, UseShellExecute = true });
The following SDK example is quite useful on this topic as well: SDK Demo.