[英]How can I add an image to a PDF at specific x-y coordinates using IText?
我有现有的 PDF,需要动态添加图像/图像。 图片来自文件上传。 上传文件后,如何指定在 PDF 上放置图像的位置。 我发现的一个代码片段无法正常工作。 这需要适用于具有任意页数的 PDF。 据我了解,绝对定位是从PDF最后一页的左下角设置的。 如果我需要在第 1 页顶部和左侧 50 像素处显示图像,我该如何实现? 或者,如果我需要在第 2 页上显示距顶部 50 像素/距左侧 100 像素的图像?
我尝试使用在http://rip747.wordpress.com/2009/03/26/add-an-image-dynamically-to-a-pdf-with-cf-and-itext/找到的代码。 我已根据以下需要对其进行了修改:
<cfscript>
myLeft = 30;
myTop = 50;
myPageNum = 1;
// output buffer to write PDF
fileIO = createObject("java","java.io.FileOutputStream").init(myOutputPath);
// reader to read our PDF
reader = createObject("java","com.lowagie.text.pdf.PdfReader").init(mySourcePath);
// stamper so we can modify our existing PDF
stamper = createObject("java","com.lowagie.text.pdf.PdfStamper").init(reader, fileIO);
// get the content of our existing PDF
content = stamper.getOverContent(reader.getNumberOfPages());
// create an image object so we can add our dynamic image to our PDF
image = createobject("java", "com.lowagie.text.Image");
// initalize our image
img = image.getInstance(imgPath);
x = (reader.getPageSize(1).width() - img.scaledWidth()) - myLeft;
y = (reader.getPageSize(1).height() - img.scaledHeight()) - myTop;
// now we assign the position to our image
img.setAbsolutePosition(javacast("float", x), javacast("float", y));
// add our image to the existing PDF
content.addImage(img);
// flattern our form so our values show
stamper.setFormFlattening(true);
// close the stamper and output our new PDF
stamper.close();
// close the reader
reader.close();
</cfscript>
上面的代码将我的图像放在第 2 页的右上角 - 距左上角 50px/30px。
我知道我很接近......只需要一点帮助来确定我的需要。
我已经更新了我的代码。 这会将图像带到第 2 页的左上角 - 正确定位,但我希望它在第 1 页:
x = myLeft;
y = (reader.getPageSize(1).height()) - img.scaledHeight() - myTop;
我想也许我需要添加第 1 页的高度才能使图像达到第 1 页,但是当我尝试以下任一选项时,图像会完全消失:
// I figure I'll need something like this to handle multi-page docs
y = (reader.getPageSize(1).height() * reader.getNumberOfPages()) - img.scaledHeight() - myTop;
y = reader.getPageSize(1).height() + reader.getPageSize(1).height() - img.scaledHeight() - myTop;
你从stamper.getOverContent(reader.getNumberOfPages());
得到你的“OverContent”。 . getOverContent()
的参数是页码。 因此,您的代码正在获取最后一页的PdfContentByte
,而不是第一页。
我找到了答案:
页码必须在com.lowagie.text.pdf.PdfStamper.getOverContent()
中设置:
content = stamper.getOverContent(myPageNum);
知道这很容易。
你用的是CF8+吗? 您可以使用
<cfpdf action="addWatermark" source="myPDF.pdf" image="myImage.jpg"
position="0,0" rotation="0" showOnPrint="true" opacity="10">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.