我正在尝试在现有 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 的图像) 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();
提前致谢。