Article

Merge Pdfs Using iTextSharp, C#

We had to automate the process of merging a couple of PDFs and inserting an image on a particular page. Since this involved programming, we decided to use the iTextSharp Library. You can find the DLL here.  iTextSharp is a tool that is used to create and manipulate PDFs.  It is quite easy to create PDFs using this simple library, rather than working with Adobe since Adobe’s API is expensive compared to iTextSharp, which is free! There are other Libraries including PdfSharp, etc., but we decided to go with iTextSharp.

Now to dive into the problem – We were planning to merge a PDF with an image into a new PDF with the option of adding more PDFs using the iTextSharp library.

With a little trial and error and a LOT of googling, we finally arrived at a solution that is given below:

Namespaces:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ItextSharp.Properties;
using iTextSharp.text;
using System.Collections;
using iTextSharp.text.pdf;
using System.IO;

Code: We wrote a modular code so that it can be reused and easily read.

namespace ItextSharp
{
    public partial class Form1 : Form
    {
         // Function call with parameters    
        public void GenerateBookPdf(string SourceFolder, string FileName, 
        string PdfPath, string ImagePath, int PageNumber)
        {
            PdfImageMerge merge = new PdfImageMerge();
            //set the properties of the class
            merge.Source_Folder = SourceFolder;
            merge.Result_File = Path.Combine(SourceFolder, FileName + ".pdf");
            merge.ImagePath=ImagePath;
            //Specify the page number
            merge.PageNumber = PageNumber;
              //You can merge any number of pdf’s together
             // Add a new file, together with a given docname to the fileList and
            // namelist collection , Multiple pdf’s can be merged together
            merge.files.Add(PdfPath);
            merge.StartMerge();
        }
        public class PdfImageMerge
        {
            ///
            /// Add the image to the Pdf Page
            /// 
            private Document AddImageToPdfPage(Document doc, string ImgPath)
            {
                iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(ImgPath);
                logo.Alignment = Element.ALIGN_MIDDLE;
                doc.Add(logo);
                return doc;
            }
            public void StartMerge()
            {
                Document document = new Document();
                try
                {
                    PdfWriter writePdf = PdfWriter.GetInstance(document,
                    new FileStream(result_file, FileMode.Create));
                    document.Open();
                    PdfContentByte cb = writePdf.DirectContent;
                    PdfImportedPage page;
                    int n = 0;
                    int pdf_rotation = 0;
                    foreach (string filename in files)
                    {
                        //The current file path
                        string filePath = source_folder + filename;
                        PdfReader readPdf = new PdfReader(filePath);
                        n = readPdf.NumberOfPages;
                        for (int i=1;i < n+1;i++)
                        {
                            document.SetPageSize(readPdf.GetPageSizeWithRotation(1));
                            document.NewPage();
                            if (i == 1)
                            {
                                Chunk fileChunk = new Chunk(" ");
                                fileChunk.SetLocalDestination(filename);
                                document.Add(fileRef);
                            }
                            //Specify the pagenumber and path number
                            if (PageNumber != null)
                            {
                                if (i == PageNumber)
                                {
                                    document = AddImageToPdfPage(document, ImagePath);
                                    continue;
                                }
                            }
                            page = writePdf.GetImportedPage(readPdf, i);
                            pdf_rotation = readPdf.GetPageRotation(i);
                            if (pdf_rotation == 90 || pdf_rotation == 270)
                            {
                                cb.AddTemplate(page, 0, -1f, 1f, 0, 0,
                                readPdf.GetPageSizeWithRotation(i).Height);
                            }
                            else
                            {
                                cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                            }
                        }
                    }
                }
                catch (Exception e) { throw e; }
                finally { document.Close(); }
            }
            public int pageNumber;
            public string source_folder;
            public string result_file;
            public string imagePath;
            public IList files = new ArrayList();
            ///
            /// Gets or Sets the SourceFolder
            ///
            public string Source_Folder
            {
                get { return source_folder; }
                set { source_folder = value; }
            }
            ///
            /// Gets or Sets the DestinationFile
            ///
            public string Result_File
            {
                get { return result_file; }
                set { result_file = value; }
            }
            // Gets or Sets the Image Path
            public string ImagePath
            {
                get { return imagePath; }
                set { imagePath = value; }
            }
            // Gets or Sets the Page number to insert image
            public int PageNumber
            {
                get { return pageNumber; }
                set { pageNumber = value; }
            }
        }
       }
    }

This seems to solve the problem. In the Windows application, we can also specify the file source and destination dynamically. This code can be used as a base to do a lot of other modifications on the go. Try the library and use this code to merge your PDFs.

We’re listening.

Do you have something to say about this article? Contact us to know more or share it with us on FacebookTwitter, or  LinkedIn.

Facebook
Twitter
LinkedIn
Categories

Select a Child Category
category
669d0368a5927
1
0
226,352,350
Loading....
Recent Posts
Social Links

Related Posts

Want to Learn More?

Milestone experts take the time to listen, understand your needs, and provide the right mix of tools, technology, and resources to help you meet your goals.

Request a complimentary consultation to get started.

Request a Complimentary Consultation

Skip to content