springboot通过thymeleaf模板实现动态html模板转pdf文件

项目中,有一个需求是动态的合同模板,最终可生成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)));
	}
	
}

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值