Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging pdf files with bookmarks

I'm trying to merge a lot of pdf's and for each pdf I want to add a bookmark(the name of the pdf), I found difrent techniques of merging pdf's but none of them can add only the bookmark fore eg. itextsharp add's a chapter, then the bookmark for the chapter, i don't want to alter the pdf's.

like image 524
XandrUu Avatar asked Apr 17 '12 08:04

XandrUu


1 Answers

Using itextsharp you can do it. I do it by the following method:

MergePdfFiles(string outputPdf, string[] sourcePdfs) {
    PdfReader reader = null;
    Document document = new Document();
    PdfImportedPage page = null;
    PdfCopy pdfCpy = null;
    int n = 0;
    int totalPages = 0;
    int page_offset = 0;
    List < Dictionary < string, object >> bookmarks = new List < Dictionary < string, object >> ();
    IList < Dictionary < string, object >> tempBookmarks;
    for (int i = 0; i <= sourcePdfs.GetUpperBound(0); i++) {
        reader = new PdfReader(sourcePdfs[i]);
        reader.ConsolidateNamedDestinations();
        n = reader.NumberOfPages;
        tempBookmarks = SimpleBookmark.GetBookmark(reader);
        if (i == 0) {
            document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1));
            pdfCpy = new PdfCopy(document, new FileStream(outputPdf, FileMode.Create));
            document.Open();
            SimpleBookmark.ShiftPageNumbers(tempBookmarks, page_offset, null);
            page_offset += n;
            if (tempBookmarks != null)
                bookmarks.AddRange(tempBookmarks);
            //  MessageBox.Show(n.ToString());
            totalPages = n;
        } else {
            SimpleBookmark.ShiftPageNumbers(tempBookmarks, page_offset, null);
            if (tempBookmarks != null)
                bookmarks.AddRange(tempBookmarks);
            page_offset += n;
            totalPages += n;
        }
        for (int j = 1; j <= n; j++) {
            page = pdfCpy.GetImportedPage(reader, j);
            pdfCpy.AddPage(page);
        }
        reader.Close();
    }
    pdfCpy.Outlines = bookmarks;
    document.Close();
}
like image 193
Md Kamruzzaman Sarker Avatar answered Sep 23 '22 12:09

Md Kamruzzaman Sarker