Springboot导出PDF⽂件
需求描述
最近项⽬有⼀个需求,需要导出 PDF ⽂件,由于之前并没有做过这⽅⾯的需求,从⽹上花了很长时间才到相关的资料。最后采⽤
了aspose.words + freemarker的⽅式解决的问题,制作 freemarker 模板,将 freemarker 模板转为 word ⽂件。然后再使⽤
aspose.words 将 word ⽂件转为 PDF⽂件。⼀开始也尝试过使⽤ docx4j 将 word ⽂件转为 PDF,但转完正⽂中⽂乱码、还有其他各种格式问题,最后并没有采⽤。
所需依赖
由于 aspose.words 是破解版,在互联⽹仓库⽆法下载,需⼿动将 jar 包引⼊本地库,如果公司有私服的话也可以上传到⾃⼰公司的私服,引⼊本地库命令如下:
mvn install:install-file -DgroupId=com.aspose -DartifactId=aspose.words -Dversion=15.8 -Dpackaging=jar -Dfile=aspose-words-15.8.0-jdk16.jar
<!-- freemarker模板引擎,⽤于定义代码⽣成模板 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose.words</artifactId>
<version>15.8</version>
</dependency>
制作freemarker模板
在 word 中编写你想要的⽂档,将 word ⽂档另存为 xml 格式,将需要注⼊数据的地⽅修改为 ${xxx} 格式,并且记住你的字段名,如果有多条数据则添加 <#list userList as user></#list>标签,userList 是 Map ⾥⾯的 key。
编辑好之后另存为 .ftl ⽂件,这就是模板。可以存放到项⽬⾥的 resource 下的 templates ⽂件夹下
word⽂档⽣成⼯具类
plate.Configuration;
plate.Template;
import java.io.*;
import java.util.Map;
/**
* @author cxhello
* @date 2021/4/2
*/
public class WordUtil {
private static final String ENCODING ="UTF-8";
/**
* ⽣成word⽂档
* @param templateName
* @param map
* @return
* @throws IOException
*/
public static File generateWord(String templateName, Map map)throws IOException {
Configuration configuration =getConfiguration();
Template template = Template(templateName);
File file =createDoc(map, template);
return file;
}
private static Configuration getConfiguration(){
Configuration configuration =new Configuration(Configuration.VERSION_2_3_23);
configuration.setDefaultEncoding(ENCODING);
configuration.setClassForTemplateLoading(WordUtil.class,"/templates/");
return configuration;
}
private static File createDoc(Map<?,?> dataMap, Template template){
String name ="sellPlan.doc";
File f =new File(name);
Template t = template;
try{
// 这个地⽅不能使⽤FileWriter因为需要指定编码类型否则⽣成的Word⽂档会因为有⽆法识别的编码⽽⽆法打开 Writer w =new OutputStreamWriter(new FileOutputStream(f), ENCODING);
t.process(dataMap, w);
w.close();
}catch(Exception ex){
ex.printStackTrace();
throw new RuntimeException(ex);
}
return f;
}
}
word转换PDF⼯具类
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.URLEncoder;
/**
* @author cxhello
* @date 2021/4/2
*/
public class PdfUtil {
private static final Logger logger = Logger(PdfUtil.class);
public static void covertDocToPdf(File file, String fileName, HttpServletResponse response){
response.setContentType("application/pdf");
try{
if(!isWordLicense()){
<("License验证不通过");
}
fileName = fileName +".pdf";
response.setHeader("Content-Disposition","attachment;filename="
.concat(String.de(fileName,"UTF-8"))));
FileInputStream fileInputStream =new FileInputStream(file);
Document doc =new Document(fileInputStream);
fileInputStream.close();
doc.OutputStream(), SaveFormat.PDF);
}catch(Exception e){
e.printStackTrace();
springboot中文}finally{
if(file != null){
file.delete();
}
}
}
public static boolean isWordLicense(){
boolean result =false;
try{
InputStream inputStream = ClassLoader().getResourceAsStream("l"); License license =new License();
license.setLicense(inputStream);
result =true;
}catch(Exception e){
e.printStackTrace();
}
return result;
}
}
业务类
ller;
import com.alibaba.fastjson.JSON;
ity.StandardReportData;
ample.util.PdfUtil;
ample.util.PdfUtil;
ample.util.WordUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.ClassPathResource;
import io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author cxhello
* @date 2021/4/2
*/
@Controller
public class ExportController {
private static final Logger logger = Logger(ExportController.class);
@GetMapping("/exportPdf")
public void exportPdf(HttpServletResponse response){
Map<String, Object> map =new HashMap<>();
String waterName ="测试⽔⼚";
map.put("waterName", waterName);
map.put("time","2021-03-23");
SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = simpleDateFormat.format(new Date());
map.put("date", date);
Resource resource =new ClassPathResource("test.json");
InputStream is = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try{
is = InputStream();
inputStreamReader =new InputStreamReader(is);
bufferedReader =new BufferedReader(inputStreamReader);
StringBuilder str =new StringBuilder();
String s;
while((s = adLine())!= null){
str.append(s);
}
StandardReportData standardReportData = JSON.String(), StandardReportData.class); map.put("standardReportData", standardReportData);
File file = ateWord("template.ftl", map);
}catch(IOException e){
<("System error", e);
}finally{
try{
is.close();
inputStreamReader.close();
bufferedReader.close();
}catch(IOException e){
<("System error", e);
}
}
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论