封装工具类
java
public class PdfOperationUtils {
// 日志记录器,用于记录操作日志
private static Logger logger = LogManager.getLogger(PdfOperationUtils.class);
/**
* pdf 加水印
* @param pdfFile 原pdf文件
* @param watermarkText 水印文字内容
* @param tmpDir 临时文件目录(为空时使用系统默认临时目录)
*/
public static void addWatermarkText(File pdfFile, String watermarkText, String tmpDir){
// 如果临时目录为空,则使用系统默认的临时目录
if(StringUtils.isBlank(tmpDir)) tmpDir=System.getProperty("java.io.tmpdir");
// 在临时目录下创建一个以UUID命名的子目录,用于存放处理中的临时PDF文件
File dir=new File(tmpDir, BaseUtils.getUUID(""));
// 临时目录中与源文件同名的输出文件(加水印后的PDF先写入这里,最后覆盖源文件)
File newPdfFile=new File(dir,pdfFile.getName());
InputStream is = null; // 源PDF输入流
OutputStream os = null; // 输出流
com.aspose.pdf.Document pdfDocument = null; // Aspose PDF文档对象
try {
// 如果临时目录不存在,则创建(支持多级目录)
if(!dir.exists()) {
dir.mkdirs();
}
// 加载Aspose PDF许可证,去除水印/试用限制
FileConvertUtils.loadAsposeLicense(FileConvertUtils.AsposeLicense_Type_Pdf);
// 打开源PDF文件输入流
is = new FileInputStream(pdfFile);
// 创建临时输出文件流
os = new FileOutputStream(newPdfFile);
// 记录开始时间,用于统计耗时
long old = System.currentTimeMillis();
// 通过输入流加载PDF文档
pdfDocument = new com.aspose.pdf.Document(is);
// 遍历 PDF 的每一页,在每页上添加水印
for (Page page : pdfDocument.getPages()) {
// 创建水印工件(Artifact),比普通Stamp更适合做页面级水印
WatermarkArtifact artifact = new WatermarkArtifact();
// 设置水印文本:内容、颜色(灰色)、字体样式(Courier斜体)、编码、嵌入字体、字号72
artifact.setText(new FormattedText(watermarkText,java.awt.Color.GRAY,FontStyle.CourierOblique,EncodingType.Identity_h,true,72.0F));
// artifact.setImage(is); // 备用:如需图片水印可取消注释
// 水平居中对齐
artifact.setArtifactHorizontalAlignment(HorizontalAlignment.Center);
// 垂直居中对齐
artifact.setArtifactVerticalAlignment(VerticalAlignment.Center);
// 水印旋转角度45度
artifact.setRotation(45);
// 水印透明度0.3(半透明)
artifact.setOpacity(0.3);
// 不作为背景(即显示在内容之上)
artifact.setBackground(false);
// 将水印添加到当前页的工件集合中
page.getArtifacts().add(artifact);
}
// 将添加水印后的PDF文档保存到临时输出流
pdfDocument.save(os);
// 关闭并释放输出流和输入流资源
BaseUtils.clean(os,is);
os=null;
is=null;
// 记录结束时间并输出耗时日志(单位:秒)
long now = System.currentTimeMillis();
logger.info("PdfOperationUtils.addWatermarkText 共耗时:" + ((now - old) / 1000.0) + "秒");
// 用临时文件覆盖原PDF文件,完成加水印
BaseUtils.copyFile(newPdfFile, pdfFile);
} catch (Exception e) {
// 捕获异常,记录错误日志并抛出运行时异常
logger.error("pdf加水印失败,"+e.getMessage(),e);
throw new RuntimeException(e);
} finally {
// 释放输出流、PDF文档对象、输入流等资源
BaseUtils.clean(os,pdfDocument,is);
// 删除临时PDF文件
BaseUtils.deleteFile(newPdfFile);
// 删除临时目录
BaseUtils.deleteFile(dir);
}
}
}
测试
java
@Test
public void pdfOperation() throws Exception {
PdfOperationUtils.addWatermarkText(new File("F:/3.pdf"), "123", null);
}
效果图
