简述

最近有个需求需要给pdf加文字水印,于是开始搜索大法,但是发现网络上的代码基本都是将字体文件直接放在jar包里面。个人强迫症发作(手动狗头),想要像poi一样直接加载系统字体,于是研究了一下午pdfbox的源代码,发现FontFileFinder类可以实现这个功能。废话不多说,直接上代码。

引入依赖

<!-- pdfbox-->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<!-- 提供 HttpServlet 相关类 -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
</dependency>

新增水印配置类

@Data
@NoArgsConstructor
public class PdfWatermarkProperties { public PdfWatermarkProperties(String content) {
this.content = content;
} /**
* 文字水印内容
*/
private String content = ""; /**
* ttf类型字体文件. 为null则使用默认字体
*/
private File fontFile; private float fontSize = 13; /**
* cmyk颜色.参数值范围为 0-255
*/
private int[] color = {0, 0, 0, 210}; /**
* 透明度
*/
private float transparency = 0.3f; /**
* 倾斜度. 默认30°
*/
private double rotate = 0.3; /**
* 初始添加水印的点位
*/
private int x = -10;
private int y = 10; /**
* 内容区域的宽高.即单个水印范围的大小
*/
private int width = 200;
private int height = 200; }

工具类

import org.apache.fontbox.ttf.TTFParser;
import org.apache.fontbox.ttf.TrueTypeCollection;
import org.apache.fontbox.ttf.TrueTypeFont;
import org.apache.fontbox.util.autodetect.FontFileFinder;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.util.Matrix; import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URI;
import java.net.URLEncoder; public class PdfUtil { private static final String DEFAULT_TTF_FILENAME = "simsun.ttf";
private static final String DEFAULT_TTC_FILENAME = "simsun.ttc";
private static final String DEFAULT_FONT_NAME = "SimSun";
private static final TrueTypeFont DEFAULT_FONT; static {
DEFAULT_FONT = loadSystemFont();
} /**
* 加载系统字体,提供默认字体
*
* @return
*/
private synchronized static TrueTypeFont loadSystemFont() {
//load 操作系统的默认字体. 宋体
FontFileFinder fontFileFinder = new FontFileFinder();
for (URI uri : fontFileFinder.find()) {
try {
final String filePath = uri.getPath();
if (filePath.endsWith(DEFAULT_TTF_FILENAME)) {
return new TTFParser(false).parse(filePath);
} else if (filePath.endsWith(DEFAULT_TTC_FILENAME)) {
TrueTypeCollection trueTypeCollection = new TrueTypeCollection(new FileInputStream(filePath));
final TrueTypeFont font = trueTypeCollection.getFontByName(DEFAULT_FONT_NAME);
//复制完之后关闭ttc
trueTypeCollection.close();
return font;
}
} catch (Exception e) {
throw new RuntimeException("加载操作系统字体失败", e);
}
} return null;
} /**
* 添加文本水印
* * 使用内嵌字体模式,pdf文件大小会增加1MB左右
*
* @param sourceFile 需要加水印的文件
* @param descFile 目标存储路径
* @param props 水印配置
* @throws IOException
*/
public static void addTextWatermark(File sourceFile, String descFile, PdfWatermarkProperties props) throws IOException {
// 加载PDF文件
PDDocument document = PDDocument.load(sourceFile);
addTextToDocument(document, props);
document.save(descFile);
document.close();
} /**
* 添加文本水印
*
* @param inputStream 需要加水印的文件流
* @param outputStream 加水印之后的流。执行完之后会关闭outputStream, 建议使用{@link BufferedOutputStream}
* @param props 水印配置
* @throws IOException
*/
public static void addTextWatermark(InputStream inputStream, OutputStream outputStream, PdfWatermarkProperties props) throws IOException {
// 加载PDF文件
PDDocument document = PDDocument.load(inputStream);
addTextToDocument(document, props);
document.save(outputStream);
} /**
* 处理PDDocument,添加文本水印
*
* @param document
* @param props
* @throws IOException
*/
public static void addTextToDocument(PDDocument document, PdfWatermarkProperties props) throws IOException {
document.setAllSecurityToBeRemoved(true); // 遍历PDF文件,在每一页加上水印
for (PDPage page : document.getPages()) {
PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true); // 加载水印字体
if (DEFAULT_FONT == null) {
throw new RuntimeException(String.format("未提供默认字体.请安装字体文件%s或%s", DEFAULT_TTF_FILENAME, DEFAULT_TTC_FILENAME));
} PDFont font;
if (props.getFontFile() != null) {
font = PDType0Font.load(document, props.getFontFile());
} else {
//当TrueTypeFont为字体集合时, embedSubSet 需要设置为true, 嵌入其子集
font = PDType0Font.load(document, DEFAULT_FONT, true);
} PDExtendedGraphicsState r = new PDExtendedGraphicsState(); // 设置透明度
r.setNonStrokingAlphaConstant(props.getTransparency());
r.setAlphaSourceFlag(true);
stream.setGraphicsStateParameters(r); // 设置水印字体颜色
final int[] color = props.getColor();
stream.setNonStrokingColor(color[0], color[1], color[2], color[3]);
stream.beginText();
stream.setFont(font, props.getFontSize()); // 获取PDF页面大小
float pageHeight = page.getMediaBox().getHeight();
float pageWidth = page.getMediaBox().getWidth(); // 根据纸张大小添加水印,30度倾斜
for (int h = props.getY(); h < pageHeight; h = h + props.getHeight()) {
for (int w = props.getX(); w < pageWidth; w = w + props.getWidth()) {
stream.setTextMatrix(Matrix.getRotateInstance(props.getRotate(), w, h));
stream.showText(props.getContent());
}
} // 结束渲染,关闭流
stream.endText();
stream.restoreGraphicsState();
stream.close();
}
} /**
* 设置pdf文件输出的响应头
*
* @param response web response
* @param fileName 文件名(不含扩展名)
*/
public static void setPdfResponseHeader(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
response.setContentType("application/pdf");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".pdf");
} }

测试

@GetMapping("/t")
public void getFile(HttpServletResponse response) throws IOException {
PdfUtil.setPdfResponseHeader(response, "watermark");
final ServletOutputStream out = response.getOutputStream();
PdfUtil.addTextWatermark(new FileInputStream("D:/测试文件.pdf"), out, new PdfWatermarkProperties("测试pdf水印"));
}

基于pdfbox实现的pdf添加文字水印工具的更多相关文章

  1. PDF怎么添加文字水印与图片水印

    现在是个知识分享时代,但不可避免的盗版也无处不在,不知道在我们大家身边有没有遇到过这样的情况:自己煞费苦心制作的PDF文档不知道在什么时候就会被别人给盗用了,那么如何才能尽量避免这个问题呢?今天带大家 ...

  2. 「Python实用秘技04」为pdf文件批量添加文字水印

    本文完整示例代码及文件已上传至我的Github仓库https://github.com/CNFeffery/PythonPracticalSkills 这是我的系列文章「Python实用秘技」的第4期 ...

  3. javacpp-opencv图像处理之1:实时视频添加文字水印并截取视频图像保存成图片,实现文字水印的字体、位置、大小、粗度、翻转、平滑等操作

    欢迎大家积极开心的加入讨论群 群号:371249677 (点击这里进群) javaCV图像处理系列: javaCV图像处理之1:实时视频添加文字水印并截取视频图像保存成图片,实现文字水印的字体.位置. ...

  4. java -PDF添加文本水印与图片水印

    java pdf添加水印文本及图片文本 PDF文件添加文本水印: private static int interval = 30; public static void waterMark(Stri ...

  5. php 图片添加文字水印 以及 图片合成(微信快码传播)

    1.图片添加文字水印: $bigImgPath = 'backgroud.png'; $img = imagecreatefromstring(file_get_contents($bigImgPat ...

  6. 利用php给图片添加文字水印--面向对象与面向过程俩种方法的实现

    1: 面向过程的编写方法 //指定图片路径 $src = '001.png'; //获取图片信息 $info = getimagesize($src); //获取图片扩展名 $type = image ...

  7. Swift - 给图片添加文字水印(图片上写文字,并可设置位置和样式)

    想要给图片添加文字水印或者注释,我们需要实现在UIImage上写字的功能. 1,效果图如下: (在图片左上角和右下角都添加了文字.) 2,为方便使用,我们通过扩展UIImage类来实现添加水印功能 ( ...

  8. JS为网页添加文字水印【原创】

    最近需要实现为网页添加水印的功能,由于水印的信息是动态生成的,而百度谷歌上的方法往往都是为网页添加图片水印或为图片添加水印,而为网页添加文字水印相关资料较少,于是就自己动手写了这个代码. 通常加动态水 ...

  9. C#图片添加文字水印

    /// <summary> /// 给图片添加文字水印 /// </summary> /// <param name="img">图片</ ...

  10. php图片添加文字水印方法汇总

    方法一: <?php header("content-type:text/html;charset=utf-8"); //指定图片路径 $src = "img/a. ...

随机推荐

  1. 【Azure 应用服务】Azure SignalR 是否可以同时支持近十万人在线互动

    什么是 Azure SignalR 服务? Azure SignalR Service 简化了通过 HTTP 向应用程序添加实时 Web 功能的过程. 这种实时功能允许服务将内容更新推送到连接的客户端 ...

  2. C# 多线程(17):小总结

    前言 本篇内容是小总结和过渡,看完这篇后,就要开始继续学习 C# 多线程中的知识点啦~. 前面,经过 16 篇的学习,我们学习了多线程.锁.线程池.任务.同步.异步等知识,还没有使用到 async.a ...

  3. VC+MFC button获取+list复制+获取+页面转换+登录与数据库账户,密码进行对比 +基础知识

    1 // DlgExec.cpp : 实现文件 2 // 3 4 #include "stdafx.h" 5 #include "Self.h" 6 #incl ...

  4. win10图标异常显示空白,WiFi图标消失等情况解决方案

    出现WiFi图标异常不显示,但是网络却正常,以下为解决方案: Win + R 快捷键调出运行框,输入%USERPROFILE%\AppData\Local,找到IconCache.db文件并删除,之后 ...

  5. 获取一段时间内,以月/季度为单位,第N天在各个月/季度是几几年几月几号

    /** * 获取一段时间内(可跨年),以季度为单位,第N天在各个季度是几月几号 * @param $sTime 时间戳 * @param $eTime 时间戳 * @param $number 第N天 ...

  6. TLSR8258方案开发之BLE协议接口代码解析

    一 前言 这里的代码是在原厂基础上修改了不少.虽然代码复杂了不少,但是逻辑也清晰了不少. 二  广播协议 想要熟悉并修改ble的广播协议和内容,请查阅结构体: static const attribu ...

  7. Spring之事务传播属性

    在Spring中,我们可以从单调烦闷的事务管理代码中解脱出来,通过声明式方式灵活地进行事务的管理,提高开发效率和质量. 在使用Spring时,大部分会用到他的声明式事务,简单的在配置文件中进行一些规则 ...

  8. MediaCodec硬解流程

    一 MediaCodec概述 MediaCodec是Android 4.1(api 16)版本引入的低层编解码接口,同时支持音视频的编码和解码.通常与MediaExtractor.MediaMuxer ...

  9. django(cookie与session、中间件、auth模块)

    一 cookie与session 1 发展史及简介 """ 发展史 1.网站都没有保存用户功能的需求,所有用户访问返回的结果都是一样的 eg:新闻.博客.文章 2.出现了 ...

  10. linux下永久添加静态路由-不同

    linux下永久添加静态路由-不同 添加路由的命令: 1,route add route add -net 192.56.76.0 netmask 255.255.255.0 dev eth0#添加一 ...