如何使用itext7.1在原始内容下添加文本水印

时间:2019-09-10 12:57:56

标签: java itext7

我有2个我无法解决的问题。 1-我想要透明的水印,或者我应该说它应该在原始文本的后面。目前它正在隐藏原始文本。 2-我想制作更多深色水印。它会变成非常浅的灰色。

当我不知道什么是页面大小时。此代码对于不同大小的页面会有所帮助。 A1,A2,A3,A4可以使用的所有不同尺寸的页面和水印都会出现在中间。我遇到了水印,但有两个问题。

 public static void watermarkPDF(PdfDocument pdfDoc, String watermarkText) 
    throws IOException
    {

    float formXOffset = 0;
    float formYOffset = 0;
    PdfFont font = PdfFontFactory.createFont();

    int numberOfPages = pdfDoc.getNumberOfPages();
    PdfPage page = null;


    for (int i = 1; i <= numberOfPages; i++)
    {
        page = pdfDoc.getPage(i);
        Rectangle ps = page.getPageSize();
        float width = ps.getWidth();
        float height = ps.getHeight();
        float fontSize = Math.min(width, height) / 12;
        height = height / 2;
        width = width / 2;
        //Center the annotation     
        Rectangle watermarkTrimmingRectangle = new Rectangle(ps.getWidth(), ps.getHeight() );
        PdfWatermarkAnnotation watermark = new PdfWatermarkAnnotation(watermarkTrimmingRectangle);

        //Apply linear algebra rotation math
        //Create identity matrix
        AffineTransform transform = new AffineTransform();//No-args constructor creates the identity transform

        float textwidth = font.getWidth(watermarkText, fontSize);

        float remainarea = ps.getWidth()-textwidth;

        //Apply translation
        transform.translate(remainarea/2, height);
        //Apply rotation
        //transform.rotate(45f);

        PdfFixedPrint fixedPrint = new PdfFixedPrint();
        watermark.setFixedPrint(fixedPrint);
        //Create appearance
        Rectangle formRectangle = new Rectangle(formXOffset, formYOffset,  ps.getWidth(), ps.getHeight());

        //Observation: font XObject will be resized to fit inside the watermark rectangle
        PdfFormXObject form = new PdfFormXObject(formRectangle);
        PdfExtGState gs1 = new PdfExtGState().setFillOpacity(0.1f);
        PdfCanvas canvas = new PdfCanvas(form, pdfDoc);

        float[] transformValues = new float[6];
        transform.getMatrix(transformValues);
        canvas.saveState()
            .beginText().setFillColorGray((float) 0.1).setExtGState(gs1)
            .setTextMatrix(transformValues[0], transformValues[1], transformValues[2], transformValues[3], transformValues[4], transformValues[5])
            .setFontAndSize(font, fontSize)
            .showText(watermarkText)
            .endText()
            .restoreState();

        canvas.release();

        watermark.setAppearance(PdfName.N, new PdfAnnotationAppearance(form.getPdfObject()));
        watermark.setFlags(PdfAnnotation.PRINT);

        page.addAnnotation(watermark);

    }
    page.flush();
    pdfDoc.close();
} 

水印不应隐藏文件的原始内容。并且在我打印输出时应该足够暗。

1 个答案:

答案 0 :(得分:0)

private static void removeWatermarkFromPDF(PdfDocument pdfDocument) throws IOException {
    PdfObject obj;
    for (int i = 1; i <= pdfDocument.getNumberOfPages(); i++) {
        PdfArray contentObjects = pdfDocument.getPage(i).getPdfObject().getAsArray(PdfName.Contents);
        for (int j = 0; j <= contentObjects.size() - 1; j++) {
            obj = contentObjects.get(j);
            if (obj != null && obj.isStream()) {
                byte[] b;
                try {
                    b = ((PdfStream) obj).getBytes();
                } catch (PdfException exc) {
                    b = ((PdfStream) obj).getBytes(false);
                }
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                baos.write(b);
                if (baos.toString().contains("iText Watermark")) {
                    contentObjects.remove(j);
                }
                baos.close();
            }
        }
    }
}
public static void main(String[] args) throws Exception {
        PdfDocument pdfDocument = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
        addWatermark(pdfDocument, "iText Watermark");
        pdfDocument.close();

        pdfDocument = new PdfDocument(new PdfReader(DEST), new PdfWriter(DEST2));
        removeWatermarkFromPDF(pdfDocument);
        pdfDocument.close();
}
public static void addWatermark(PdfDocument pdfDocument, String text) throws Exception {
        PdfFont font = PdfFontFactory.createFont();

        PdfExtGState gs1 = new PdfExtGState();
        gs1.setFillOpacity(0.2f);

        for (int i = 1; i <= pdfDocument.getNumberOfPages(); i++) {
            PdfPage page = pdfDocument.getPage(i);
            float fontSize = Math.min(page.getPageSize().getWidth(), page.getPageSize().getHeight()) / 12;
            Paragraph p = new Paragraph(text)
                    .setFontColor(ColorConstants.LIGHT_GRAY, 0.2f).setFont(font).setFontSize(fontSize);
            PdfCanvas under = new PdfCanvas(page.newContentStreamBefore(), new PdfResources(), pdfDocument);
            under.setExtGState(gs1);
            new Canvas(under, pdfDocument, pdfDocument.getDefaultPageSize())
                    .showTextAligned(p,
                            page.getPageSize().getWidth() / 2,
                            page.getPageSize().getHeight() / 2,
                            1, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
        }

        pdfDocument.close();
}