带有使用 iText java 创建的水印图像的 PDF 文件



将pdf文件发送到打印机时,它给出错误,例如"此页面上存在错误。Acrobat 可能无法正确显示页面。请联系创建 PDF 文档的人员以更正问题。

我正在创建一个 PDF 文件,并使用文本 java 向其添加水印图像。

如果从PDF文件中删除水印图像,则工作正常。

不知道水印图像的确切问题是什么?请帮忙。

以下是代码片段:

PdfReader pdfReader = new PdfReader(finalPath);
int noOfPages = pdfReader.getNumberOfPages();
PdfStamper stamp = new PdfStamper(pdfReader, new FileOutputStream(fileNameAfterWatermark));
int i = 0;
PdfContentByte underContent;    
PdfGState gs;
while (i < noOfPages) {
i++;
underContent = stamp.getUnderContent(i);
gs = new PdfGState();
gs.setFillOpacity(0.3f);                
gs.setStrokeOpacity(0.3f);              
Rectangle  pagesize = pdfReader.getPageSize(i);
int pageRotation = pdfReader.getPageRotation(i);
float  x = (pagesize.getLeft() + pagesize.getRight()) / 2 ;
float  y = (pagesize.getTop() + pagesize.getBottom()) / 2 ;
if(pageRotation != 0){
x = (pagesize.getHeight()) / 2;
y = (pagesize.getWidth()) / 2;
y = y - 80;
}
float w = image.getScaledWidth();
float h = image.getScaledHeight();
float scaleMultiplicationFactor = 1.25f;
float image_width = (w * (scaleMultiplicationFactor));
float image_height = (h * (scaleMultiplicationFactor));
float x_co_ordinate = x - (image_width / 2 );
float y_co_ordinate = y - (image_height / 2);
int fontSize = 180;
underContent.saveState();
underContent.setGState(gs);
underContent.beginText();
underContent.setFontAndSize(bf, fontSize);
underContent.setColorFill(Color.LIGHT_GRAY);
underContent.addImage(image, image_width, 0, 0, image_height, x_co_ordinate , y_co_ordinate );
underContent.endText();
underContent.restoreState();
}
stamp.close();
pdfReader.close();

您将水印内容添加到UnderContent中,如下所示:

underContent.saveState();
underContent.setGState(gs);
underContent.beginText();
underContent.setFontAndSize(bf, fontSize);
underContent.setColorFill(Color.LIGHT_GRAY);
underContent.addImage(image, image_width, 0, 0, image_height, x_co_ordinate , y_co_ordinate );
underContent.endText();
underContent.restoreState();

即,您将(位图?(图像添加到文本对象中。这是无效的,文本对象可能不包含外部对象或内联图像对象。在文本对象外部添加图像:

underContent.saveState();
underContent.setGState(gs);
underContent.beginText();
underContent.setFontAndSize(bf, fontSize);
underContent.setColorFill(Color.LIGHT_GRAY);
underContent.endText();
underContent.addImage(image, image_width, 0, 0, image_height, x_co_ordinate , y_co_ordinate );
underContent.restoreState();

话虽如此,您无需在该文本对象中添加任何内容。因此,您可以将代码简化为:

underContent.saveState();
underContent.setGState(gs);
underContent.addImage(image, image_width, 0, 0, image_height, x_co_ordinate , y_co_ordinate );
underContent.restoreState();

此外,您将该内容添加到UnderContent。因此,您在PdfGState中设置的透明度只会使图像更苍白。如果可以使原始位图像最终需要的那样苍白,则根本不需要使用该PdfGState。在某些PDF配置文件中,透明度是被禁止的,因此摆脱它也可能是有利的......

最新更新