|
@@ -0,0 +1,70 @@
|
|
|
|
|
+package com.gz;
|
|
|
|
|
+
|
|
|
|
|
+import com.spire.pdf.PdfDocument;
|
|
|
|
|
+import com.spire.pdf.PdfPageBase;
|
|
|
|
|
+import com.spire.pdf.graphics.*;
|
|
|
|
|
+
|
|
|
|
|
+import java.awt.*;
|
|
|
|
|
+import java.awt.geom.Dimension2D;
|
|
|
|
|
+import java.awt.geom.Point2D;
|
|
|
|
|
+import java.awt.geom.Rectangle2D;
|
|
|
|
|
+
|
|
|
|
|
+public class WatermarkPdf {
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+ public static void main(String[] args)
|
|
|
|
|
+ {
|
|
|
|
|
+ //加载PDF文档
|
|
|
|
|
+ PdfDocument pdf = new PdfDocument();
|
|
|
|
|
+ pdf.loadFromFile("D:\\Program Files (x86)\\Tencent\\WeChat\\WeChat_DATA\\WeChat Files\\wxid_p52tn1dpq62f22\\FileStorage\\File\\2021-11\\自检情况报告(南苑街道).pdf");
|
|
|
|
|
+
|
|
|
|
|
+ //调用AddImageWatermark方法给PDF第一页添加图片水印
|
|
|
|
|
+// AddImageWatermark(pdf.getPages().get(0), "H:\\Pictures\\20210615105005_4d1f0.jpg");
|
|
|
|
|
+
|
|
|
|
|
+ //调用AddTextWatermark方法给PDF第二页添加文字水印
|
|
|
|
|
+ AddTextWatermark(pdf.getPages().get(0), "测试水印");
|
|
|
|
|
+
|
|
|
|
|
+ //保存
|
|
|
|
|
+ pdf.saveToFile("H:\\Desktop\\Watermark.pdf");
|
|
|
|
|
+ //关闭
|
|
|
|
|
+ pdf.close();
|
|
|
|
|
+ }
|
|
|
|
|
+ /**
|
|
|
|
|
+ * @param page
|
|
|
|
|
+ * 要添加水印的页面
|
|
|
|
|
+ * @param imageFile
|
|
|
|
|
+ * 水印图片路径
|
|
|
|
|
+ */
|
|
|
|
|
+ static void AddImageWatermark(PdfPageBase page, String imageFile)
|
|
|
|
|
+ {
|
|
|
|
|
+ page.setBackgroundImage(imageFile);
|
|
|
|
|
+ Rectangle2D rect = new Rectangle2D.Float();
|
|
|
|
|
+ rect.setFrame(page.getClientSize().getWidth()/2 - 100, page.getClientSize().getHeight()/2 - 100, 200, 200);
|
|
|
|
|
+ page.setBackgroundRegion(rect);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * @param page
|
|
|
|
|
+ * 要添加水印的页面
|
|
|
|
|
+ * @param textWatermark
|
|
|
|
|
+ * 水印文字
|
|
|
|
|
+ */
|
|
|
|
|
+ static void AddTextWatermark(PdfPageBase page, String textWatermark)
|
|
|
|
|
+ {
|
|
|
|
|
+ Dimension2D dimension2D = new Dimension();
|
|
|
|
|
+ dimension2D.setSize(page.getCanvas().getClientSize().getWidth() / 2, page.getCanvas().getClientSize().getHeight() / 3);
|
|
|
|
|
+ PdfTilingBrush brush = new PdfTilingBrush(dimension2D);
|
|
|
|
|
+ brush.getGraphics().setTransparency(0.3F);
|
|
|
|
|
+ brush.getGraphics().save();
|
|
|
|
|
+ brush.getGraphics().translateTransform((float) brush.getSize().getWidth() / 2, (float) brush.getSize().getHeight() / 2);
|
|
|
|
|
+ brush.getGraphics().rotateTransform(-45);
|
|
|
|
|
+ brush.getGraphics().drawString(textWatermark, new PdfTrueTypeFont(new Font("宋体",Font.PLAIN,30),true), PdfBrushes.getRed(), 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
|
|
|
|
|
+ brush.getGraphics().restore();
|
|
|
|
|
+ brush.getGraphics().setTransparency(1);
|
|
|
|
|
+ Rectangle2D loRect = new Rectangle2D.Float();
|
|
|
|
|
+ loRect.setFrame(new Point2D.Float(0, 0), page.getCanvas().getClientSize());
|
|
|
|
|
+ page.getCanvas().drawRectangle(brush, loRect);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+}
|