Click here to Skip to main content
6,594,088 members and growing! (14,813 online)
Email Password   helpLost your password?
Desktop Development » Files and Folders » Utilities     Intermediate License: The GNU General Public License (GPL)

Simple .NET PDF Merger

By Michael Ulmann

A simple .NET PDF merger that supports header and footer text.
C# (C# 1.0, C# 2.0, C# 3.0), Windows, .NET, Win32, Dev
Posted:31 Jul 2008
Views:15,676
Bookmarked:34 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
11 votes for this article.
Popularity: 4.32 Rating: 4.15 out of 5
1 vote, 9.1%
1

2

3
1 vote, 9.1%
4
9 votes, 81.8%
5

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
    {
        /// <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();
            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();
        }
    }



    /// <summary>
    /// Implements custom page events.
    /// </summary>
    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 (GPL)

About the Author

Michael Ulmann


Member
MCAD, MCPD Web Developer
Visit my Space: http://ukmichael.spaces.live.com
www.smart-soft.ch
Occupation: Software Developer (Senior)
Company: Smart-Soft
Location: Australia Australia

Other popular Files and Folders articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 10 of 10 (Total in Forum: 10) (Refresh)FirstPrevNext
GeneralHow to bookmark by each PDF creation time Pinmemberorlandito2023:08 30 Apr '09  
GeneralHow to bookmark by each PDF file name PinmemberSaam_cse23:49 27 Nov '08  
AnswerRe: How to bookmark by each PDF file name PinmemberMichael Ulmann12:25 1 Dec '08  
GeneralRe: How to bookmark by each PDF file name PinmemberSaam_cse0:23 2 Dec '08  
GeneralRe: How to bookmark by each PDF file name Pinmemberfriendmastor16:24 25 Aug '09  
QuestionMerge Large Amount of files Pinmemberastaykov2:02 7 Aug '08  
AnswerRe: Merge Large Amount of files PinmemberMichael Ulmann13:52 7 Aug '08  
GeneralHow to pass arguments PinmemberVäinölä Harri4:10 1 Aug '08  
GeneralRe: How to pass arguments PinmemberMichael Ulmann15:38 1 Aug '08  
GeneralRe: How to pass arguments PinmemberVäinölä Harri21:02 3 Aug '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 31 Jul 2008
Editor: Smitha Vijayan
Copyright 2008 by Michael Ulmann
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project