最近有个需求需要给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水印"));
}
当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/
我有一大串格式化数据(例如JSON),我想使用Psychinruby同时保留格式转储到YAML。基本上,我希望JSON使用literalstyle出现在YAML中:---json:|{"page":1,"results":["item","another"],"total_pages":0}但是,当我使用YAML.dump时,它不使用文字样式。我得到这样的东西:---json:!"{\n\"page\":1,\n\"results\":[\n\"item\",\"another\"\n],\n\"total_pages\":0\n}\n"我如何告诉Psych以想要的样式转储标量?解
我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它
我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以
我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden
我需要一个表,其中行实际上是2行表,一个嵌套表是..我怎样才能在Prawn中做到这一点?也许我需要延期..但哪一个? 最佳答案 现在支持子表:Prawn::Document.generate("subtable.pdf")do|pdf|subtable=pdf.make_table([["sub"],["table"]])pdf.table([[subtable,"original"]])end 关于ruby-on-rails-PrawnPDF:Ineedtogeneratenested
对于作为String#tr参数的单引号字符串文字中反斜杠的转义状态,我觉得有些神秘。你能解释一下下面三个例子之间的对比吗?我特别不明白第二个。为了避免复杂化,我在这里使用了'd',在双引号中转义时不会改变含义("\d"="d")。'\\'.tr('\\','x')#=>"x"'\\'.tr('\\d','x')#=>"\\"'\\'.tr('\\\d','x')#=>"x" 最佳答案 在tr中转义tr的第一个参数非常类似于正则表达式中的括号字符分组。您可以在表达式的开头使用^来否定匹配(替换任何不匹配的内容)并使用例如a-f来匹配一
当谈到运行时自省(introspection)和动态代码生成时,我认为ruby没有任何竞争对手,可能除了一些lisp方言。前几天,我正在做一些代码练习来探索ruby的动态功能,我开始想知道如何向现有对象添加方法。以下是我能想到的3种方法:obj=Object.new#addamethoddirectlydefobj.new_method...end#addamethodindirectlywiththesingletonclassclass这只是冰山一角,因为我还没有探索instance_eval、module_eval和define_method的各种组合。是否有在线/离线资
我注意到类定义,如果我打开classMyClass,并在不覆盖的情况下添加一些东西我仍然得到了之前定义的原始方法。添加的新语句扩充了现有语句。但是对于方法定义,我仍然想要与类定义相同的行为,但是当我打开defmy_method时似乎,def中的现有语句和end被覆盖了,我需要重写一遍。那么有什么方法可以使方法定义的行为与定义相同,类似于super,但不一定是子类? 最佳答案 我想您正在寻找alias_method:classAalias_method:old_func,:funcdeffuncold_func#similartoca
我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司