Java项目使用itextpdf给pdf文件添加水印

1. 添加pom依赖pom.xml


   com.itextpdf
   itextpdf
   5.5.13


   com.itextpdf
   itext-asian
   5.2.0

itextpdf 可以兼容中文

2. 创建工具类WatermarkUtils.java

public class WaterMarkUtils {
     public static OutputStream addWaterMark(byte[] bytes, OutputStream outputStream, String text, int textWidth, int textHeight,
                                                   String imgFile, int imgWidth, int imgHeight) throws IOException, DocumentException {
        // 待加水印的文件
        PdfReader reader = new PdfReader(bytes);

        // 加完水印的文件
        PdfStamper stamper = new PdfStamper(reader, outputStream);

        // 设置字体
        BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); // 华文宋体

        //BaseFont font = BaseFont.createFont("C:\\Windows\\Fonts\\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); // 标准黑体

        // 水印透明度
        PdfGState gs = new PdfGState();
        gs.setFillOpacity(0.5f);
        gs.setStrokeOpacity(0.5f);

        // PDF总页数
        int total = reader.getNumberOfPages() + 1;

        // 循环对每页插入水印
        PdfContentByte content;
        for (int i = 1; i < total; i++) {

            // 水印在之前文本之上
            content = stamper.getOverContent(i);

            // 透明度
            content.setGState(gs);

            // 图片水印
            if (imgFile != null) {

                Image image = null;
                if (imgFile != null) {

                    image = Image.getInstance(imgFile);
                    image.setAbsolutePosition(imgWidth, imgHeight);

                    // 设置图片的显示大小
                    image.scaleToFit(100, 125);
                }

                content.addImage(image);
            }

            // 文字水印
            if (text != null) {

                content.beginText();

                // 设置颜色 默认为蓝色
                content.setColorFill(new BaseColor(204, 204, 204));
                //content.setColorFill(Color.BLUE);

                // 设置字体及字号
                content.setFontAndSize(font, 25);

                // 设置起始位置
                content.setTextMatrix(textWidth, textHeight);

                // 字符间距
                content.setCharacterSpacing(2);

                // 中间水印
                content.showTextAligned(Element.ALIGN_LEFT, text, textWidth, textHeight, 45);

                // 底部水印
//                for (int k = 0; k < text.length(); k++) {
//                    // 距离底边的距离
//                    content.setTextRise(10);
//
//                    // 将char转成字符串
//                    content.showText(String.valueOf(text.charAt(k)));
//                }

                content.endText();
            }
        }

        stamper.close();
        reader.close();
        return outputStream;
    }
}

3. 从URL获取文件二进制数据HttpRequestUtils.java

public class HttpRequestUtils {
     /**
     * 发送get请求 返回byte
     * @param url    路径
     * @return
     */
    public static byte[] httpGetFile(String url){
        //get请求返回结果
        byte[] byteResult = null;
        try {

            CloseableHttpClient client = HttpClients.createDefault();
            //发送get请求
            HttpGet request = new HttpGet(url);
            CloseableHttpResponse response = client.execute(request);
            try {
                /**请求发送成功,并得到响应**/
                if (response.getStatusLine().getStatusCode() == 200) {
                    byteResult = EntityUtils.toByteArray(response.getEntity());
                } else {
                    logger.error("get请求提交失败:" + url);
                }
            } finally {
                response.close();
            }

        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        }
        return byteResult;
    }
}

4. 给文件加水印实例

@RestController
@ResponseBody
@RequestMapping(value = "/api/demo")
public class DemoController {
    @GetMapping("/addWaterPdf")
    public ResponseEntity addWaterPdf(String url) throws Exception{
        // url中获取文件流
        byte[] buffer = HttpRequestUtils.httpGetFile(url);
        if (Objects.isNull(buffer) || buffer.length == 0) {
            throw new RuntimeException("文件不存在");
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// 输出流实例
        String waterText = "这是一个水印";
        WatermarkUtils.addWaterMark(buffer, baos, waterText,20, 30, null, 400, 500);
        HttpHeaders headers = new HttpHeaders();
        // header只支持ASCII,需要把中文通过ISO-8859-1重新编码
        String fileName = new String("水印文件.pdf".getBytes("utf-8"), "iso-8859-1");
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity(baos.toByteArray(), headers, HttpStatus.OK);
    }
}

你可能感兴趣的:(Java项目使用itextpdf给pdf文件添加水印)