• Java实现给PDF文件加文字水印和图片水印(可以自定义水印格式)


    使用Java代码给PDF文件加文字水印

    直接上代码运行即可

    依赖

    有的可能用不上我直接复制全部了

     <dependencies>
            <!--word文件转PDF以及水印-->
            <dependency>
                <groupId>e-iceblue</groupId>
                <artifactId>spire.doc.free</artifactId>
                <version>3.9.0</version>
            </dependency>
            <dependency>
                <groupId>e-iceblue</groupId>
                <artifactId>spire.pdf.free</artifactId>
                <version>3.9.0</version>
            </dependency>
            <!--解析word时用到的包-->
            <dependency>
                <groupId>com.lowagie</groupId>
                <artifactId>itext</artifactId>
                <version>2.1.7</version>
            </dependency>
            <!--lombok-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.16</version>
                <scope>compile</scope>
            </dependency>
            <!--Aspose相关依赖 需要在本地指定导入-->
            <dependency>
                <groupId>com.aspose.words</groupId>
                <artifactId>aspose-words</artifactId>
                <version>words-15.8.0-jdk16</version>
                <scope>system</scope>
                <systemPath>${project.basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
            </dependency>
    
            <dependency>
                <groupId>com.aspose.cells</groupId>
                <artifactId>aspose-cells</artifactId>
                <version>cell-8.5.2</version>
                <scope>system</scope>
                <systemPath>${project.basedir}/src/main/resources/lib/aspose-cells-8.5.2.jar</systemPath>
            </dependency>
    
            <dependency>
                <groupId>com.aspose.pdf</groupId>
                <artifactId>aspose-pdf</artifactId>
                <version>pdf-17.3.0</version>
                <scope>system</scope>
                <systemPath>${project.basedir}/src/main/resources/lib/aspose.pdf-17.3.0.jar</systemPath>
            </dependency>
            <!--文件上传-->
    
            <!--骑缝章相关依赖-->
            <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itextpdf</artifactId>
                <version>5.5.13</version>
            </dependency>
    
            <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itext-asian</artifactId>
                <version>5.2.0</version>
            </dependency>
    
            <dependency>
                <groupId>com.itextpdf.tool</groupId>
                <artifactId>xmlworker</artifactId>
                <version>5.5.13</version>
            </dependency>
    
            <dependency>
                <groupId>fr.opensagres.xdocreport</groupId>
                <artifactId>fr.opensagres.poi.xwpf.converter.pdf-gae</artifactId>
                <version>2.0.1</version>
            </dependency>
    
        </dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77

    文字水印

    方式1

     public static void addWatermarkWYH(String filepath, String data) {
            Document pdfDocument = new Document(filepath);
            TextStamp textStamp = new TextStamp(data);
            //背景(好像没用)
            textStamp.setBackground(true);
            //x坐标  可以通过xy坐标来定义水印的具体位置
            textStamp.setXIndent(100);
            //y坐标
            textStamp.setYIndent(10);
            //通过以下属性控制水印的样式 字体 大小 颜色等
            //旋转角度
            textStamp.setRotateAngle(0);
            //字体类型
            textStamp.getTextState().setFont(FontRepository.findFont("Arial"));
            //字体大小
            textStamp.getTextState().setFontSize(20.0F);
            //字体样式
            textStamp.getTextState().setFontStyle(FontStyles.Italic);
            //字体颜色
            textStamp.getTextState().setForegroundColor(com.aspose.pdf.Color.fromRgb(Color.yellow));
    
            TextStamp textStamp1 = new TextStamp(data);
            textStamp1.setBackground(true);
            textStamp1.setXIndent(200);//设置位置
            textStamp1.setYIndent(10);
            textStamp1.setRotateAngle(0);//设置旋转角度
            textStamp1.getTextState().setFont(FontRepository.findFont("Arial"));
            textStamp1.getTextState().setFontSize(30.0F);//设置字体大小
            textStamp1.getTextState().setFontStyle(FontStyles.Italic);
            textStamp1.getTextState().setForegroundColor(com.aspose.pdf.Color.fromRgb(Color.green));
    
    
            TextStamp textStamp2 = new TextStamp(data);
            textStamp2.setBackground(true);
            textStamp2.setXIndent(300);
            textStamp2.setYIndent(10);
            textStamp2.setRotateAngle(0);
            textStamp2.getTextState().setFont(FontRepository.findFont("Arial"));
            textStamp2.getTextState().setFontSize(40.0F);
            textStamp2.getTextState().setFontStyle(FontStyles.Italic);
            textStamp2.getTextState().setForegroundColor(com.aspose.pdf.Color.fromRgb(Color.red));
            PageCollection pages = pdfDocument.getPages();
            System.out.println(pages);
            int size = pages.size();
            for (int i = 1; i <= size; i++) {
                //如果只想要一个水印 只添加一个即可
                pages.get_Item(i).addStamp(textStamp);
                pages.get_Item(i).addStamp(textStamp1);
                pages.get_Item(i).addStamp(textStamp2);
            }
            pdfDocument.save(filepath);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
      public static void main(String[] args) throws IOException {
            //原pdf文件路径
            String sourcePath = "D:\\File\\b.pdf";
            //指定水印内容
            ConvertPDFUtils.addWatermarkWYH(sourcePath, "已审核");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    方式2

      /**
         * @param page          要添加水印的页面
         * @param textWatermark 水印文字
         */
        public static void AddTextWatermark(PdfPageBase page, String textWatermark) {
            Dimension2D dimension2D = new Dimension();
            dimension2D.setSize(page.getCanvas().getClientSize().getWidth() / 3, 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.getGray(), 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);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
        public static void main(String[] args) throws IOException {
            //原pdf文件路径
            String sourcePath = "D:\\file\\test.pdf";
            //目标pdf文件路径
            String targetPath = "D:\\file\\Watermark22.pdf";
            //加载原pdf文档
            PdfDocument pdf = new PdfDocument();
            pdf.loadFromFile(sourcePath);
            PdfReader reader = new PdfReader(sourcePath);
            int total = reader.getNumberOfPages();
            for (int i = 0; i < total; i++) {
                ConvertPDFUtils.AddTextWatermark(pdf.getPages().get(i), "已审阅");
            }
            //保存
            pdf.saveToFile(targetPath);
            ConvertPDFUtils.addWatermark(sourcePath, "hahah");
            //关闭
            pdf.close();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    图片水印

    package dmyz.util;
    
    /**
     * @Author 魏一鹤
     * @Description  生成图片水印
     * @Date 10:43 2022/6/28
    **/
    import com.spire.pdf.*;
    import com.spire.pdf.automaticfields.PdfCompositeField;
    import com.spire.pdf.automaticfields.PdfPageCountField;
    import com.spire.pdf.automaticfields.PdfPageNumberField;
    import com.spire.pdf.graphics.*;
    
    import java.awt.*;
    import java.awt.geom.Dimension2D;
    import java.awt.geom.Rectangle2D;
        public class ImageWaterMark {
            public static void main(String[] args) {
                //实例化PdfDocument类的对象,并加载测试文档
                PdfDocument pdf = new PdfDocument();
                //获取文档
                pdf.loadFromFile("D:\\File\\test\\wyh\\moban.pdf");
                //添加一个空白页,目的为了删除jar包添加的水印,后面再移除这一页
                pdf.getPages().add();
                //创建字体
                PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("宋体", Font.PLAIN, 10),true);
                //遍历文档中的页
                for (int i = 0; i < pdf.getPages().getCount(); i++) {
                    Dimension2D pageSize = pdf.getPages().get(i).getSize();
                    float y = (float) pageSize.getHeight() - 40;
                    //初始化页码域
                    PdfPageNumberField number = new PdfPageNumberField();
                    //初始化总页数域
                    PdfPageCountField count = new PdfPageCountField();
                    //创建复合域
                    PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.getBlack(), "第{0}页 共{1}页", number, count);
                    //设置复合域内文字对齐方式
                    compositeField.setStringFormat(new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top));
                    //测量文字大小
                    Dimension2D textSize = font.measureString(compositeField.getText());
                    //设置复合域的在PDF页面上的位置及大小
                    compositeField.setBounds(new Rectangle2D.Float(((float) pageSize.getWidth() - (float) textSize.getWidth())/2, y, (float) textSize.getWidth(), (float) textSize.getHeight()));
                    //将复合域添加到PDF页面
                    compositeField.draw(pdf.getPages().get(i).getCanvas());
                }
                //移除第一个页
                pdf.getPages().remove(pdf.getPages().get(pdf.getPages().getCount()-1));
                //加载图片,设置为背景水印
                PdfPageBase page = pdf.getPages().get(0);
                //指定水印在文档中的位置及图片大小
                page.setBackgroundImage("D:\\File\\test\\wyh\\zhang.png");
                Rectangle2D.Float rect = new Rectangle2D.Float();
                //设置水印大小以及位置
                rect.setRect(400, 600, 150, 150);
                page.setBackgroundRegion(rect);
                //保存文档
                pdf.saveToFile("D:\\File\\test\\wyh\\imageWaterMark.pdf");
                pdf.close();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61

    全部的工具类代码

    package dmyz.util;
    
    import com.aspose.cells.License;
    import com.aspose.cells.SaveFormat;
    import com.aspose.cells.Workbook;
    import com.aspose.pdf.*;
    import com.aspose.pdf.devices.JpegDevice;
    import com.aspose.pdf.devices.PngDevice;
    import com.aspose.pdf.devices.Resolution;
    import com.spire.pdf.PdfPageBase;
    import com.spire.pdf.graphics.*;
    
    import javax.imageio.ImageIO;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.*;
    import java.awt.geom.Dimension2D;
    import java.awt.geom.Point2D;
    import java.awt.geom.Rectangle2D;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.util.ArrayList;
    import java.util.List;
    
    
    public class ConvertPDFUtils {
        /**
         * 获取license
         *
         * @return
         */
        public static boolean getLicense() {
            boolean result = false;
            try {
                InputStream is = ConvertPDFUtils.class.getClassLoader().getResourceAsStream("\\license.xml");
                License aposeLic = new License();
                aposeLic.setLicense(is);
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    
        /**
         * 支持DOC, DOCX, OOXML, RTF, HTML, OpenDocument, PDF, EPUB, XPS, SWF等相互转换<br>
         *
         * @param excelfilePath [原始excel路径]
         * @param pdfFilePath   [输出路径]
         */
    
        public static Boolean excelConvertToPdf(String excelfilePath, String pdfFilePath) {
            // 验证License
            if (!getLicense()) {
                return false;
            }
    
            try {
                // 原始excel路径
                Workbook wb = new Workbook(excelfilePath);
                // 输出路径
                File pdfFile = new File(pdfFilePath);
                FileOutputStream fileOS = new FileOutputStream(pdfFile);
                wb.save(fileOS, SaveFormat.PDF);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 支持DOC, DOCX, OOXML, RTF, HTML, OpenDocument, PDF, EPUB, XPS, SWF等相互转换<br>
         *
         * @param wordfilePath [原始excel路径]
         * @param pdfFilePath  [输出路径]
         */
        public static Boolean wordConvertToPdf(String wordfilePath, String pdfFilePath) {
            // 验证License
            if (!getLicense()) {
                return false;
            }
    
            try {
                // 原始word路径
                Document doc = new Document(wordfilePath);
                // 输出路径
                File pdfFile = new File(pdfFilePath);
                FileOutputStream fileOS = new FileOutputStream(pdfFile);
                doc.save(fileOS,SaveFormat.PDF);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 将pdf转图片
         *
         * @param inputStream pdf源文件流
         * @param imgFilePath 转成一张图片文件全路径 例如 "D:\\home\\qq.png"
         */
        public static void pdfToImage(InputStream inputStream, String imgFilePath) {
            try {
                System.out.println("convert pdf2jpg begin");
                long old = System.currentTimeMillis();
                if (!getLicense()) {
                    return;
                }
                Document pdfDocument = new Document(inputStream);
                //分辨率
                Resolution resolution = new Resolution(130);
                JpegDevice jpegDevice = new JpegDevice(resolution);
                List<BufferedImage> imageList = new ArrayList<BufferedImage>();
                List<File> fileList = new ArrayList<File>();
                for (int index = 1; index <= pdfDocument.getPages().size(); index++) {
                    File file = File.createTempFile("tempFile", "png");
                    FileOutputStream fileOS = new FileOutputStream(file);
                    jpegDevice.process(pdfDocument.getPages().get_Item(index), fileOS);
                    fileOS.close();
                    imageList.add(ImageIO.read(file));
                    fileList.add(file);
                }
                //临时文件删除
                BufferedImage mergeImage = mergeImage(false, imageList);
                ImageIO.write(mergeImage, "png", new File(imgFilePath));
                long now = System.currentTimeMillis();
                System.out.println("convert pdf2jpg completed, elapsed :" + ((now - old) / 1000.0) + "秒");
                //删除临时文件
                for (File f : fileList) {
                    if (f.exists()) {
                        f.delete();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
        /**
         * 合并任数量的图片成一张图片
         *
         * @param isHorizontal true代表水平合并,fasle代表垂直合并
         * @param imgs         待合并的图片数组
         * @return
         * @throws IOException
         */
        public static BufferedImage mergeImage(boolean isHorizontal, List<BufferedImage> imgs) throws IOException {
            // 生成新图片
            BufferedImage destImage = null;
            // 计算新图片的长和高
            int allw = 0, allh = 0, allwMax = 0, allhMax = 0;
            // 获取总长、总宽、最长、最宽
            for (int i = 0; i < imgs.size(); i++) {
                BufferedImage img = imgs.get(i);
                allw += img.getWidth();
    
                if (imgs.size() != i + 1) {
                    allh += img.getHeight() + 5;
                } else {
                    allh += img.getHeight();
                }
    
    
                if (img.getWidth() > allwMax) {
                    allwMax = img.getWidth();
                }
                if (img.getHeight() > allhMax) {
                    allhMax = img.getHeight();
                }
            }
            // 创建新图片
            if (isHorizontal) {
                destImage = new BufferedImage(allw, allhMax, BufferedImage.TYPE_INT_RGB);
            } else {
                destImage = new BufferedImage(allwMax, allh, BufferedImage.TYPE_INT_RGB);
            }
            Graphics2D g2 = (Graphics2D) destImage.getGraphics();
            g2.setBackground(Color.LIGHT_GRAY);
            g2.clearRect(0, 0, allw, allh);
            g2.setPaint(Color.RED);
    
            // 合并所有子图片到新图片
            int wx = 0, wy = 0;
            for (int i = 0; i < imgs.size(); i++) {
                BufferedImage img = imgs.get(i);
                int w1 = img.getWidth();
                int h1 = img.getHeight();
                // 从图片中读取RGB
                int[] ImageArrayOne = new int[w1 * h1];
                // 逐行扫描图像中各个像素的RGB到数组中
                ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1);
                if (isHorizontal) {
                    // 水平方向合并
                    // 设置上半部分或左半部分的RGB
                    destImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1);
                } else {
                    // 垂直方向合并
                    // 设置上半部分或左半部分的RGB
                    destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1);
                }
                wx += w1;
                wy += h1 + 5;
            }
    
    
            return destImage;
        }
    
        /**
         * pfd转图片
         *
         * @param pdf     源文件全路径
         * @param outPath 转后的文件夹路径
         */
        public static void pdfToImage(String pdf, String outPath) {
            // 验证License
            if (!getLicense()) {
                return;
            }
    
            try {
                long old = System.currentTimeMillis();
                System.out.println("convert pdf2png begin");
                Document pdfDocument = new Document(pdf);
                //图片宽度:800
                //图片高度:100
                // 分辨率 960
                //Quality [0-100] 最大100
                //例: new JpegDevice(800, 1000, resolution, 90);
                Resolution resolution = new Resolution(960);
    //            JpegDevice jpegDevice = new JpegDevice(resolution);
                PngDevice pngDevice = new PngDevice(resolution);
                for (int index = 1; index <= pdfDocument.getPages().size(); index++) {
                    // 输出路径
                    File file = new File(outPath + "/" + index + ".png");
                    FileOutputStream fileOs = new FileOutputStream(file);
    //                jpegDevice.process(pdfDocument.getPages().get_Item(index), fileOs);
                    pngDevice.process(pdfDocument.getPages().get_Item(index), fileOs);
                    fileOs.close();
                }
    
                long now = System.currentTimeMillis();
                System.out.println("convert pdf2png completed, elapsed :" + ((now - old) / 1000.0) + "秒");
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
        /**
         * @param page      要添加水印的页面
         * @param imageFile 水印图片路径
         */
        public 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 水印文字
         */
        public static void AddTextWatermark(PdfPageBase page, String textWatermark) {
            Dimension2D dimension2D = new Dimension();
            dimension2D.setSize(page.getCanvas().getClientSize().getWidth() / 3, 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.getGray(), 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);
        }
    
        /**
         * @param sourceFile 需要重新重命名的图片路径
         * @param targetPath 重命名的图片路径保存地址
         */
        public static void fileCopyRightWay(String sourceFile, String targetPath) {
            try {
                //读取源地址文件的字节流
                FileInputStream in = new FileInputStream(sourceFile);
                FileOutputStream out = new FileOutputStream(targetPath);
                byte[] bs = new byte[1026];
                int count = 0;
                while ((count = in.read(bs, 0, bs.length)) != -1) {
                    //把读取到的字节流写入到目的地址的文件里面
                    out.write(bs, 0, count);
                }
                //刷新下输出流
                out.flush();
                // 关闭输入流和输出流
                out.close();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    
        /**
         * 添加水印
         *
         * @param filepath [文件路径]
         * @param data     [水印文字内容]
         */
        public static void addWatermark(String filepath, String data) {
    
            Document pdfDocument = new Document(filepath);
            TextStamp textStamp = new TextStamp(data);
            textStamp.setBackground(true);
            textStamp.setXIndent(100);
            textStamp.setYIndent(100);
            textStamp.setRotateAngle(50);
    
            textStamp.getTextState().setFont(FontRepository.findFont("Arial"));
            textStamp.getTextState().setFontSize(34.0F);
            textStamp.getTextState().setFontStyle(FontStyles.Italic);
    //        textStamp.getTextState().setForegroundColor(Color.getLightGray());
    
            TextStamp textStamp1 = new TextStamp(data);
            textStamp1.setBackground(true);
            textStamp1.setXIndent(300);//设置位置
            textStamp1.setYIndent(300);
            textStamp1.setRotateAngle(50);//设置旋转角度
            textStamp1.getTextState().setFont(FontRepository.findFont("Arial"));
            textStamp1.getTextState().setFontSize(34.0F);//设置字体大小
            textStamp1.getTextState().setFontStyle(FontStyles.Italic);
    //        textStamp1.getTextState().setForegroundColor(Color.LIGHT_GRAY);//设置字体颜色
    
            TextStamp textStamp2 = new TextStamp(data);
            textStamp2.setBackground(true);
            textStamp2.setXIndent(500);
            textStamp2.setYIndent(500);
            textStamp2.setRotateAngle(50);
            textStamp2.getTextState().setFont(FontRepository.findFont("Arial"));
            textStamp2.getTextState().setFontSize(34.0F);
            textStamp2.getTextState().setFontStyle(FontStyles.Italic);
    //        textStamp2.getTextState().setForegroundColor(Color.getLightGray());
    
    
            PageCollection pages = pdfDocument.getPages();
            int size = pages.size();
            for (int i = 1; i <= size; i++) {
                pages.get_Item(i).addStamp(textStamp);
                pages.get_Item(i).addStamp(textStamp1);
                pages.get_Item(i).addStamp(textStamp2);
            }
            pdfDocument.save(filepath);
        }
        public static void addWatermarkWYH(String filepath, String data) {
            Document pdfDocument = new Document(filepath);
            TextStamp textStamp = new TextStamp(data);
            //背景(好像没用)
            textStamp.setBackground(true);
            //x坐标  可以通过xy坐标来定义水印的具体位置
            textStamp.setXIndent(100);
            //y坐标
            textStamp.setYIndent(10);
            //通过以下属性控制水印的样式 字体 大小 颜色等
            //旋转角度
            textStamp.setRotateAngle(0);
            //字体类型
            textStamp.getTextState().setFont(FontRepository.findFont("Arial"));
            //字体大小
            textStamp.getTextState().setFontSize(20.0F);
            //字体样式
            textStamp.getTextState().setFontStyle(FontStyles.Italic);
            //字体颜色
            textStamp.getTextState().setForegroundColor(com.aspose.pdf.Color.fromRgb(Color.yellow));
    
            TextStamp textStamp1 = new TextStamp(data);
            textStamp1.setBackground(true);
            textStamp1.setXIndent(200);//设置位置
            textStamp1.setYIndent(10);
            textStamp1.setRotateAngle(0);//设置旋转角度
            textStamp1.getTextState().setFont(FontRepository.findFont("Arial"));
            textStamp1.getTextState().setFontSize(30.0F);//设置字体大小
            textStamp1.getTextState().setFontStyle(FontStyles.Italic);
            textStamp1.getTextState().setForegroundColor(com.aspose.pdf.Color.fromRgb(Color.green));
    
    
            TextStamp textStamp2 = new TextStamp(data);
            textStamp2.setBackground(true);
            textStamp2.setXIndent(300);
            textStamp2.setYIndent(10);
            textStamp2.setRotateAngle(0);
            textStamp2.getTextState().setFont(FontRepository.findFont("Arial"));
            textStamp2.getTextState().setFontSize(40.0F);
            textStamp2.getTextState().setFontStyle(FontStyles.Italic);
            textStamp2.getTextState().setForegroundColor(com.aspose.pdf.Color.fromRgb(Color.red));
            PageCollection pages = pdfDocument.getPages();
            System.out.println(pages);
            int size = pages.size();
            for (int i = 1; i <= size; i++) {
                //如果只想要一个水印 只添加一个即可
                pages.get_Item(i).addStamp(textStamp);
                pages.get_Item(i).addStamp(textStamp1);
                pages.get_Item(i).addStamp(textStamp2);
            }
            pdfDocument.save(filepath);
        }
    
        //word->pdf
        public static boolean docToPdf(String inPath, String outPath) {
            if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
                return false;
            }
            FileOutputStream os = null;
            try {
                long old = System.currentTimeMillis();
                File file = new File(outPath); // 新建一个空白pdf文档
                os = new FileOutputStream(file);
                Document doc = new Document(inPath); // Address是将要被转化的word文档
                doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
                // EPUB, XPS, SWF 相互转换
                long now = System.currentTimeMillis();
                System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }finally {
                if (os != null) {
                    try {
                        os.flush();
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return true;
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382
    • 383
    • 384
    • 385
    • 386
    • 387
    • 388
    • 389
    • 390
    • 391
    • 392
    • 393
    • 394
    • 395
    • 396
    • 397
    • 398
    • 399
    • 400
    • 401
    • 402
    • 403
    • 404
    • 405
    • 406
    • 407
    • 408
    • 409
    • 410
    • 411
    • 412
    • 413
    • 414
    • 415
    • 416
    • 417
    • 418
    • 419
    • 420
    • 421
    • 422
    • 423
    • 424
    • 425
    • 426
    • 427
    • 428
    • 429
    • 430
    • 431
    • 432
    • 433
    • 434
    • 435
    • 436
    • 437
    • 438
    • 439
    • 440
    • 441
    • 442
    • 443
    • 444
    • 445
    • 446
    • 447
  • 相关阅读:
    详解机器学习最优化算法
    LeetCode--580. 统计各专业学生人数
    【由浅入深_打牢基础】HOST头攻击
    自动驾驶 2D 单目\双目\多目视觉方法 一(Pseudo-LiDAR,Mono3D,FCOS3D,PSMNet)
    react-state hook
    【Scheme】Scheme 编程学习 (六) —— lambda 函数
    Pan-cancer image-based detection of clinically actionable genetic alternations
    房子装修有哪些注意事项要注意?
    累加出整个范围所有的数最少还需要几个数
    性能测试【第三篇】Jmeter的使用
  • 原文地址:https://blog.csdn.net/weixin_46713508/article/details/125502476