代码之家  ›  专栏  ›  技术社区  ›  lealceldeiro VonC

如何使用iText旋转PDF中的水印(文本)?

  •  2
  • lealceldeiro VonC  · 技术社区  · 7 年前

    我使用iText在PDF文件上打上水印(文本:“SuperEasy You Done”),如中所述 How to watermark PDFs using text or images? ( TransparentWatermark2.java See project source code on GitHub

    现在我得到的PDF的一个例子是 this one (本文件其余部分略去):

    enter image description here

    如您所见,水印居中且水平。

    我想去 在页面中间,但是 旋转45度 ,所以它逆时针旋转。像这样:

    enter image description here

    This is the code 用于在给定字节数组上加盖水印(pdf文档目前仅适用于我)

    /**
     * Returns the same document with the watermark stamped on it.
     * @param documentBytes Byte array of the pdf which is going to be returned with the watermark
     * @return byte[] with the same byte array provided but now with the watermark stamped on it.
     * @throws IOException If any IO exception occurs while adding the watermark
     * @throws DocumentException If any DocumentException exception occurs while adding the watermark
     */
    private byte[] getDocumentWithWaterMark(byte[] documentBytes) throws IOException, DocumentException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // pdf
        PdfReader reader = new PdfReader(documentBytes);
        int n = reader.getNumberOfPages();
        PdfStamper stamper = new PdfStamper(reader, outputStream);
        // text watermark
        Font font = new Font(Font.HELVETICA, 60);
        Phrase phrase = new Phrase("SuperEasy You Done", font);
        // transparency
        PdfGState gs1 = new PdfGState();
        gs1.setFillOpacity(0.06f);
        // properties
        PdfContentByte over;
        Rectangle pagesize;
        float x, y;
        // loop over every page (in case more than one page)
        for (int i = 1; i <= n; i++) {
            pagesize = reader.getPageSizeWithRotation(i);
            x = (pagesize.getLeft() + pagesize.getRight()) / 2;
            y = (pagesize.getTop() + pagesize.getBottom()) / 2;
            over = stamper.getOverContent(i);
            over.saveState();
            over.setGState(gs1);
            // add text
            ColumnText.showTextAligned(over, Element.ALIGN_CENTER, phrase, x, y, 0);
            over.restoreState();
        }
        stamper.close();
        reader.close();
        return outputStream.toByteArray();
    }
    

    附言:我读了这篇文章,但没用:

    1 回复  |  直到 7 年前
        1
  •  3
  •   lealceldeiro VonC    7 年前

    只需将所需的旋转角度指定为中的第6个参数 this line :

    ColumnText.showTextAligned(over, Element.ALIGN_CENTER, phrase, x, y, 0); // rotate 0 grades in this case
    

    如果指定值为正(>0)旋转方向为逆时针,否则(<0)顺时针旋转。

    like this :

    ColumnText.showTextAligned(over, Element.ALIGN_CENTER, phrase, x, y, 45f); // 45f means rotate the watermark 45 degrees anticlockwise
    


    整个文档如下: https://developers.itextpdf.com/apis 在的链接下 version 5 version 7