In this post, we will learn how to generate a single pdf file from multiple pdf files using PdfSharp library in C#.
For this example, first, we need to install PdfSharp NuGet package for accessing classes and methods of PdfSharp.
Here is a step by step example of generating pdf files and merging files.
First, install the package in the project.
Install-Package PdfSharp -Version 1.50.4845-RC2a
The second one is adding the below namespace in cs file.
- using PdfSharp.Drawing;
- using PdfSharp.Pdf;
- using PdfSharp.Pdf.IO;
- using System.IO;
After adding the above namespace, get all already generated pdf files from the folder.
- string[] pdfs = Directory.GetFiles(YourPDFFolderPathHere);
The above code returns all pdf files from the folder and the result gets in string array that contains file path. Now, create one function for merging pdf files.
- private void MergeMultiplePDFIntoSinglePDF(string outputFilePath, string[] pdfFiles) {
- PdfDocument document = new PdfDocument();
- foreach(string pdfFile in pdfFiles) {
- PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
- document.Version = inputPDFDocument.Version;
- foreach(PdfPage page in inputPDFDocument.Pages) {
- document.AddPage(page);
- }
-
- System.IO.File.Delete(pdfFile);
- }
-
- XFont font = new XFont("Verdana", 9);
- XBrush brush = XBrushes.Black;
-
- string noPages = document.Pages.Count.ToString();
-
- for (int i = 0; i < document.Pages.Count; ++i) {
- PdfPage page = document.Pages[i];
-
- XRect layoutRectangle = new XRect(240 , page.Height - font.Height - 10 , page.Width , font.Height );
- using(XGraphics gfx = XGraphics.FromPdfPage(page)) {
- gfx.DrawString("Page " + (i + 1).ToString() + " of " + noPages, font, brush, layoutRectangle, XStringFormats.Center);
- }
- }
- document.Options.CompressContentStreams = true;
- document.Options.NoCompression = false;
-
- document.Save(outputFilePath);
- }
The above code, first, merges all pdf files given in string array and in the second step, sets page number.
To call this function, you can use the below code.
- static void Main(string[] args) {
- string[] pdfs = Directory.GetFiles(YourPDFFolderPathHere);
- MergeMultiplePDFIntoSinglePDF("TestPDFFile.pdf", pdfs);
- }