为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

小唯快跑啊 2021-11-11 13:19:41
我正在使用 iText 在 PDF 文件上添加水印(文本:“SuperEasy You Done”),如如何使用文本或图像对 PDF加水印?(TransparentWatermark2.java)。请参阅 GitHub 上的项目源代码。现在我得到的 PDF 的一个例子是这个(文档的其余部分被省略):如您所见,水印居中且水平。我想将它保持在页面中间的中心,但是将它旋转“45”度,所以它逆时针旋转。像这样的东西:这是在给定字节数组上标记水印的代码(目前仅适用于我的 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
查看完整描述

1 回答

?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

您只需要指定所需的旋转角度作为此行中的第 6 个参数:

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

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

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

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

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


整个文档在这里:https : //developers.itextpdf.com/apis在第5第 7的链接下。


查看完整回答
反对 回复 2021-11-11
  • 1 回答
  • 0 关注
  • 373 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信