在Java中使用iText在PDF文件上不可移动的水印

时间:2018-11-28 15:16:34

标签: java pdf itext watermark

我们有一个要求,即我们需要在杂志上添加文本水印,该杂志的每一页上都有多个丰富的图像。我尝试com.itextpdf.jar version 5.0.6添加水印,但最终我可以使用Adobe Acrobat Pro删除

我也尝试了下面的选项,但是那也不起作用。

stamper.setFreeTextFlattening(true); 

使用iText是否可以添加水印,而无需费劲就可以删除水印。

下面是我的实现。

public static void addWaterMark() throws IOException, DocumentException {
    PdfReader reader = new PdfReader("C:/Trade-catalog/Catalog2017.pdf");
    ByteArrayOutputStream outputPdf = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(reader, outputPdf);

    String bodyWatermarkText = "12345 - John Smith";
    String bodyWatermarkRotation = "35";
    String footerWatermarkText = "Richard Parker";
    BaseFont font = BaseFont.createFont("/fonts/micross.ttf", "Cp1250", BaseFont.EMBEDDED);

    PdfGState state = new PdfGState();
    state.setFillOpacity(0.3f);

    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
        Rectangle thisPageSize = reader.getPageSize(i);
        PdfPatternPainter bodyPainter = stamper.getOverContent(i).createPattern(thisPageSize.getWidth(),
                thisPageSize.getHeight());
        bodyPainter.setColorFill(new BaseColor(0, 0, 0));
        bodyPainter.beginText();
        bodyPainter.setTextRenderingMode(PdfPatternPainter.TEXT_RENDER_MODE_FILL);
        bodyPainter.setFontAndSize(font, 60);
        bodyPainter.showTextAlignedKerned(Element.ALIGN_CENTER, bodyWatermarkText, thisPageSize.getWidth() / 2,
                thisPageSize.getHeight() / 2, Integer.valueOf(bodyWatermarkRotation));
        bodyPainter.showTextAlignedKerned(Element.ALIGN_RIGHT, footerWatermarkText, thisPageSize.getWidth() * 0.97f,
                thisPageSize.getHeight() * 0.015f, 0);
        bodyPainter.endText();

        PdfContentByte overContent = stamper.getOverContent(i);
        overContent.setGState(state);
        overContent.setColorFill(new PatternColor(bodyPainter));
        overContent.rectangle(thisPageSize.getLeft(), thisPageSize.getBottom(), thisPageSize.getWidth(),
                thisPageSize.getHeight());
        overContent.fill();
        overContent.setFlatness(100);
    }
    stamper.close();
    FileOutputStream outputStream = new FileOutputStream(
            "C:/Trade-catalog/output/TradeCatalog2017Watermarked_bodyPainter.pdf");
    outputPdf.writeTo(outputStream);
    outputPdf.close();
    reader.close();
}

0 个答案:

没有答案