Click here to Skip to main content
Click here to Skip to main content
Go to top

Simple .NET PDF Merger

, 31 Jul 2008
Rate this:
Please Sign up or sign in to vote.
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:

writer.PageEvent = new PdfPageEvents(/*Any type of information goes here*/);

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.

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 SmartSoft.PdfLibrary
{
    public static class PdfMerger
    {
        /// <span class="code-SummaryComment"><summary></span>
        /// Merge pdf files.
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="sourceFiles">PDF files being merged.</param></span>
        /// <span class="code-SummaryComment"><returns></returns></span>
        public static byte[] MergeFiles(List<byte[]> sourceFiles)
        {
            Document document = new Document();
            MemoryStream output = new MemoryStream();

            try
            {
                // Initialize pdf writer
                PdfWriter writer = PdfWriter.GetInstance(document, output);
                writer.PageEvent = new PdfPageEvents();
                
                // Open document to write
                document.Open();
                PdfContentByte content = writer.DirectContent;

                // 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++)
                    {
                        // Determine page size for the current page
                        document.SetPageSize(
                           reader.GetPageSizeWithRotation(currentPageIndex));
                        
                        // Create page
                        document.NewPage();
                        PdfImportedPage importedPage = 
                          writer.GetImportedPage(reader, currentPageIndex);

                        
                        // Determine page orientation
                        int pageOrientation = reader.GetPageRotation(currentPageIndex);
                        if ((pageOrientation == 90) || (pageOrientation == 270))
                        {
                            content.AddTemplate(importedPage, 0, -1f, 1f, 0, 0,
                               reader.GetPageSizeWithRotation(currentPageIndex).Height);
                        }
                        else
                        {
                            content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                throw new Exception("There has an unexpected exception" + 
                      " occured during the pdf merging process.", exception);
            }
            finally
            {
                document.Close();
            }
            return output.GetBuffer();
        }
    }



    /// <span class="code-SummaryComment"><summary></span>
    /// Implements custom page events.
    /// <span class="code-SummaryComment"></summary></span>
    internal class PdfPageEvents : IPdfPageEvent
    {
        #region members
        private BaseFont _baseFont = null;
        private PdfContentByte _content;
        #endregion

        #region IPdfPageEvent Members
        public void OnOpenDocument(PdfWriter writer, Document document)
        {
            _baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, 
                             BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            _content = writer.DirectContent;
        }

        public void OnStartPage(PdfWriter writer, Document document)
        {}

        public void OnEndPage(PdfWriter writer, Document document)
        {
            // Write header text
            string headerText = "PDF Merger by Smart-Soft";
            _content.BeginText();
            _content.SetFontAndSize(_baseFont, 8);
            _content.SetTextMatrix(GetCenterTextPosition(headerText, 
                                   writer), writer.PageSize.Height - 10);
            _content.ShowText(headerText);
            _content.EndText();

            // Write footer text (page numbers)
            string text = "Page " + writer.PageNumber;
            _content.BeginText();
            _content.SetFontAndSize(_baseFont, 8);
            _content.SetTextMatrix(GetCenterTextPosition(text, writer), 10);
            _content.ShowText(text);
            _content.EndText();
        }

        public void OnCloseDocument(PdfWriter writer, Document document)
        {}

        public void OnParagraph(PdfWriter writer, 
                    Document document, float paragraphPosition)
        {}

        public void OnParagraphEnd(PdfWriter writer, 
                    Document document, float paragraphPosition)
        {}

        public void OnChapter(PdfWriter writer, Document document, 
                              float paragraphPosition, Paragraph title)
        {}

        public void OnChapterEnd(PdfWriter writer, 
                    Document document, float paragraphPosition)
        {}

        public void OnSection(PdfWriter writer, Document document, 
                    float paragraphPosition, int depth, Paragraph title)
        {}

        public void OnSectionEnd(PdfWriter writer, 
                    Document document, float paragraphPosition)
        {}

        public void OnGenericTag(PdfWriter writer, Document document, 
                                 Rectangle rect, string text)
        {}
        #endregion

        private float GetCenterTextPosition(string text, PdfWriter writer)
        {
            return writer.PageSize.Width / 2 - _baseFont.GetWidthPoint(text, 8) / 2;
        }
    }
}

History

  • 01.08.2008 - Article created.

License

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

Share

About the Author

Michael Ulmann
Architect Helvetic Solutions
Australia Australia
MCAD, MCPD Web Developer 2.0, MCPD Enterprise Developer 3.5
My company: www.helveticsolutions.com
Hopp Schwiiz Smile | :)

Comments and Discussions

 
GeneralMy vote of 5 PinmemberTyler Forsythe30-Jul-14 11:23 
Bugunable to open merged pdf PinmemberDevXYZ18-Jul-14 1:01 
QuestionMerged document always asks to be saved PinmemberRay Mitchell8-Jun-14 19:00 
AnswerRe: Merged document always asks to be saved PinmemberMember 365110127-Jul-14 20:05 
GeneralThanx PinmemberPRABHUSUN7-May-14 1:34 
QuestionBlank pages - SQL report PDF PinmemberGarethfr3-Oct-13 5:54 
AnswerRe: Blank pages - SQL report PDF [modified] PinmemberMember 1077258924-Apr-14 6:27 
QuestionHelp for merging fillable PDF with regular PDF Pinmemberdfaber512-Jul-13 14:00 
QuestionCrop/Rotate PinmemberCorbin de Bruin25-Apr-13 6:45 
I'm using your code to combine pdf that I've previously cropeed and rotated individually (usually rotated 180 degrees). The merge process doesn't seem to handle this. My output pdf is coming in with original size and rotation. Could you suggest how to fix this?
Questionneed help for security PinmemberHanieef12-Mar-13 15:17 
GeneralUpvoted - PinmemberJohn Atten26-Jan-13 3:07 
GeneralMy vote of 5 Pinmemberjafarkofahi5-Sep-12 5:52 
QuestionGreat! PinmemberAleBrozzo20-Mar-12 18:51 
QuestionTHANK YOU! PinmemberMember 340683825-Jan-12 5:04 
AnswerRe: THANK YOU! PinmemberMichael Ulmann18-Mar-12 13:06 
GeneralRe: THANK YOU! PinmemberMember 987752922-Sep-13 22:47 
GeneralMy vote of 5 Pinmemberjuniorsebr22-Jul-10 2:37 
GeneralPdfContentByte has a method called ShowTextAligned PinmemberRubyPdf25-May-10 13:28 
GeneralInformative article Pinmembersuraj mehare2-Mar-10 7:06 
GeneralRe: Informative article PinmemberMichael Ulmann2-Mar-10 19:02 
QuestionHow to bookmark by each PDF creation time Pinmemberorlandito2030-Apr-09 22:08 
QuestionHow to bookmark by each PDF file name PinmemberSaam_cse27-Nov-08 22:49 
AnswerRe: How to bookmark by each PDF file name PinmemberMichael Ulmann1-Dec-08 11:25 
GeneralRe: How to bookmark by each PDF file name PinmemberSaam_cse1-Dec-08 23:23 
GeneralRe: How to bookmark by each PDF file name Pinmemberfriendmastor25-Aug-09 15:24 
QuestionMerge Large Amount of files Pinmemberastaykov7-Aug-08 1:02 
AnswerRe: Merge Large Amount of files PinmemberMichael Ulmann7-Aug-08 12:52 
QuestionHow to pass arguments PinmemberVäinölä Harri1-Aug-08 3:10 
AnswerRe: How to pass arguments PinmemberMichael Ulmann1-Aug-08 14:38 
GeneralRe: How to pass arguments PinmemberVäinölä Harri3-Aug-08 20:02 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 31 Jul 2008
Article Copyright 2008 by Michael Ulmann
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid