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

我正在使用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

您只需指定所需的旋转角度作为此行中的第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的链接下。