I was working on a email invoicing application a few days ago, and I needed a way to consolidate multiple PDF invoices (approximately ~50-200 invoice p/week). I wanted something that was free and worked with C#, I found PdfSharp and after looking at the demo’s I came up with a quick solution. The process is really simple and can be summarized as (Create a new empty PDF, open each existing PDF and copy their pages into the new PDF). Here is a code snippet of how I combined the PDF files, using a DataReader that has the source URL of each invoice:
// ********************************************************************************************* //
// This is just a simplified excerpt, I was looping over all the invoices from the previous week
// by customer, and aggregating their PDF invoices into a single document. In addition to the
// generating the PDF, I used the DataReader to also generate a CSV file of their invoice details.
// ********************************************************************************************* //
// Combined PDF
var customerPdf = new PdfDocument();
// Hold copy of last document
string lastDocumentUrl = string.Empty;
while (dr.Read())
{
// Get current document
string documentUrl = dr["InvoiceURL"].ToString();
// Check if last document added is the same as current document
if (lastDocumentUrl != documentUrl)
{
// Set the last document equal to the current document
lastDocumentUrl = documentUrl;
// Get the current file (e.g. \\\\\.pdf)
string filePath = documentUrl;
// Read in the existing document
PdfDocument inputDocument = PdfReader.Open(filePath, PdfDocumentOpenMode.Import);
// Get # of pages
var count = inputDocument.PageCount;
// Add each page to "Combined PDF"
for (int idx = 0; idx < count; idx++)
{
PdfPage page = inputDocument.Pages[idx];
customerPdf.AddPage(page);
}
}
}