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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With