使用书签添加文件 [英] Add file with bookmark

查看:95
本文介绍了使用书签添加文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用iTextSharp添加PDF文件,但是如果PDF文件包含书签,则还应该添加它们.

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();

推荐答案

请阅读我的第6章书.在表6.1中,您将看到:

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

可以从其他PDF文档导入页面.主要缺点是在此过程中会丢失导入页面的所有交互功能(注释,书签,字段等).

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.

这正是您所经历的.但是,如果您查看该表中列出的其他类,则会发现PdfStamper,PdfCopy等...这些类确实保留了交互式功能.

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将保留书签.如果要使用PdfCopy(或PdfSmartCopy),则需要阅读第7章以了解如何保存它们.第7章不是免费提供的,但您可以在此处查阅示例: Java / C#.您需要 ConcatenateBookmarks 示例.

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.

请注意,由于未使用正确的类,因此您当前的代码看起来有些混乱.使用PdfStamper应该可以大大减少代码行数.

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.

这篇关于使用书签添加文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆