猿问

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

我正在使用 iText 在 PDF 文件上添加水印(文本:“SuperEasy You Done”),如如何使用文本或图像对 PDF加水印?(TransparentWatermark2.java)。请参阅 GitHub 上的项目源代码。

现在我得到的 PDF 的一个例子是这个(文档的其余部分被省略):

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

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

http://img1.mukewang.com/618ca823000140af04240306.jpg

这是在给定字节数组上标记水印的代码(目前仅适用于我的 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:我读过这个,但没有帮助:


http://itext.2136553.n4.nabble.com/rotate-a-watermark-td2155042.html


小唯快跑啊
浏览 374回答 1
1回答

慕田峪4524236

您只需要指定所需的旋转角度作为此行中的第 6 个参数:ColumnText.showTextAligned(over,&nbsp;Element.ALIGN_CENTER,&nbsp;phrase,&nbsp;x,&nbsp;y,&nbsp;0);&nbsp;//&nbsp;rotate&nbsp;0&nbsp;grades&nbsp;in&nbsp;this&nbsp;case如果指定值为正 (> 0) 则逆时针旋转,否则 (< 0) 旋转顺时针。在这种特殊情况下,要将水印逆时针旋转 45 度,您只需像这样编写前一行:ColumnText.showTextAligned(over,&nbsp;Element.ALIGN_CENTER,&nbsp;phrase,&nbsp;x,&nbsp;y,&nbsp;45f);&nbsp;//&nbsp;45f&nbsp;means&nbsp;rotate&nbsp;the&nbsp;watermark&nbsp;45&nbsp;degrees&nbsp;anticlockwise通过应用相同的原理,我们可以实现任何方向的任何旋转。整个文档在这里:https&nbsp;:&nbsp;//developers.itextpdf.com/apis在第5版和第 7版的链接下。
随时随地看视频慕课网APP

相关分类

Java
我要回答