作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图在现有的 PDF 中提供一个超链接,单击该链接将打开该文件。如何做到这一点?
我尝试遵循代码,它对于外部超链接(如 http://www.google.com)工作正常。 但不适用于本地文件超链接,例如 D:/intro.pdf 。
我正在使用itext pdf 库。
代码:
String in = "D:/introduction.pdf";
String out = "D:/introduction.pdf";
try {
PdfReader reader = new PdfReader(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, baos);
PdfContentByte canvas=stamper.getOverContent(6);
Chunk imdb = new Chunk("Local Link");
imdb.setAnchor("http://www.google.com"); // this work
// imdb.setAnchor("D://intro.pdf"); // this does not work
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(imdb), 100, 10, 0);
stamper.close();
FileOutputStream fileOutputStream = new FileOutputStream(out);
IOUtils.write(baos.toByteArray(), fileOutputStream);
} catch (Exception e) {
}
我还尝试使用注释,如下所示:
PdfAnnotation annotation;
PdfName aa=new PdfName("test test");
annotation = PdfAnnotation.createLink(stamper.getWriter(),
new Rectangle(50f, 750f, 180f, 800f),aa,PdfAction.gotoRemotePage("file:///D:/intro.pdf","1", false, true));
annotation.setTitle("Click Here");
stamper.addAnnotation(annotation, 1);
我还尝试了@Bruno Lowagie的以下代码注释:[它在给定页面上但在intro.pdf文件中创建链接,当我单击同一页面上的链接时(intro.pdf) ]
如上图所示(intro.pdf 第 2 页的图像)
PdfReader reader1 = new PdfReader("D://introduction.pdf");
PdfStamper stamper1 = new PdfStamper(reader1, new FileOutputStream("D://intro.pdf"));
PdfAnnotation link1 = PdfAnnotation.createLink(stamper1.getWriter(),
new Rectangle(136, 780, 559, 806), PdfAnnotation.HIGHLIGHT_INVERT,
new PdfAction("D://introduction.pdf", 1));
link1.setTitle("Click Here");
stamper1.addAnnotation(link1, 2);
stamper1.close();
提前致谢。
最佳答案
您需要指定协议(protocol)。对于网页,您的 URI 以 http://
开头;对于文件,您的 URI 应以 file://
开头。
但是,由于您要链接的文件也是 PDF 文件,您可能不想使用 setAnchor()
方法。您应该使用 setRemoteGoto()
方法。请参阅MovieLinks2示例。
如果您想添加指向现有文档的链接,请按以下步骤操作:
PdfReader reader = new PdfReader("hello.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("hello_link.pdf"));
PdfAnnotation link = PdfAnnotation.createLink(stamper.getWriter(),
new Rectangle(36, 790, 559, 806), PdfAnnotation.HIGHLIGHT_INVERT,
new PdfAction("hello.pdf", 1));
stamper.addAnnotation(link, 1);
stamper.close();
如果您查看 PDF 文档内部,您将看到名为 hello_link.pdf 的新文件包含引用旧文件 hello.pdf 的链接注释:
关于Java使用itext在现有pdf中设置本地文件超链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18052858/
我是一名优秀的程序员,十分优秀!