日期:2014-05-20 浏览次数:20698 次
try { PdfReader Read_PDF_To_Watermark = new PdfReader("Sample.pdf"); int number_of_pages = Read_PDF_To_Watermark.getNumberOfPages(); PdfStamper stamp = new PdfStamper(Read_PDF_To_Watermark, new FileOutputStream("New_PDF_With_Watermark_Image.pdf")); int i = 0; Image watermark_image = Image.getInstance("watermark.jpg"); watermark_image.setAbsolutePosition(200, 400); PdfContentByte add_watermark; while (i < number_of_pages) { i++; add_watermark = stamp.getUnderContent(i); add_watermark.addImage(watermark_image); } stamp.close(); } catch (Exception i1) { i1.printStackTrace(); }
------解决方案--------------------
Image watermarkImage = new Image(imgPath);
watermarkImage.setAbsolutePosition(x, y);
writer.setPageEvent( new MyPageEvent(watermarkImage) );
public MyPageEvent extends PdfPageEventHelper {
private Image waterMark;
public MyPageEvent(Image img) {
waterMark = img;
}
public void OnEndPage(PdfWriter writer, Document doc) {
PdfContentByte content = writer.getContent();
content.addImage( waterMark );
}
}