从 pdf 中的 html 文本块访问内部 PDF 链接

Access Internal PDF links from html text block inside pdf

我正在使用 itext 5。我有一个带有 HTML 样式的字符串和一个 link 以转到 pdf 中的第 2 章。

String text = "<p><strong>Jack </strong>and <strong>Jill </strong>went up the hill, then down the hill, around the hill then to <a href="Chapter 2">Chater 2</a>.</p>";

我正在使用 HTMLWorker 将 html 解析为字符串,并使用带有 localGoto 的块为第 2 章设置本地目标。

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.PdfWriter;

public class InternalLinkExample {

    public static void main(String[] args) {

        Document document = new Document();

        try {

            PdfWriter.getInstance(document, new FileOutputStream("InternalLink.pdf"));

            String text = "<p><strong>Jack </strong>and <strong>Jill </strong>went up the hill, then down the hill, around the hill then to <a href=#\"Chapter2\">Chater 2</a>.</p>";

            document.open();

            HTMLWorker htmlWorker = new HTMLWorker(document);
            try {
                htmlWorker.parse(new StringReader(text));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            document.newPage();

            Chunk chunk = new Chunk("Chapter 2 Jack");
            chunk.setLocalDestination("Chapter2");  
            document.add(chunk);

            document.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

当我使用 iText 使用给定字符串生成 pdf 并在 adobe PDF 查看器中打开 PDF 内部 links 时,它会引发安全警告并且无法打开。但是,当我使用 google chrome 打开 pdf 时,我能够访问 link。

我想使用 adobe pdf 查看器访问内部 links。所以请让我知道如何从 Html 字符串访问内部 link 。另外,我正在升级到 Itext 7,如果该解决方案适用于 Itext 7 将会很有帮助。

iText 7 中的代码看起来与 iText 5 中的代码非常相似。确保散列符号 (#) 包含在 href 属性值中(在双引号内),即<a href="#Chapter2">

以下是如何在 iText 7 中为锚点生成 link 的完整代码。结果文档中的 link 在 Acrobat 中工作正常。

PdfDocument pdfDocument = new PdfDocument(new PdfWriter("C:/path/to.pdf"));
Document document = new Document(pdfDocument);

String text = "<p><strong>Jack </strong>and <strong>Jill </strong>went up the hill, then down the hill, around the hill then to <a href=\"#Chapter2\">Chapter 2</a>.</p>";

List<IElement> elements = HtmlConverter.convertToElements(text);

for (IElement element : elements) {
    if (element instanceof IBlockElement) {
        document.add((IBlockElement) element);
    }
}

document.add(new AreaBreak());

Text chapterTitle = new Text("Chapter 2 Jack").setDestination("Chapter2");
document.add(new Paragraph(chapterTitle));

document.close();