美文网首页
java pdf 添加水印

java pdf 添加水印

作者: 六层 | 来源:发表于2020-07-01 15:42 被阅读0次
maven
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
代码
public static void addWaterMark(String srcFile, String destFile, String text) throws Exception {
        // 待加水印的文件
        PdfReader reader = new PdfReader(srcFile);
        // 加完水印的文件
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));

        int total = reader.getNumberOfPages() + 1;
        PdfContentByte content;

        // 设置透明度
        PdfGState gs = new PdfGState();
        gs.setFillOpacity(0.3f);
        // 设置字体
        BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        // 循环对每页插入水印
        for (int i = 1; i < total; i++)
        {
            // 水印的起始
            content = stamper.getOverContent(i);
            content.setGState(gs);
            content.setFontAndSize(base, 50);
            // 开始
            content.beginText();
            // 设置颜色 默认为黑色
            content.setColorFill(BaseColor.BLACK);
            // 开始写入水印

            content.showTextAligned(Element.ALIGN_MIDDLE, text, 198,
                    221, 45);
            content.showTextAligned(Element.ALIGN_MIDDLE, text, 598,
                    221, 45);
            content.showTextAligned(Element.ALIGN_MIDDLE, text, 998,
                    221, 45);
            content.endText();
        }
        stamper.close();
    }

相关文章

网友评论

      本文标题:java pdf 添加水印

      本文链接:https://www.haomeiwen.com/subject/dlthqktx.html