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

How to rotate watermark (text) in PDF using iText?

我正在使用 iText 在 PDF 文件上加盖水印(文本:"SuperEasy You Done"),如 (TransparentWatermark2.java). See project source code on GitHub 中所述。

现在我得到的 PDF 示例是 this one(文档的其余部分被省略):

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

我想保持它在页面中间居中,但是将它旋转“45”度,所以它逆时针旋转。像这样:

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();
}

PS:我读了这个,但没有帮助:

您只需要在this line中的第6个参数中指定想要的旋转角度即可:

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

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

在这种特殊情况下,要将水印逆时针旋转 45 度,您只需编写上一行 like this:

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

通过应用相同的原理,我们可以实现任何方向的任何旋转。


完整文档在此处:https://itextpdf.com/en/resources/api-documentation under the links for version 5 and version 7