文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Java PDF加水印

2023-10-20 17:41

关注

自适应文字长度水印

1.效果图

2.代码

2.1.pom

                            com.itextpdf            itextpdf            5.5.13.1                                    com.itextpdf            itext-asian            5.2.0        

2.2.水印工具类(自动调节文字个数)

import cn.hutool.core.date.DateUtil;import com.itextpdf.text.Element;import com.itextpdf.text.Rectangle;import com.itextpdf.text.pdf.*;import javax.swing.*;import java.awt.*;import java.io.*;import java.net.URL;import java.nio.file.Files;import java.nio.file.Paths;import static com.shinkeer.common.utils.SecurityUtils.getUsername;public class PdfWatermarkUtil {    public static void main(String[] args) {        PdfWatermarkLocal("C:\\Users\\Pictures\\pdf水印测试.pdf", "C:\\Users\\Pictures\\pdf(加).pdf",                "一二三四五六七八九十十九八七六五四三二一");    }    public static void main2(String[] args) throws Exception {        File file = new File("C:\\Users\\Pictures\\pdf水印测试.pdf");        InputStream inputStream = file.toURL().openStream();        InputStream stream = PdfWatermarkTool.addPdfWatermark(inputStream, "这是水印" + DateUtil.now(), 10, 30, 50);        writeToLocal("C:\\Users\\Pictures\\AAA" + System.currentTimeMillis() + ".pdf", stream);    }        private static void writeToLocal(String destination, InputStream input) throws IOException {        int index;        byte[] bytes = new byte[1024];        FileOutputStream downloadFile = new FileOutputStream(destination);        while ((index = input.read(bytes)) != -1) {            downloadFile.write(bytes, 0, index);            downloadFile.flush();        }        downloadFile.close();        input.close();    }        public static void PdfWatermarkLocal(String inputFile, String outputFile, String waterMarkName) {        try {            // 切记这里的参数是文件的路径 ,路径必须是双斜杠的如F:\\test.pdf,不能是F:/test.pdf 或者F:\test.pdf            PdfReader reader = new PdfReader(inputFile);            PdfStamper stamper = new PdfStamper(reader, Files.newOutputStream(Paths.get(outputFile)));            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);            PdfGState gs = new PdfGState();            gs.setFillOpacity(0.2f);//改透明度            gs.setStrokeOpacity(0.4f);            int total = reader.getNumberOfPages() + 1;            JLabel label = new JLabel();            label.setText(waterMarkName);            PdfContentByte under;            // 可添加多个水印            Rectangle pageRect = null;            label.setText(waterMarkName);            for (int i = 1; i < total; i++) {                pageRect = reader.getPageSizeWithRotation(i);                int width1 = (int) pageRect.getWidth();                int height1 = (int) pageRect.getHeight();                int fontSize = (width1 + height1) / 80;                // 间隔距离(参数可调节)                int interval = fontSize * 2;                // 文字占用的宽度                int xWidth = getStrWidth(waterMarkName, fontSize);                // x,y可以绘制的数量,多加一个补充空白                int xCanNum = width1 / xWidth + 1;                int yCanNum = height1 / fontSize + 1;                // 在内容上方加水印                under = stamper.getOverContent(i);                // 在内容下方加水印                //under = stamper.getUnderContent(i);                under.saveState();                under.setGState(gs);                under.beginText();                //水印字体和大小                under.setFontAndSize(base, fontSize);                // 水印文字成30度角倾斜                for (int ii = 1; ii <= yCanNum; ii++) {                    int y = fontSize * ii + interval * ii;                    for (int jj = 0; jj < xCanNum; jj++) {                        int x = xWidth * jj + interval * jj;                        under.showTextAligned(Element.ALIGN_LEFT    , waterMarkName, x, y - (fontSize + interval) * jj, 30);                    }                }                // 添加水印文字                under.endText();            }            stamper.close();            reader.close();        } catch (Exception e) {            e.printStackTrace();        }    }        public static OutputStream PdfWatermarkOut(InputStream inputStream, String waterMarkName) {        try {            PdfReader reader = new PdfReader(inputStream);            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();            PdfStamper stamper = new PdfStamper(reader, outputStream);            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);            PdfGState gs = new PdfGState();            gs.setFillOpacity(0.2f);//改透明度            gs.setStrokeOpacity(0.4f);            int total = reader.getNumberOfPages() + 1;            JLabel label = new JLabel();            label.setText(waterMarkName);            PdfContentByte under;            // 可添加多个水印            Rectangle pageRect = null;            label.setText(waterMarkName);            for (int i = 1; i < total; i++) {                pageRect = reader.getPageSizeWithRotation(i);                int width1 = (int) pageRect.getWidth();                int height1 = (int) pageRect.getHeight();                int fontSize = (width1 + height1) / 80;                // 间隔距离(参数可调节)                int interval = fontSize * 2;                // 文字占用的宽度                int xWidth = getStrWidth(waterMarkName, fontSize);                // x,y可以绘制的数量,多加一个补充空白                int xCanNum = width1 / xWidth + 1;                int yCanNum = height1 / fontSize + 1;                // 在内容上方加水印                under = stamper.getOverContent(i);                // 在内容下方加水印                //under = stamper.getUnderContent(i);                under.saveState();                under.setGState(gs);                under.beginText();                //水印字体和大小                under.setFontAndSize(base, fontSize);                // 水印文字成30度角倾斜                for (int ii = 1; ii <= yCanNum; ii++) {                    int y = fontSize * ii + interval * ii;                    for (int jj = 0; jj < xCanNum; jj++) {                        int x = xWidth * jj + interval * jj;                        under.showTextAligned(Element.ALIGN_LEFT    , waterMarkName, x, y - (fontSize + interval) * jj, 30);                    }                }                // 添加水印文字                under.endText();            }            stamper.close();            reader.close();            return outputStream;        } catch (Exception e) {            throw new RuntimeException(e);        }    }        public static InputStream PdfWatermarkInt(InputStream inputStream, String waterMarkName) {        try {            PdfReader reader = new PdfReader(inputStream);            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();            PdfStamper stamper = new PdfStamper(reader, outputStream);            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);            PdfGState gs = new PdfGState();            gs.setFillOpacity(0.2f);//改透明度            gs.setStrokeOpacity(0.4f);            int total = reader.getNumberOfPages() + 1;            JLabel label = new JLabel();            label.setText(waterMarkName);            PdfContentByte under;            // 可添加多个水印            Rectangle pageRect = null;            label.setText(waterMarkName);            for (int i = 1; i < total; i++) {                pageRect = reader.getPageSizeWithRotation(i);                int width1 = (int) pageRect.getWidth();                int height1 = (int) pageRect.getHeight();                int fontSize = (width1 + height1) / 80;                // 间隔距离(参数可调节)                int interval = fontSize * 2;                // 文字占用的宽度                int xWidth = getStrWidth(waterMarkName, fontSize);                // x,y可以绘制的数量,多加一个补充空白                int xCanNum = width1 / xWidth + 1;                int yCanNum = height1 / fontSize + 1;                // 在内容上方加水印                under = stamper.getOverContent(i);                // 在内容下方加水印                //under = stamper.getUnderContent(i);                under.saveState();                under.setGState(gs);                under.beginText();                //水印字体和大小                under.setFontAndSize(base, fontSize);                // 水印文字成30度角倾斜                for (int ii = 1; ii <= yCanNum; ii++) {                    int y = fontSize * ii + interval * ii;                    for (int jj = 0; jj < xCanNum; jj++) {                        int x = xWidth * jj + interval * jj;                        under.showTextAligned(Element.ALIGN_LEFT    , waterMarkName, x, y - (fontSize + interval) * jj, 30);                    }                }                // 添加水印文字                under.endText();            }            stamper.close();            reader.close();            return new ByteArrayInputStream(outputStream.toByteArray());        } catch (Exception e) {            throw new RuntimeException(e);        }    }        public static int getStrWidth(String str, int fontSize) {        char[] chars = str.toCharArray();        int fontSize2 = fontSize / 2;        int width = 0;        for (char c : chars) {            int len = String.valueOf(c).getBytes().length;            // 汉字为3,其余1            // 可能还有一些特殊字符占用2等等,统统计为汉字            if (len != 1) {                width += fontSize;            } else {                width += fontSize2;            }        }        return width == 0 ? 1 : width;    }}

水印工具类(写死文字大小个数)

import cn.hutool.core.date.DateUtil;import com.itextpdf.text.Element;import com.itextpdf.text.Rectangle;import com.itextpdf.text.pdf.*;import javax.swing.*;import java.awt.*;import java.io.*;import java.net.URL;import java.nio.file.Files;import java.nio.file.Paths;import static com.shinkeer.common.utils.SecurityUtils.getUsername;public class PdfWatermarkUtil {    public static void main(String[] args) {        PdfWatermarkLocal("D:\\AAA.pdf", "D:\\BBB.pdf", "这是水印");    }    public static void main2(String[] args) throws Exception {        File file = new File("D:\\AAA.pdf");        InputStream inputStream = file.toURL().openStream();        InputStream stream = PdfWatermarkTool.addPdfWatermark(inputStream, "这是水印" + DateUtil.now(), 10, 30, 50);        writeToLocal("D:\\AAA" + System.currentTimeMillis() + ".pdf", stream);    }        private static void writeToLocal(String destination, InputStream input) throws IOException {        int index;        byte[] bytes = new byte[1024];        FileOutputStream downloadFile = new FileOutputStream(destination);        while ((index = input.read(bytes)) != -1) {            downloadFile.write(bytes, 0, index);            downloadFile.flush();        }        downloadFile.close();        input.close();    }        public static void PdfWatermarkLocal(String inputFile, String outputFile, String waterMarkName) {        try {            // 水印的高和宽(参数可调节)            int textH = 75;            int textW = 170;            // 间隔距离(参数可调节)            int interval = 30;            // 切记这里的参数是文件的路径 ,路径必须是双斜杠的如F:\\test.pdf,不能是F:/test.pdf 或者F:\test.pdf            PdfReader reader = new PdfReader(inputFile);            PdfStamper stamper = new PdfStamper(reader, Files.newOutputStream(Paths.get(outputFile)));            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);            PdfGState gs = new PdfGState();            gs.setFillOpacity(0.2f);//改透明度            gs.setStrokeOpacity(0.4f);            int total = reader.getNumberOfPages() + 1;            JLabel label = new JLabel();            label.setText(waterMarkName);            PdfContentByte under;            // 可添加多个水印            Rectangle pageRect = null;            FontMetrics metrics;            label.setText(waterMarkName);            metrics = label.getFontMetrics(label.getFont());            for (int i = 1; i < total; i++) {                pageRect = reader.getPageSizeWithRotation(i);                // 在内容上方加水印                under = stamper.getOverContent(i);                // 在内容下方加水印                //under = stamper.getUnderContent(i);                under.saveState();                under.setGState(gs);                under.beginText();                under.setFontAndSize(base, 20);                // 水印文字成30度角倾斜                for (int height = interval + textH; height < pageRect.getHeight();                     height = height + textH * 3) {                    for (int width = interval + textW; width < pageRect.getWidth() + textW;                         width = width + textW * 2) {                        under.showTextAligned(Element.ALIGN_LEFT    , waterMarkName, width - textW,    height - textH, 30);                    }                }                // 添加水印文字                under.endText();            }            stamper.close();            reader.close();        } catch (Exception e) {            e.printStackTrace();        }    }        public static OutputStream PdfWatermarkOut(InputStream inputStream, String waterMarkName) {        try {            // 水印的高和宽(参数可调节)            int textH = 75;            int textW = 170;            // 间隔距离(参数可调节)            int interval = 30;            PdfReader reader = new PdfReader(inputStream);            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();            PdfStamper stamper = new PdfStamper(reader, outputStream);            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);            PdfGState gs = new PdfGState();            gs.setFillOpacity(0.2f);//改透明度            gs.setStrokeOpacity(0.4f);            int total = reader.getNumberOfPages() + 1;            JLabel label = new JLabel();            label.setText(waterMarkName);            PdfContentByte under;            // 可添加多个水印            Rectangle pageRect = null;            FontMetrics metrics;            label.setText(waterMarkName);            metrics = label.getFontMetrics(label.getFont());            for (int i = 1; i < total; i++) {                pageRect = reader.getPageSizeWithRotation(i);                // 在内容上方加水印                under = stamper.getOverContent(i);                // 在内容下方加水印                //under = stamper.getUnderContent(i);                under.saveState();                under.setGState(gs);                under.beginText();                under.setFontAndSize(base, 20);                // 水印文字成30度角倾斜                for (int height = interval + textH; height < pageRect.getHeight();                     height = height + textH * 3) {                    for (int width = interval + textW; width < pageRect.getWidth() + textW;                         width = width + textW * 2) {                        under.showTextAligned(Element.ALIGN_LEFT    , waterMarkName, width - textW,    height - textH, 30);                    }                }                // 添加水印文字                under.endText();            }            stamper.close();            reader.close();            return outputStream;        } catch (Exception e) {            throw new RuntimeException(e);        }    }        public static InputStream PdfWatermarkInt(InputStream inputStream, String waterMarkName) {        try {            // 水印的高和宽(参数可调节)            int textH = 75;            int textW = 170;            // 间隔距离(参数可调节)            int interval = 30;            PdfReader reader = new PdfReader(inputStream);            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();            PdfStamper stamper = new PdfStamper(reader, outputStream);            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);            PdfGState gs = new PdfGState();            gs.setFillOpacity(0.2f);//改透明度            gs.setStrokeOpacity(0.4f);            int total = reader.getNumberOfPages() + 1;            JLabel label = new JLabel();            label.setText(waterMarkName);            PdfContentByte under;            // 可添加多个水印            Rectangle pageRect = null;            FontMetrics metrics;            label.setText(waterMarkName);            metrics = label.getFontMetrics(label.getFont());            for (int i = 1; i < total; i++) {                pageRect = reader.getPageSizeWithRotation(i);                // 在内容上方加水印                under = stamper.getOverContent(i);                // 在内容下方加水印                //under = stamper.getUnderContent(i);                under.saveState();                under.setGState(gs);                under.beginText();                under.setFontAndSize(base, 20);                // 水印文字成30度角倾斜                for (int height = interval + textH; height < pageRect.getHeight();                     height = height + textH * 3) {                    for (int width = interval + textW; width < pageRect.getWidth() + textW;                         width = width + textW * 2) {                        under.showTextAligned(Element.ALIGN_LEFT    , waterMarkName, width - textW,    height - textH, 30);                    }                }                // 添加水印文字                under.endText();            }            stamper.close();            reader.close();            return new ByteArrayInputStream(outputStream.toByteArray());        } catch (Exception e) {            throw new RuntimeException(e);        }    }}

来源地址:https://blog.csdn.net/Ying_ph/article/details/131800711

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯