iText - 如何在现有PDF上标记图像并创建锚点 [英] iText - How to stamp image on existing PDF and create an anchor
问题描述
我有一个现有文件,我想在绝对位置标记图像。
我能够做到这一点,但我也想让这个图像可以点击:当用户点击图像上的
时,我希望PDF转到文档的最后一页。
I have an existing document, onto which I would like to stamp an image at an absolute position. I am able to do this, but I would also like to make this image clickable: when a user clicks on the image I would like the PDF to go to the last page of the document.
这是我的代码:
PdfReader readerOriginalDoc = new PdfReader("src/main/resources/test.pdf");
PdfStamper stamper = new PdfStamper(readerOriginalDoc,new FileOutputStream("NewStamper.pdf"));
PdfContentByte content = stamper.getOverContent(1);
Image image = Image.getInstance("src/main/resources/images.jpg");
image.scaleAbsolute(50, 20);
image.setAbsolutePosition(100, 100);
image.setAnnotation(new Annotation(0, 0, 0, 0, 3));
content.addImage(image);
stamper.close();
知道如何做到这一点吗?
Any idea how to do this ?
推荐答案
您正在使用的技术仅适用于从头开始创建文档。
You are using a technique that only works when creating documents from scratch.
请查看 AddImageLink 示例,了解如何添加图像和链接,使该图像可以点击现有文档:
Please take a look at the AddImageLink example to find out how to add an image and a link to make that image clickable to an existing document:
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
Image img = Image.getInstance(IMG);
float x = 10;
float y = 650;
float w = img.getScaledWidth();
float h = img.getScaledHeight();
img.setAbsolutePosition(x, y);
stamper.getOverContent(1).addImage(img);
Rectangle linkLocation = new Rectangle(x, y, x + w, y + h);
PdfDestination destination = new PdfDestination(PdfDestination.FIT);
PdfAnnotation link = PdfAnnotation.createLink(stamper.getWriter(),
linkLocation, PdfAnnotation.HIGHLIGHT_INVERT,
reader.getNumberOfPages(), destination);
link.setBorder(new PdfBorderArray(0, 0, 0));
stamper.addAnnotation(link, 1);
stamper.close();
}
您已经有关于正确添加图像的部分。请注意,我为图像的位置及其尺寸创建参数:
You already have the part about adding the image right. Note that I create parameters for the position of the image as well as its dimensions:
float x = 10;
float y = 650;
float w = img.getScaledWidth();
float h = img.getScaledHeight();
我使用这些值来创建矩形
object:
I use these values to create a Rectangle
object:
Rectangle linkLocation = new Rectangle(x, y, x + w, y + h);
这是我们用 PdfAnnotation <创建的链接注释的位置/ code> class。您需要使用
addAnnotation()
方法单独添加此注释。
This is the location for the link annotation we are creating with the PdfAnnotation
class. You need to add this annotation separately using the addAnnotation()
method.
您可以查看结果这里: link_image.pdf
如果点击我图标,您跳转到文档的最后一页。
You can take a look at the result here: link_image.pdf If you click on the i icon, you jump to the last page of the document.
这篇关于iText - 如何在现有PDF上标记图像并创建锚点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!