如何给PDF文件添加文字水印?

在最近一次自己捣鼓中,发现给PDF添加文字水印并不方便,有的说要下载Adobe的软件,有的在线pdf添加水印的网站,试过之后发现只能添加一个水印文字,并不能像我希望的那样能够全屏铺满,然后在搜索结果中发现了能够用itextpdf这个库用代码的方式给PDF添加水印,但是当中过程也是曲折,特此记录一下,并说明当中的坑。

这里直接贴上java代码:

public class PDFWaterMark {
    private static int interval = -5;

    /**
     * 添加文字水印
     * @param inputFile 文件源地址
     * @param outputFile 文件输出地址
     * @param waterMarkName 水印文字
     */
    public static void waterMark(String inputFile,
                                 String outputFile, String waterMarkName) {
        try {
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
                    outputFile));
            //这里获取一个默认的BaseFont
            BaseFont base = BaseFont.createFont();

            Rectangle pageRect;
            PdfGState gs = new PdfGState();
            //设置文字透明度
            gs.setFillOpacity(0.2f);
            gs.setStrokeOpacity(0.2f);
            //获取pdf总页数
            int total = reader.getNumberOfPages() + 1;

            JLabel label = new JLabel();
            FontMetrics metrics;
            int textH;
            int textW;
            label.setText(waterMarkName);
            metrics = label.getFontMetrics(label.getFont());
            //得到文字的宽高
            textH = metrics.getHeight();
            textW = metrics.stringWidth(label.getText());

            PdfContentByte under;
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                //得到一个覆盖在上层的水印文字
                under = stamper.getOverContent(i);
                under.saveState();
                under.setGState(gs);
                under.beginText();
                //设置水印文字颜色
                under.setColorFill(BaseColor.LIGHT_GRAY);
                //设置水印文字和大小
                under.setFontAndSize(base, 30);

                //这个position主要是为了在换行加水印时能往右偏移起始坐标
                int position = 0;
                for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 8) {
                    for (int width = interval + textW + position * 50; width < pageRect.getWidth() + textW; width = width + textW * 3) {
                        //添加水印文字,水印文字成30度角倾斜
                        under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW , height - textH, 30);
                    }
                    position++;
                }
                // 添加水印文字
                under.endText();
            }
            //一定不要忘记关闭流
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String fileIn = "你电脑中的文件源路径/XXX.pdf";
        String fileOut = "你想保存的文件源路径/outfile.pdf";
        waterMark(fileIn, fileOut, "testword");
    }
}

代码中已经添加了较为详细的注释,首先要说明的是这个代码现在目前只能添加英文水印,并不能添加中文水印,因为在实现过程中发现按照网上的写法,BaseFont会报错

"STSong-Light' with 'UniGB-UCS2-H' is not recognized"

因为我没用到itextasian.jar,所以我没有按照他们的解决方式去解决,大家如有需要,可以自己尝试,目前代码可以正常运行,亲测有效,用到的itextpdf下载地址

发布了87 篇原创文章 · 获赞 161 · 访问量 87万+

猜你喜欢

转载自blog.csdn.net/woshizisezise/article/details/87706787