Add file with bookmark

柔情痞子 提交于 2019-12-24 13:47:22

问题


I want to add a PDF file using iTextSharp but if PDF file contains bookmarks then they should also be added.

Currently I'm using following code

Document document = new Document();
//Step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFileName, FileMode.Create));
writer.ViewerPreferences = PdfWriter.PageModeUseOutlines;
//Step 3: Open the document
document.Open();

PdfContentByte cb = writer.DirectContent;

//The current file path
string filename = "D:\\rtf\\2.pdf";

// we create a reader for the document
PdfReader reader = new PdfReader(filename);

//Chapter ch = new Chapter("", 1);

for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++)
{
    document.SetPageSize(reader.GetPageSizeWithRotation(1));
    document.NewPage();

    // Insert to Destination on the first page
    if (pageNumber == 1)
    {
        Chunk fileRef = new Chunk(" ");
        fileRef.SetLocalDestination(filename);
        document.Add(fileRef);
    }

    PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);
    int rotation = reader.GetPageRotation(pageNumber);
    if (rotation == 90 || rotation == 270)
    {
        cb.Add(page);
    }
    else
    {
        cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
    }
}

document.Close();

回答1:


Please read Chapter 6 of my book. In table 6.1, you'll read:

Can import pages from other PDF documents. The major downside is that all interactive features of the imported page (annotations, bookmarks, fields, and so forth) are lost in the process.

This is exactly what you experience. However, if you look at the other classes listed in that table, you'll discover PdfStamper, PdfCopy, etc... which are classes that do preserve interactive features.

PdfStamper will keep the bookmarks. If you want to use PdfCopy (or PdfSmartCopy), you need to read chapter 7 to find out how to keep them. Chapter 7 isn't available for free, but you can consult the examples here: Java / C#. You need the ConcatenateBookmarks example.

Note that you're code currently looks convoluted because you're not using the correct classes. Using PdfStamper should significantly reduce the number of lines of code.



来源:https://stackoverflow.com/questions/14729237/add-file-with-bookmark

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!