我正在尝试在Itext5中制作不可移除的透明水印,我能够使用PdfPatternPainter使水印不可移除,但仍然面临一个问题,即水印不太透明,并且仍然覆盖内容并使其更难阅读
我的代码如下:
public class TestWatermark {
public static String resourcesPath = "C:\\Users\\java\\Desktop\\TestWaterMark\\";
public static String FILE_NAME = resourcesPath + "test.pdf";
public static void main(String[] args) throws IOException {
System.out.println("########## STARTED ADDING WATERMARK ###########");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] byteArray = Files.readAllBytes(Paths.get(FILE_NAME));
String watermarkText = "confidential";
String fontPath = resourcesPath + "DINNextLTArabic-Regular.ttf";
Font arabicFont = FontFactory.getFont(fontPath, BaseFont.IDENTITY_H, 16);
BaseFont baseFont = arabicFont.getBaseFont();
PdfReader reader = new PdfReader(byteArray);
PdfStamper stamper = new PdfStamper(reader, baos);
int numberOfPages = reader.getNumberOfPages();
float height = baseFont.getAscentPoint(watermarkText, 24) + baseFont.getDescentPoint(watermarkText, 24);
for (int i = 1; i <= numberOfPages; i++) {
Rectangle pageSize = reader.getPageSizeWithRotation(i);
PdfContentByte overContent = stamper.getOverContent(i);
PdfPatternPainter bodyPainter = stamper.getOverContent(i).createPattern(pageSize.getWidth(),
pageSize.getHeight());
BaseColor baseColor = new BaseColor(10, 10, 10);
bodyPainter.setColorStroke(baseColor);
bodyPainter.setColorFill(baseColor);
bodyPainter.setLineWidth(0.85f);
bodyPainter.setLineDash(0.2f, 0.2f, 0.2f);
PdfGState state = new PdfGState();
state.setFillOpacity(0.01f);
overContent.saveState();
overContent.setGState(state);
for (float x = 70f; x < pageSize.getWidth(); x += height + 100) {
for (float y = 90; y < pageSize.getHeight(); y += height + 100) {
bodyPainter.beginText();
bodyPainter.setTextRenderingMode(PdfPatternPainter.TEXT_RENDER_MODE_FILL);
bodyPainter.setFontAndSize(baseFont, 13);
bodyPainter.showTextAlignedKerned(Element.ALIGN_MIDDLE, watermarkText, x, y, 45f);
bodyPainter.endText();
overContent.setColorFill(new PatternColor(bodyPainter));
overContent.rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(),
pageSize.getHeight());
overContent.fill();
}
}
overContent.restoreState();
}
stamper.close();
reader.close();
byteArray = baos.toByteArray();
File outputFile = new File(resourcesPath + "output.pdf");
if (outputFile.exists()) {
outputFile.delete();
}
Files.write(outputFile.toPath(), byteArray);
System.out.println("########## FINISHED ADDING WATERMARK ###########");
} catch (Exception e) {
e.printStackTrace();
}
}
}
请告知如何让我的水印不覆盖文字
我能够通过将 overContent 的不透明度设置得非常低来完成要求,如下所示:
state.setFillOpacity(0.01f);
并将画家颜色更改为:
BaseColor baseColor = new BaseColor(10, 10, 10);