我有我需要动态添加图像/图像的现有PDF。该图像来自文件上传。一旦我上传了文件,如何指定在PDF上放置图像的位置。我找到的一个代码片段无法正常工作。这需要适用于任意数量页面的PDF。据我所知,绝对定位是从PDF的最后一页的左下角开始设置的。如果我需要一个图像显示从顶部30像素和第1页左侧50像素,我怎么能做到这一点?或者,如果我需要从第2页左侧的顶部/ 100像素显示50像素的图像?如何在使用IText的特定x-y坐标处将图像添加到PDF中?
我试过使用在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页的右上角 - 50像素形成从左侧顶部/ 30像素。
我知道我很接近...只需要一点点帮助让我明白我的需求。
我已更新我的代码。这得到图像到第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;
您的pdf只有“肖像”方向吗? IIRC你需要用横向pdf来解释旋转。此外,请始终关闭文件夹,否则文件可能会保持锁定状态。 (假设亨利提到你不在CF8上) – Leigh