maven项目开发遇到的问题。
这个问题有点坑,测试时doc(x)、xls(x)添加水印后正常显示,而ppt(x)打开后水印看不到,但是可以被选中。不了解pdf文档,搜了半天,最后发现pdf文档是分层的(用词不准)…设置水印时必须获取pdf文档的最上层(getOverContent())才能使得你设置的水印显示出来。mark下
/**
* pdf添加水印
*
* @param filePO po
* @param response res
* @param waterMarkContent 水印内容
* @throws DocumentException
* @throws IOException
*/
public static void setTextWaterMarkForPdf(FilePO filePO, HttpServletResponse response, String waterMarkContent)
throws DocumentException, IOException {
PdfReader reader = new PdfReader(filePO.getOnlinePath());
PdfStamper stamper = new PdfStamper(reader, response.getOutputStream());
PdfGState gs = new PdfGState();
//设置透明度
gs.setFillOpacity(0.3f);
BaseFont font = BaseFont.createFont("Courier", "Cp1252", false);
JLabel label = new JLabel();
label.setText(waterMarkContent);
FontMetrics metrics = label.getFontMetrics(label.getFont());
int textH = metrics.getHeight() * 2;
int textW = metrics.stringWidth(label.getText()) * 2;
int total = reader.getNumberOfPages() + 1;
PdfContentByte content;
for (int i = 1; i < total; i++) {
//**注意!这里是获取pdf最顶层,否则会使得部分pdf文档无法显示水印
content = stamper.getOverContent(i);
content.beginText();
content.setGState(gs);
content.setColorFill(BaseColor.RED);
content.setFontAndSize(font, 30);
// 开始写入水印
float pageWidth = reader.getPageSize(i).getWidth();
float pageHigh = reader.getPageSize(i).getHeight();
for (float heigh = 20; heigh < pageHigh; heigh += textH * 2) {
for (float width = 20; width < pageWidth; width += textW + 30) {
content.showTextAligned(Element.ALIGN_LEFT, waterMarkContent, width, heigh, -45);
}
}
content.endText();
}
stamper.close();
}
maven依赖:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>