如何在Itext7中合并时如何将书签添加到PDF

时间:2017-02-17 17:05:25

标签: c# itext7

我正在尝试创建一个合并多个pdf的程序,并且每个程序都有一个书签。

我的开始方法是:

    private Byte[] MergePdfForms(Dictionary<string, Stream> files)
    {
        var dest = new MemoryStream();
        PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
        PdfMerger merger = new PdfMerger(pdf);

        foreach (var keyValuePair in files)
        {
               //TODO add bookmark to this page 
            PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(keyValuePair.Value));
            merger.Merge(firstSourcePdf, 1, firstSourcePdf.GetNumberOfPages());
            firstSourcePdf.Close();
        }

        pdf.Close();
        return dest.ToArray();
    }

我尝试过像

这样的事情
  pdf.InitializeOutlines();
  pdf.AddNamedDestination("Test Bookmark", pdf.GetLastPage().GetPdfObject());

哪个不会创建任何书签。

1 个答案:

答案 0 :(得分:3)

看一下这里的示例:http://developers.itextpdf.com/examples/merging-pdf-documents/clone-merging-documents-bookmarks

    private byte[] MergePdfForms(Dictionary<string, Stream> files)
    {
        var dest = new MemoryStream();
        PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
        PdfMerger merger = new PdfMerger(pdf);
        PdfOutline rootOutline = pdf.GetOutlines(false);
        PdfOutline helloWorld = rootOutline.AddOutline("Root");

        int pages = 1;
        foreach (var keyValuePair in files)
        {
            var firstSourcePdf = new PdfDocument(new PdfReader(keyValuePair.Value));
            var subPages = firstSourcePdf.GetNumberOfPages();
            merger.Merge(firstSourcePdf, 1, subPages);
            firstSourcePdf.Close();

            var link1 = helloWorld.AddOutline(keyValuePair.Key);
            link1.AddDestination(PdfExplicitDestination.CreateFit(pdf.GetPage(pages)));
            pages += subPages;

        }
        pdf.Close();
        return dest.ToArray();
    }