Merging Bookmarks Of Two Or More PDF Files By ITextSharp

Introduction

Recently, I was working on a project. In the project, I would like to merge bookmarks of two or more PDF Files by iTextSharp. So I tried looking at tutorials around the web. But I can't find a good solution to this. This article will explain how to merge bookmarks of two or more PDF Files by iTextSharp. To do that, here we use the ITextSharp library to create PDF documents. It provides all of the primitive functions necessary to create a PDF document.

This article is for merging bookmarks of two or more PDF files where each file contains bookmarks.

For example, PDF file A contains some bookmarks, and file B contains other bookmarks.

I will merge two PDF files using iTextSharp. After merging the two files, A & B, the new File C will be created where all bookmarks will be in File C.

File A bookmark.

File A bookmark

File B bookmark.

File B bookmark

After merging File A and File B, File C contains the bookmark.

bookmark

With this code section, you can get a PDF file's bookmarks.

Example

iTextSharp.text.Document document = new iTextSharp.text.Document();
MemoryStream output = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, output);
writer.PageEvent = new FilePageEvent();
// Open document to write
document.Open();
PdfContentByte content = writer.DirectContent;
int counter = 0;
int fileCount = 0;
int pageno = 0;
foreach (FileInformation file in sourceFiles)
{
    filesByte.Add(File.ReadAllBytes(file.FilePath));
}
PdfOutline objRootOutLine;
List<PDFFIleManager> FileBookmarkInfo;
objRootOutLine = content.RootOutline;
PdfOutline objfolderoutline = content.RootOutline;
string folderName = string.Empty;
for (int fileCounter = 0; fileCounter < filesByte.Count; fileCounter++)
{
    // Create pdf reader
    PdfReader reader = new PdfReader(filesByte[fileCounter]);
    int numberOfPages = reader.NumberOfPages;
    IList<Dictionary<string, object>> book_mark = SimpleBookmark.GetBookmark(reader);
    // By this code section, you can merge PDF file bookmarks
    // Start merging bookmark of PDF generation
    if (!object.Equals(book_mark, null))
    {
        int index = 0;
        int j = 0;
        foreach (Dictionary<string, object> bk in book_mark)
        {
            int i = 0;
            IList<Dictionary<string, object>> kids = null;
            IList<Dictionary<string, object>> list = null;
            string Title = string.Empty;
            int page = 0;
            foreach (string key in bk.Keys)
            {
                if (key.Equals("Title"))
                {
                    Title = Convert.ToString(bk[key]);
                    i = i + 1;
                    CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                    TextInfo textInfo = cultureInfo.TextInfo;
                    Title = textInfo.ToTitleCase(Title);
                }
                if (key.Equals("Kids"))
                {
                    kids = (IList<Dictionary<string, object>>)bk[key];
                }
                if (key.Equals("Page"))
                {
                    string[] words = Convert.ToString(bk[key]).Split(' ');

                    if (!object.Equals(words, null))
                    {
                        page = Convert.ToInt32(words[0]);
                    }
                }
            }
            if (!string.IsNullOrEmpty(Title))
            {
                PdfAction obja3lvl = PdfAction.GotoLocalPage(counter + page - 1, new iTextSharp.text.pdf.PdfDestination(iText

The MergePDF Method accepts a collection of PDF files that have Bookmarks where you can merge 3 levels of bookmarks.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common.Interface {
  /// <summary>  
  /// Interface for manage the file information  
  /// </summary>  
  public interface IFileInformation {
    #region Properties
    /// <summary>  
    /// Gets and set the fileid  
    /// </summary>  
    string FileID {
      get;
      set;
    }
    /// <summary>  
    /// Gets and sets the pdf file name  
    /// </summary>  
    string FileName {
      get;
      set;
    }
    /// <summary>  
    /// Gets and sets the pdf file path  
    /// </summary>  
    string FilePath {
      get;
      set;
    }
    /// <summary>  
    /// Gets and set the folder name  
    /// </summary>  
    string FolderName {
      get;
      set;
    }
    /// <summary>  
    /// Gets and set the is deleted  
    /// </summary>  
    bool IsDeleted {
      get;
      set;
    }
    /// <summary>  
    /// Gets and set the is bookmarkName  
    /// </summary>  
    string FileBookMark {
      get;
      set;
    }
    #endregion
  }
}

/// <summary>  
/// Method for merge pdf files  
/// </summary>  
/// <param name="listFileInformation">List of pdf files</param>  
/// <returns></returns>  
public byte[] MergePDF(List < IFileInformation > sourceFiles) {
    if (sourceFiles.Count == 0) {
      throw new ArgumentNullException("File list");
    }
    iTextSharp.text.Document document = new iTextSharp.text.Document();
    MemoryStream output = new MemoryStream();
    List < byte[] > filesByte = new List < byte[] > ();
    bool checkCoverBookmark = true;
    try {
      // Initialize pdf writer  
      PdfWriter writer = PdfWriter.GetInstance(document, output);
      writer.PageEvent = new FilePageEvent();
      // Open document to write  
      document.Open();
      PdfContentByte content = writer.DirectContent;
      int counter = 0;
      int fileCount = 0;
      int pageno = 0;

      foreach(FileInformation file in sourceFiles) {
        filesByte.Add(File.ReadAllBytes(file.FilePath));
      }
      PdfOutline objRootOutLine;
      List < PDFFIleManager > FileBookmarkInfo;
      objRootOutLine = content.RootOutline;
      PdfOutline objfolderoutline = content.RootOutline;
      string folderName = string.Empty;
      for (int fileCounter = 0; fileCounter < filesByte.Count; fileCounter++) {
        // Create pdf reader  
        PdfReader reader = new PdfReader(filesByte[fileCounter]);
        int numberOfPages = reader.NumberOfPages;
        IList < Dictionary < string, object >> book_mark = SimpleBookmark.GetBookmark(reader);

        if (!object.Equals(book_mark, null)) {
          IList < Dictionary < string, object >> list = IterateBookmark(book_mark);
        }
        #region bookmarking of member and decision vote
        // Iterate through all pages  
        for (int currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++) {
          counter = counter + 1;
          pageno = pageno + 1;
          // Determine page size for the current page  
          document.SetPageSize(reader.GetPageSizeWithRotation(currentPageIndex));
          // Create page  
          document.NewPage();
          if (currentPageIndex == 1) {
            fileCount = fileCount + 1;
            string fileName = (from l in sourceFiles where l.FileID == fileCount.ToString() select l.FileName).FirstOrDefault();
            string folderName1 = (from l in sourceFiles where l.FileID == fileCount.ToString() select l.FolderName).FirstOrDefault();
            string bookmarkIndividualName = (from l in sourceFiles where l.FileID == fileCount.ToString() select l.FileBookMark).FirstOrDefault();
            if (folderName != folderName1) {
              PdfAction objFolderAction = PdfAction.GotoLocalPage(counter, new iTextSharp.text.pdf.PdfDestination(iTextSharp.text.pdf.PdfDestination.FITH), writer);
              objfolderoutline = new PdfOutline(objRootOutLine, objFolderAction, folderName1.ToUpper(), true);
              folderName = folderName1;
            }

            PdfAction objaction = PdfAction.GotoLocalPage(counter, new iTextSharp.text.pdf.PdfDestination(iTextSharp.text.pdf.PdfDestination.FITH), writer);

            if (string.IsNullOrEmpty(bookmarkIndividualName))
              bookmarkIndividualName = fileName;
            PdfOutline objoutline = new PdfOutline(objfolderoutline, objaction, bookmarkIndividualName.ToUpper(), true);
            //******************Start merging bookmark of pdf generation   
            if (!object.Equals(book_mark, null)) {
              int index = 0;
              int j = 0;
              foreach(Dictionary < string, object > bk in book_mark) {
                int i = 0;
                IList < Dictionary < string, object >> kids = null;
                IList < Dictionary < string, object >> list = null;
                string Title = string.Empty;
                int page = 0;
                foreach(string key in bk.Keys) {
                  if (key.Equals("Title")) {
                    Title = Convert.ToString(bk[key]);
                    i = i + 1;
                    CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                    TextInfo textInfo = cultureInfo.TextInfo;
                    Title = textInfo.ToTitleCase(Title);
                    // counter = i;  
                  }

                  if (key.Equals("Kids")) {
                    kids = (IList < Dictionary < string, object >> ) bk[key];
                  }
                  if (key.Equals("Page")) {
                    //page = Convert.ToString(bk[key]).Split('');  

                    string[] words = Convert.ToString(bk[key]).Split(' ');
                    if (!object.Equals(words, null)) {
                      page = Convert.ToInt32(words[0]);
                    }
                  }
                }
                if (!string.IsNullOrEmpty(Title)) {
                  // counter = counter + 1;   
                  PdfAction obja3lvl = PdfAction.GotoLocalPage(counter + page - 1, new iTextSharp.text.pdf.PdfDestination(iTextSharp.text.pdf.PdfDestination.FITH), writer);
                  PdfOutline objoutline3lvl = new PdfOutline(objoutline, obja3lvl, Title.ToString(), true);
                  if (!object.Equals(kids, null)) {
                    // int j = i;  
                    foreach(Dictionary < string, object > innerkids in kids) {
                      IList < Dictionary < string, object >> kids2nd = null;
                      string Title2nd = string.Empty;
                      int page2 = 0;
                      foreach(string key in innerkids.Keys) {
                        if (key.Equals("Title")) {
                          Title2nd = Convert.ToString(innerkids[key]);
                          i = i + 1;
                          CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                          TextInfo textInfo = cultureInfo.TextInfo;
                          Title2nd = textInfo.ToTitleCase(Title2nd);
                        }
                        if (key.Equals("Kids")) {
                          kids2nd = (IList < Dictionary < string, object >> ) innerkids[key];
                        }
                        if (key.Equals("Page")) {
                          string[] words = Convert.ToString(innerkids[key]).Split(' ');
                          if (!object.Equals(words, null)) {
                            page2 = Convert.ToInt32(words[0]);
                          }
                        }
                      }

                      if (!string.IsNullOrEmpty(Title2nd)) {
                        PdfAction obja4lvl = PdfAction.GotoLocalPage(counter + page2 - 1, new iTextSharp.text.pdf.PdfDestination(iTextSharp.text.pdf.PdfDestination.FITH), writer);
                        PdfOutline objoutline4lvl = new PdfOutline(objoutline3lvl, obja4lvl, Title2nd.ToString(), true);
                        if (!object.Equals(kids2nd, null)) {
                          // int k = j;  
                          foreach(Dictionary < string, object > innerkids3rd in kids2nd) {

                            IList < Dictionary < string, object >> kids3rd = null;
                            string Title3rd = string.Empty;
                            int page3 = 0;
                            foreach(string key in innerkids3rd.Keys) {
                              if (key.Equals("Title")) {
                                Title3rd = Convert.ToString(innerkids3rd[key]);
                                i = i + 1;
                                CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                                TextInfo textInfo = cultureInfo.TextInfo;
                                Title3rd = textInfo.ToTitleCase(Title3rd);
                              }

                              if (key.Equals("Kids")) {
                                kids3rd = (IList < Dictionary < string, object >> ) innerkids3rd[key];
                              }
                              if (key.Equals("Page")) {
                                //  page3 = Convert.ToInt32(innerkids3rd[key]);  

                                string[] words = Convert.ToString(innerkids3rd[key]).Split(' ');
                                if (!object.Equals(words, null)) {
                                  page3 = Convert.ToInt32(words[0]);
                                }
                              }
                            }

                            if (!string.IsNullOrEmpty(Title2nd)) {
                              PdfAction obja5lvl = PdfAction.GotoLocalPage(counter + page3 - 1, new iTextSharp.text.pdf.PdfDestination(iTextSharp.text.pdf.PdfDestination.FITH), writer);
                              PdfOutline objoutline5lvl = new PdfOutline(objoutline4lvl, obja5lvl, Title3rd.ToString(), true);
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }

              //*************End bookmark of pdf generation  
            }

            PdfImportedPage importedPage = writer.GetImportedPage(reader, currentPageIndex);
            // Determine page orientation  
            int pageOrientation = reader.GetPageRotation(currentPageIndex);
            if ((pageOrientation == 90) || (pageOrientation == 270)) {
              content.AddTemplate(importedPage, 0, -1 f, 1 f, 0, 0, reader.GetPageSizeWithRotation(currentPageIndex).Height);
            } else {
              content.AddTemplate(importedPage, 1 f, 0, 0, 1 f, 0, 0);
            }
          }
          #endregion
          //}   
        }
      } catch (IOException ex) {
        throw new IOException(ex.Message);
      } catch (OutOfMemoryException ex) {
        throw new OutOfMemoryException(ex.Message);
      } catch (Exception ex) {
        throw new Exception(ex.Message);
      } finally {
        document.Close();
      }
      return output.GetBuffer();
    }


Similar Articles