网上很多ttf转xml的文章,不多说
但是字体配置一节 是在
把
另外:
如果不报错,还是乱码,那么,配置未生效
./
72
72
// svg文件转成PDF
public static void convert2Pdf(File svg, File pdf) {
OutputStream outs = null;
InputStream ins = null;
try {
File file = ResourceUtils.getFile("classpath:fop.xml");
DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
cfg = cfgBuilder.buildFromFile(file);
outs = new BufferedOutputStream(new FileOutputStream(pdf));
ins = new FileInputStream(svg);
PDFTranscoder transcoder = new PDFTranscoder();
transcoder.configure(cfg); //配置.. 这里只是示例,不用每次都读...
TranscoderInput input = new TranscoderInput(ins);
TranscoderOutput output = new TranscoderOutput(outs);
transcoder.transcode(input, output);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ins.close();
outs.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
彩蛋: 简化配置
./
72
72
时隔一年... 把字体配置到数据库的方式一并放上来. 由于是定制项目,fop代码被我修改了不少,比如不支持svg中特殊字符,透明背景, cmyk单黑问题.
项目是一个印刷品在线编辑. 浏览器读取模板,在canvas中编辑排版,导出svg到后台,用fop转pdf这么个流程.前端用的fabricjs
------------------------------------------
fop配置文件中字体配置一项放进数据库.
1. 读取数据库配置到Configuration
@PostConstruct //必须在系统初始化,或者操作fop之前做
public void init() {
try {
File file = ResourceUtils.getFile("classpath:fop.xml");
log.debug("fop配置文件" + file.getAbsolutePath() + " , " + file.exists());
DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
String generateFontXML = printingFontsService.generateFontXML(); //这里是读取数据库生成xml节点
String conf = FileUtil.readString(file, "UTF-8");
String source = StrUtil.format(conf, generateFontXML );
InputStream confStream = new StringInputStream(source, "UTF-8");
cfg = cfgBuilder.build(confStream );
FopFactoryBuilder fopFactoryBuilder = new FopFactoryBuilder(new File(".").toURI()).setConfiguration(cfg);
fac = fopFactoryBuilder.build();
log.debug("svgUtil inited");
} catch (Exception e) {
e.printStackTrace();
}
}
2. 读取数据库 代码
public String generateFontXML() throws Exception {
List allEntitys = this.getAllEntitys();
StringBuilder sb = new StringBuilder();
for (PrintingFonts f : allEntitys) {
String fontname = f.getFontname();
String md5 = EncryptUtil.MD5(fontname);
// 注意,这里的 md5值是名称,实际操作下,发现有些中文,英文字体,自身有空格时,不生效.SVG属性中同样用这个md5作为font-family的值
sb.append("\n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
"\n");
}
return sb.toString();
}
3. fop.xml
./
300
{}
flate
/data/pdf_icc/PSO_LWC_Standard_bas.ICC
PDF/X-4
PDF/VT-1
-->
rgba