gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:09:23 25 4
gpt4 key购买 nike

将 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 透明度是被禁止的,因此摆脱它也可能是有利的......

关于java - 使用 iText java 创建的带有水印图像的 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50705266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com