A while ago I had to combine PDF files for a project that I was working on, after some research I noticed that there was software available but didn’t have the features I needed or had more features that made it harder to use.
So, I looked for a way to implement an application that allowed to merge PDF files.
Initially I wrote PDF Merger using Java as programming language, at the time, it was the language I was used to.
When I was learning C#, I decide to convert PDF Merger to C# and continue to improve only the C# version.
This post is only based on the C# version since the Java version isn’t updated for some time now.
After compiling and launching PDF Merger we can see the following User Interface.
I tried to keep it basic (to reduce the development time) while making sure all features were easy to use.
We can use Add File or Add Folder to add files but also drag and drop, .
After adding files, we can also change the order they will appear in the output PDF file using the Move Up and Move Down buttons.
We have 3 modes available in PDF Merger:
- Normal – This will create a new PDF file with all pages from PDF1, then PDF2, PDF3, etc.
- Alternate – Only supports 2 input files and the output will be PDF1-Page1, PDF2-Page1, PDF1-Page2, PDF2-Page2.
This mode was created when I had a single side scanner and was generating 2 PDF files, one with odd pages and the other with even pages. - Split – Only accepts a single file and will create one PDF file per page from the input PDF file.
Here is an example of a function that merge all files given an array of PDF file paths and an output file path.
internal static void ConcatenatePDF(string[] inputFiles, string outFilename)
{
int count = 0;
// Open the output document
using (PdfDocument outputDocument = new PdfDocument())
{
// Iterate files
foreach (string inputFile in inputFiles)
{
using (PdfDocument inputDocument = PdfReader.Open(inputFile, PdfDocumentOpenMode.Import))
{
count = inputDocument.PageCount;
for (int idx = 0; idx < count; idx++)
{
PdfPage page = inputDocument.Pages[idx];
outputDocument.AddPage(page);
}
}
}
outputDocument.Save(outFilename);
}
}
And here is the function that will split a PDF file into individual files, one file per page:
internal static bool SplitPDF(string[] inputFiles)
{
foreach(string inputFile in inputFiles)
{
// Open the file
PdfDocument inputDocument = PdfReader.Open(inputFile, PdfDocumentOpenMode.Import);
string filename = Path.GetFileNameWithoutExtension(inputFile);
Console.WriteLine(filename);
for (int idx = 0; idx < inputDocument.PageCount; idx++)
{
Console.WriteLine(idx);
using (PdfDocument outputDocument = new PdfDocument())
{
// Add the page and save it
outputDocument.AddPage(inputDocument.Pages[idx]);
outputDocument.Save(String.Format("{0} - Page {1}.pdf", filename, idx + 1));
}
}
}
return true;
}
The library used in PDF Merger is PDFsharp, for more information please visit:
Overview of PDFsharp
The source code can be found here:
uclobby/PDFMerger (github.com)