Click here to Skip to main content
15,879,326 members
Articles / Desktop Programming / Win32

Simple .NET PDF Merger

Rate me:
Please Sign up or sign in to vote.
4.75/5 (41 votes)
17 Nov 2014GPL31 min read 255.6K   11.2K   99   60
A simple .NET PDF merger that supports header and footer text.

Introduction

There are a couple of PDF mergers available on the Internet. But, either they are commercial products or don't support printing of the header and/or footer text, which is particularly interesting, e.g., to print the page number.

Background

The presented PDF merger uses the open source PDF library iTextSharp to process PDF files. The sample solution also includes a tiny Windows Forms application to demonstrate the functionality.

Using the code

For the merge process, the PDF library takes advantage of the PDF page events of the iTextSharp.text.pdf.PdfWriter object. During the initialization of the PdfPageEvent instance (which inherits from iTextSharp.text.pdf.IPdfPageEvent), necessary information for the header/footer text could be passed in to the constructor call:

C#
<s>writer.PageEvent = new PdfPageEvents(/*Any type of information goes here*/);</s>

It is important that the header and the footer text, both, are rendered in the 'public void OnEndPage(PdfWriter writer, Document document)' method. The 'public void OnStartPage(PdfWriter writer, Document document)' is not accurate.

For performance reasons, this library is now leveraging the PdfCopy class from the iTextSharp library instead of the described method above.

Even though the shown sample is very basic, it generally gives a good overview of how the header and the footer can be populated, e.g., with picture(s), text(s)...

The source code

using System;
using System.Collections.Generic;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace HelveticSolutions.PdfLibrary
{
    public static class PdfMerger
    {
        /// <summary>
        /// Merge pdf files.
        /// </summary>
        /// <param name="sourceFiles">PDF files being merged.</param>
        /// <returns></returns>
        public static byte[] MergeFiles(List<byte[]> sourceFiles)
        {
            Document document = new Document();
            using (MemoryStream ms = new MemoryStream())
            {
                PdfCopy copy = new PdfCopy(document, ms);
                document.Open();
                int documentPageCounter = 0;

                // Iterate through all pdf documents
                for (int fileCounter = 0; fileCounter < sourceFiles.Count; fileCounter++)
                {
                    // Create pdf reader
                    PdfReader reader = new PdfReader(sourceFiles[fileCounter]);
                    int numberOfPages = reader.NumberOfPages;

                    // Iterate through all pages
                    for (int currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                    {
                        documentPageCounter++;
                        PdfImportedPage importedPage = copy.GetImportedPage(reader, currentPageIndex);
                        PdfCopy.PageStamp pageStamp = copy.CreatePageStamp(importedPage);

                        // Write header
                        ColumnText.ShowTextAligned(pageStamp.GetOverContent(), Element.ALIGN_CENTER,
                            new Phrase("PDF Merger by Helvetic Solutions"), importedPage.Width / 2, importedPage.Height - 30,
                            importedPage.Width < importedPage.Height ? 0 : 1);

                        // Write footer
                        ColumnText.ShowTextAligned(pageStamp.GetOverContent(), Element.ALIGN_CENTER,
                            new Phrase(String.Format("Page {0}", documentPageCounter)), importedPage.Width / 2, 30,
                            importedPage.Width < importedPage.Height ? 0 : 1);

                        pageStamp.AlterContents();

                        copy.AddPage(importedPage);
                    }

                    copy.FreeReader(reader);
                    reader.Close();
                }

                document.Close();
                return ms.GetBuffer();
            }
        }
    }
}

History

  • 01.08.2008 - Article created.
  • 17.11.2014 - Updated implementation based on other user's feedback.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
Architect Swissworx
Australia Australia
MCAD, MCPD Web Developer 2.0, MCPD Enterprise Developer 3.5

My company: Swissworx
My blog: Sitecore Experts

Hopp Schwiiz Smile | :)

Comments and Discussions

 
GeneralSet margins to zero Pin
Karri Kalpio1-Apr-16 3:29
Karri Kalpio1-Apr-16 3:29 
GeneralMessage Closed Pin
11-Apr-16 4:09
Member 1245171711-Apr-16 4:09 
QuestionCorrupt PDFs Pin
Member 1153641912-May-15 9:37
Member 1153641912-May-15 9:37 
GeneralMessage Closed Pin
11-Apr-16 4:09
Member 1245171711-Apr-16 4:09 
QuestionFile size seems large Pin
Joel WZ20-Apr-15 9:45
professionalJoel WZ20-Apr-15 9:45 
AnswerRe: File size seems large Pin
Member 1229730330-Jan-16 7:54
Member 1229730330-Jan-16 7:54 
QuestionThank you for your work Pin
araczynski230-Jan-15 11:33
araczynski230-Jan-15 11:33 
QuestionCannot download your sample project Pin
fredatcodeproject17-Nov-14 1:50
professionalfredatcodeproject17-Nov-14 1:50 
AnswerRe: Cannot download your sample project Pin
Michael Ulmann17-Nov-14 11:34
Michael Ulmann17-Nov-14 11:34 
GeneralRe: Cannot download your sample project Pin
fredatcodeproject17-Nov-14 21:49
professionalfredatcodeproject17-Nov-14 21:49 
SuggestionWorks....usually Pin
FlindianaJones7-Nov-14 10:57
FlindianaJones7-Nov-14 10:57 
GeneralRe: Works....usually Pin
Michael Ulmann13-Nov-14 19:07
Michael Ulmann13-Nov-14 19:07 
GeneralRe: Works....usually Pin
Michael Ulmann16-Nov-14 13:32
Michael Ulmann16-Nov-14 13:32 
QuestionMerge Pin
Member 1019053616-Oct-14 5:36
Member 1019053616-Oct-14 5:36 
AnswerRe: Merge Pin
Michael Ulmann16-Nov-14 13:30
Michael Ulmann16-Nov-14 13:30 
QuestionThank you Pin
Tammam Koujan1-Oct-14 4:34
professionalTammam Koujan1-Oct-14 4:34 
AnswerRe: Thank you Pin
Michael Ulmann3-Nov-14 12:50
Michael Ulmann3-Nov-14 12:50 
GeneralMy vote of 3 Pin
Sunil Kumar P20-Sep-14 23:49
Sunil Kumar P20-Sep-14 23:49 
GeneralRe: My vote of 3 Pin
Michael Ulmann13-Nov-14 19:08
Michael Ulmann13-Nov-14 19:08 
GeneralMy vote of 5 Pin
Tyler Forsythe30-Jul-14 11:23
Tyler Forsythe30-Jul-14 11:23 
GeneralRe: My vote of 5 Pin
Michael Ulmann13-Nov-14 19:08
Michael Ulmann13-Nov-14 19:08 
Thanks mate, appreciate it!
Bugunable to open merged pdf Pin
DevXYZ18-Jul-14 1:01
DevXYZ18-Jul-14 1:01 
GeneralRe: unable to open merged pdf Pin
Michael Ulmann16-Nov-14 13:33
Michael Ulmann16-Nov-14 13:33 
QuestionMerged document always asks to be saved Pin
Ray Mitchell8-Jun-14 19:00
Ray Mitchell8-Jun-14 19:00 
AnswerRe: Merged document always asks to be saved Pin
Mehdi Khaleghian27-Jul-14 20:05
Mehdi Khaleghian27-Jul-14 20:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.