项目中,有一个需求是动态的合同模板,最终可生成pdf文件。项目架构是springboot
1、在pom.xml里添加thymeleaf的starter和生成pdf的jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf</artifactId>
<version>9.0.7</version>
</dependency>
2、在application.yml或者application.properties中添加thymeleaf的配置
thymeleaf:
prefix: classpath:/templates
suffix: .html
mode: HTML
encoding: utf-8
servlet.content-type: text/html
cache: false
3、下边是实现代码
@Controller
@RequestMapping("/test")
public class TestThymeleafEngineController {
@Autowired
private TemplateEngine templateEngine;
@GetMapping("/index")
public String index(HttpServletRequest request,HttpServletResponse response){
WebContext ctx = new WebContext(request, response,request.getServletContext(),request.getLocale() );
//这里图片路径设置成了全路径,要不然在pdf中不显示
ctx.setVariable("imgUrl", request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/images/1.jpg");
try {
//"/contract" 为模板文件,注意路径和“/”
String htmlcontext = templateEngine.process("/contract", ctx);
HtmlToPdf.topdf(htmlcontext,"D:/test.pdf");
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("time", new Date());
return "/contract";
}
}
//psf工具栏
public class HtmlToPdf {
public static void topdf(String content,String path) throws DocumentException, FileNotFoundException{
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver fontResolver = renderer.getFontResolver();
try {
//设置字体,否则不支持中文,在html中使用字体,html{ font-family: SimSun;}
fontResolver.addFont("templates/simsun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
renderer.setDocumentFromString(content);
renderer.layout();
renderer.createPDF(new FileOutputStream(new File(path)));
}
}
更多推荐
springboot通过thymeleaf模板实现动态html模板转pdf文件
发布评论