-->

Merging PDFs

dev pdf, csharp

I like playing around with PDFs especially when planning my week. I have my daily plans and often need to merge them into a single PDF to print easily. As I decided to migrate to Mac for daily use now I can merge them very easily from command line as I described in my TIL site here.

Mac’s PDF viewer is great as it also allows to simply drag and drop a PDF into another one to merge them. Windows doesn’t have this kind of nicety so I had to develop my own application to achieve this. I was planning to ad more PDF operations but since I’m not using it anymore I don’t think it will happen anytime soon so I decided to open the source.

Very simple application anyway but hope it helps someone save some time.

Implementation

It uses iTextSharp NuGet package to handle the merge operation:

public class PdfMerger
{
    public string MergePdfs(List<string> sourceFileList, string outputFilePath)
    {
        using (var stream = new FileStream(outputFilePath, FileMode.Create))
        {
            using (var pdfDoc = new Document())
            {
                var pdf = new PdfCopy(pdfDoc, stream);
                pdfDoc.Open();
                foreach (string file in sourceFileList)
                {
                    pdf.AddDocument(new PdfReader(file));
                }
            }
        }

        return outputFilePath;
    }
}

Also uses Fluent Command Line Parse, another of my favourite NuGet packages to take care of the input parameters:

var parser = new FluentCommandLineParser<Settings>();
parser.Setup(arg => arg.RootFolder).As('d', "directory");
parser.Setup(arg => arg.FileList).As('f', "files");
parser.Setup(arg => arg.OutputPath).As('o', "output").Required();
parser.Setup(arg => arg.AllInFolder).As('a', "all");
    
var result = parser.Parse(args);
if (result.HasErrors)
{
    DisplayUsage();
    return;
}

var p = new Program();
p.Run(parser.Object);

The full source code can be found in the GitHub repository (link down below).

Resources