iText 中的图像定位 - Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13021193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Image positioning in iText - Java
提问by Anurag Ramdasan
I am trying to read one PDF and copy its data into another PDF. The first PDF contains some text and images and I wish to write an image in the second PDF exactly where the text ends(which is basically the end of the PDF file). RIght now it just prints at the top. How can I make this change?
我正在尝试阅读一个 PDF 并将其数据复制到另一个 PDF 中。第一个 PDF 包含一些文本和图像,我希望在第二个 PDF 中准确地在文本结束的位置(基本上是 PDF 文件的结尾)写一个图像。现在它只是打印在顶部。我怎样才能做出这个改变?
PdfReader reader = null;
reader = new PdfReader(Var.input);
Document document=new Document();
PdfWriter writer = null;
writer = PdfWriter.getInstance(document,new FileOutputStream(Var.output));
PdfImportedPage page = writer.getImportedPage(reader, 1);
reader.close();
document.open();
PdfContentByte cb = writer.getDirectContent();
// Copy first page of existing PDF into output PDF
document.newPage();
cb.addTemplate(page, 0, 0);
// Add your new data / text here
Image image = null;
image = Image.getInstance (Var.qr);
document.add(image);
document.close();
采纳答案by mkl
You should use a PdfStamper instead of a PdfWriter with imported pages. Your approach throws away all interactive contents. You can use sorifiend's idea there, too.
对于导入的页面,您应该使用 PdfStamper 而不是 PdfWriter。您的方法丢弃了所有交互式内容。你也可以在那里使用 sorifiend 的想法。
To determine where the text on the given page ends, have a look at the iText in Action, 2nd edition example ShowTextMarginswhich parses a PDF and ads a rectangle showing the text margin.
要确定给定页面上的文本结束位置,请查看 iText in Action,第 2 版示例ShowTextMargins,它解析 PDF 并显示一个显示文本边距的矩形。
回答by sorifiend
Try this:
试试这个:
First get the location/co-ords of where the image needs to go, then simply add the second line from below to your code so the image is inserted at that location "X, Y"
首先获取图像需要去的位置/坐标,然后只需将下面的第二行添加到您的代码中,以便将图像插入该位置“X,Y”
Image image = Image.getInstance(String RESOURCE);
image.setAbsolutePosition(X, Y);
writer.getDirectContent().addImage(image);
Take a look here for some examples in iText 5: https://itextpdf.com/en/resources/examples/itext-5-legacy/chapter-3-adding-content-absolute-positions
在这里查看 iText 5 中的一些示例:https: //itextpdf.com/en/resources/examples/itext-5-legacy/chapter-3-adding-content-absolute-positions