PdfReader reader = new PdfReader("template.pdf");
PdfStamper stamper = new PdfStamper( reader, new FileOutputStream("output.pdf"));
PdfContentByte content = stamper.getOverContent(1); // first page == 1
Image image = Image.createInstance("someImage.png");
image.setAbsolutePosition( x, y );
image.setAbsoluteHeight( hei );
image.setAbsoluteWidth( wid );
content.addImage(image);
// instead of absolutely positioning the image, you can do:
//content.addImage( image, wid, 0f, 0f, hei, x, y );
// that's a transformation matrix, you can skew, rotate, scale, etc.
stamper.close();
如果您不知道确切的位置,您有几个选择。
1) 替换现有图像。
使用此选项,您实际上可以让模板稍微突出图像,使用 Alpha 混合等。获得幻想。如果您使用stamper.getUnderContent(1) 并使用透明背景构建模板,则可以对上述代码执行相同的操作。我刚刚回答了一个replace an image question,应该会在这方面有所帮助。
新图像将继承占位符图像的所有图形状态。 x,y,wid,hei, 可选内容组, 透明度, 各种东西。
2)在 Acrobat 中(或者我想是 iText)中为模板添加注释(字段易于访问),并使用它的 RECT 为上述代码提供 x,y,wid,hei。
// given the above stamper
AcroFields fields = stamper.getAcroFields();
PdfDictionary replaceAnnot = fields.getFieldItem("ReplaceMe").getMerged(0);
//we can remove the field from the PDF without breaking the info in replaceAnnot.
fields.removeField("ReplaceMe");
// rects are laid out [llx, lly, urx, ury]
PdfArray rect = replaceAnnot.getAsArray(PdfName.RECT);
float x = rect.getAsNumber(0).floatValue();
float y = rect.getAsNumber(1).floatValue();
float width = rect.getAsNumber(2).floatValue() - x;
float height = rect.getAsNumber(3).floatValue() - y;
将这些坐标输入到上面的图像代码中,你就可以开始了。