1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import com.aspose.words.License;
/**
* freemarker模板生成pdf
*/
@SneakyThrows
private void freemarkerGenePdf(HttpServletResponse response) {
// 1. freemarker to word.xml
// a.构建模板
Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
cfg.setClassForTemplateLoading(this.getClass(), "/");
// .ftl文件,先将word转xml,再改文件后嘴得到
Template template = cfg.getTemplate(this.getClass().getResource("/").getPath() + "template" + File.separator + "zxalive.com账单.ftl");
// b.构建输出流
File docxTemp = File.createTempFile("temp", ".docx");
// c.构建map
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("key1", "value1");
dataMap.put("key2", 123);
dataMap.put("key3", true);
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docxTemp), StandardCharsets.UTF_8))) {
// d.渲染
template.process(dataMap, writer);
}
// 2. word.xml to word
File xmlFile = new File(docxTemp.getAbsolutePath());
File wordFile = new File(xmlFile.getParent(), xmlFile.getName().replace(".xml", ""));
// xml重命名为word
xmlFile.renameTo(wordFile);
// 3. word to pdf
File pdfFIle = File.createTempFile("temp", ".pdf");
// 验证License 若不验证则转化出的pdf文档会有水印产生
try (InputStream licenseIn = this.getClass().getResourceAsStream("/license/license.xml")) {
new License().setLicense(licenseIn);
}
try (XWPFDocument document = new XWPFDocument(new FileInputStream(wordFile));
BufferedOutputStream pdfbos = new BufferedOutputStream(new FileOutputStream(pdfFIle));
) {
document.write(pdfbos);
pdfbos.flush();
}
// 4. web下载pdf
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(pdfFIle.getAbsolutePath()))) {
// 构建response
response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("fileName", StandardCharsets.UTF_8)
.replaceAll("\\+", "%20")
.replaceAll("%2F", "/")
+ ".xlsx");
response.setContentType("application/vnd.ms-excel"); // application/json application/pdf
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
}
}
|