【发布时间】:2019-11-27 11:45:12
【问题描述】:
我正在使用 itext 5。我有一个带有 HTML 样式的字符串和一个指向 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 内部链接时,它会引发安全警告并且无法打开。但是,当我使用谷歌浏览器打开 pdf 时,我可以访问链接。
我想使用 adobe pdf 查看器访问内部链接。所以请让我知道如何从 Html 字符串访问内部链接。另外,我正在升级到 Itext 7,如果该解决方案适用于 Itext 7,将会很有帮助。
【问题讨论】:
-
你的问题不清楚。您是简单地将 HTML 转换为 PDF,还是仅使用 HTML 到元素的转换来对元素应用一些样式,同时自己生成文档?或者您是否修改现有文档?
-
@AlexeySubach 我只是使用 HTML 进行元素转换,以便在生成 pdf 时对元素应用一些样式。
-
@AlexeySubach 我已经用实际代码更新了这个问题。