首页 文章

如何使用IText在特定的x-y坐标处将图像添加到PDF?

提问于
浏览
1

我有现有的PDF,我需要动态添加图像/图像 . 图像来自文件上传 . 上传文件后,如何指定将图像放在PDF上的位置 . 我找到的一个代码段无法正常工作 . 这需要适用于具有任意数量页面的PDF . 据我所知,绝对定位是从PDF最后一页的左下角设置的 . 如果我需要从顶部30像素和第1页左侧50像素显示图像,我该如何做到这一点?或者,如果我需要从第2页的左上角/ 100像素显示50像素的图像?

我已经尝试使用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;

3 回答

  • 6

    你在用CF8吗?您可以使用

    <cfpdf action="addWatermark" source="myPDF.pdf" image="myImage.jpg" 
           position="0,0" rotation="0" showOnPrint="true" opacity="10">
    
  • 1

    我找到了答案:

    页码必须在 com.lowagie.text.pdf.PdfStamper.getOverContent() 中设置:

    content = stamper.getOverContent(myPageNum);
    

    知道这很容易 .

  • 0

    你从 stamper.getOverContent(reader.getNumberOfPages()); 获得"OverContent" . getOverContent() 的参数是页码 . 因此,您的代码在最后一页获得了 PdfContentByte ,而不是第一页 .

相关问题