标签:设置字体 pfile field except path new key ttf bsp
1.引入jar包
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
2.放入生成好的文档(以及字体)
3.注释代码为导出代码
// 模板路径
// String templatePath = "C:/my/test.pdf";
// 生成的新文件路径
// String newPDFPath = "E:/ceshi.pdf";
// FileOutputStream out;
PdfReader reader;
ByteArrayOutputStream bos;
PdfStamper stamper;
InputStream stream=null;
try {
Resource pdfresource=new ClassPathResource("template/dianzikepiao.pdf");
//针对打成jar包文件读取失败,使用文件流读取数据放入新的文件
InputStream inputStream = pdfresource.getInputStream();
//生成目标文件
File somethingFile = File.createTempFile("dianzikepiao", ".pdf");
try {
FileUtils.copyInputStreamToFile(inputStream, somethingFile);
} finally {
IOUtils.closeQuietly(inputStream);
}
InputStream newpdf = new FileInputStream(somethingFile);
//读取字体文件
ClassPathResource ttf=new ClassPathResource("template/SIMHEI.TTF");
InputStream inputttf = ttf.getInputStream();
//生成目标文件
File ttfFile = File.createTempFile("SIMHEI", ".TTF");
try {
FileUtils.copyInputStreamToFile(inputttf, ttfFile);
} finally {
IOUtils.closeQuietly(inputttf);
}
//使用字体根据自行放入的字体
BaseFont baseFont = BaseFont.createFont(ttfFile.getPath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// out = new FileOutputStream(newPDFPath);// 输出流
reader = new PdfReader(newpdf);// 读取pdf模板
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = stamper.getAcroFields();
//设置字体
form.addSubstitutionFont(baseFont);
//设置PDF模板文本域值
java.util.Iterator<String> it = form.getFields().keySet().iterator();
while (it.hasNext()) {
String name = it.next().toString();
if(null != map.get(name) && !"".equals(map.get(name))){
form.setField(name, map.get(name).toString());
}
}
stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑,一定要设为true
stamper.close();
// Document doc = new Document();
// PdfCopy copy = new PdfCopy(doc, out);
// doc.open();
// PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
// copy.addPage(importPage);
//上传新的PDF文件到ftp
stream= new ByteArrayInputStream(bos.toByteArray());
StorePath storePath = storageClient.uploadFile(stream,bos.size(), FilenameUtils.getExtension(map.get("tname").toString()),null);
// doc.close();
return getResAccessUrl(storePath);//返回地址
} catch (IOException e) {
log.info("生成PDF异常:"+e.getMessage());
return "";
} catch (DocumentException e) {
log.info("生成PDF异常:"+e.getMessage());
return "";
}finally {
if(stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}
标签:设置字体 pfile field except path new key ttf bsp
原文地址:https://www.cnblogs.com/Yogoo/p/13356645.html