ShiftPageNumbers with iTextSharp

I’m having some trouble using iTextSharp to merge some PDFs while preserving the bookmarks. I’ve written the following hackish code to test an idea, but the ShiftPageNumbers method doesn’t seem to even be working for me. Does anyone have any idea why?

string[] files = Directory.GetFiles(folder);
string path = Path.GetDirectoryName(files[0]);
IList<Dictionary<string, object>> oldBookmarks
    = SimpleBookmark.GetBookmark(new PdfReader(files[0]));
List<Dictionary<string, object>> newBookmarks = new List<Dictionary<string, object>>();

FileStream outFile = new FileStream(output, FileMode.Create);
PdfConcatenate newPdf = new PdfConcatenate(outFile);

switch (oldBookmarks.Count())
{
    case 0:
        break;

    case 1:
        oldBookmarks = (IList<Dictionary<string, object>>)(oldBookmarks[0])["Kids"];
        break;

    default:
        break;
}

files = oldBookmarks.Select(b => b["File"]).Cast<string>().ToArray();

foreach (string filename in files)
{
    Console.Write:ine(filename);
    PdfReader reader = new PdfReader(Path.Combine(path, filename));
    newPdf.AddPages(reader);

    List<Dictionary<string, object>> tempBookmarks =
        oldBookmarks.Where(b => (string)b["File"] == filename).ToList();

    // handles bookmarks
    SimpleBookmark.ShiftPageNumbers(tempBookmarks, length, null);
    newBookmarks.AddRange(tempBookmarks);
    length += reader.NumberOfPages;

    reader.Close();
}

newPdf.Writer.Outlines = newBookmarks;
newPdf.Close();


Source: bookmarks

Leave a Reply