Freemarker + flying-saucer-pdf 基于IText2.17实现HTML文档转换成PDF

9 篇文章 0 订阅
1 篇文章 0 订阅
一、引入依赖
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>
        <dependency>
            <groupId>org.xhtmlrenderer</groupId>
            <artifactId>flying-saucer-pdf</artifactId>
            <version>9.1.5</version>
        </dependency>
二、创建Freemarker模板(test.ftl)
		<html>
		<head>
		    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/><br/>
		    <title>测试</title>
		</head>
		
		<body style="font-family:FangSong;" >
		    <table border="1">
		        <#list itemList as item>
		            <tr>
		                <th>${item.id}</th>
		                <th>${item.name}</th>
		            </tr>
		        </#list>
		    </table>
		    <img src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAAQABAAD//gA/Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0IHF1YWxpdHkKAP/bAEMAAgEBAgEBAgICAgICAgIDBQMDAwMDBgQEAwUHBgcHBwYHBwgJCwkICAoIBwcKDQoKCwwMDAwHCQ4PDQwOCwwMDP/bAEMBAgICAwMDBgMDBgwIBwgMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDP/AABEIAHgAeAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQ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X8A+MbLyYrLVre5ln1a9spZ7VAsZtGdlt4It9srRA7ZRLGS6iJjXmPw7+D8l34I8W+MbebS/hDdqIPCmh/23PLBdaEEiH2zNutuiybpXE8KhmJlkdvlCutFFeZCTjU5V1t+Vz6GpGMqVrbN6630cV+rOF8VWVp408+bR9U0hfHngua7hsbWHUjo9qgkxOb7ynSASQFzdXEvlRlpPPjRlDR75Siivp8LXjUgpVKcXouj9ej8z5rEYWWHrTpUKkoq76rX1umf/2Q==" alt="" width="120" height="120"/>
		</body>
		</html>
四、创建转换工具
package com.test.demo.pdf;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * HTML转换成PDF文件
 * @Author LinCH
 **/
public class HtmlToPdfUtils {

    private static Logger LOG = LoggerFactory.getLogger(HtmlToPdfUtils.class);

    /**
     * 生成PDF文档字节流
     * @param template Freemarker模板
     * @param variables 参数
     * @param fontPaths 字体文件路径(文档中存在中文一定要设置一个支持中文的字体,且在这边必须将该字体的文件设置进来,否则中文无法显示)
     * @return PDF文档字节流
     * @throws IOException
     * @throws DocumentException
     * @throws TemplateException
     */
    public static ByteArrayOutputStream generatePdfStream(String template, Map<String, Object> variables, String[] fontPaths) throws IOException, DocumentException, TemplateException {
        String htmlStr = generateHtmlStr(template, variables);
        LOG.debug(htmlStr);
        ITextRenderer renderer = new ITextRenderer();
        ITextFontResolver fontResolver = renderer.getFontResolver();
        for(String fontPath : fontPaths){
            fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        renderer.setDocumentFromString(htmlStr);
        renderer.layout();
        renderer.createPDF(os);
        return os;
    }

    /**
     * 使用Freemarker生成HTML文档
     * @param template Freemarker模板
     * @param variables 参数
     * @return 生成的HTML文档字符串
     * @throws IOException
     * @throws TemplateException
     */
    public static String generateHtmlStr(String template, Map<String, Object> variables) throws IOException, TemplateException {
        Configuration config = new Configuration();
        config.setClassForTemplateLoading(FreemarkerUtils.class, "/");
        Template tp = config.getTemplate(template);
        StringWriter stringWriter = new StringWriter();
        BufferedWriter writer = new BufferedWriter(stringWriter);
        tp.setEncoding("UTF-8");
        tp.process(variables, writer);
        String htmlStr = stringWriter.toString();
        writer.flush();
        writer.close();
        return htmlStr;
    }

}

四、生成并下载PDF文档
package com.test.demo.web.controller;

import com.lowagie.text.DocumentException;
import com.test.demo.pdf.HtmlToPdfUtils;
import com.test.demo.pdf.Item;

import freemarker.template.TemplateException;

import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * @Author LinCH
 **/
@Controller
public class TestController {

    public final static String USER_AGENT = "USER-AGENT";
    public final static String MSIE = "MSIE";
    public final static String TRIDENT = "Trident";
    public final static String MOZILLA = "Mozilla";
    public final static String UTF8 = "UTF-8";
    public final static String ISO88591 = "ISO8859-1";

    @RequestMapping("/fun1")
    public ResponseEntity<byte[]> fun1(HttpServletRequest request) throws DocumentException, TemplateException, IOException {

        Map<String, Object> map = new HashMap<>();
        List<Item> itemList = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            itemList.add(new Item("id" + i, "张三aaaaaaaaa" + i));
        }
        map.put("itemList", itemList);

        ByteArrayOutputStream os = HtmlToPdfUtils.generatePdfStream("test.ftl",
            map, new String[]{new ClassPathResource("/simfang.ttf").getPath()});

        HttpHeaders headers = new HttpHeaders();

        String codedfilename = null;
        String agent = request.getHeader(USER_AGENT);
        // IE
        if (null != agent && -1 != agent.indexOf(MSIE) || null != agent && -1 != agent.indexOf(TRIDENT)) {
            String name = java.net.URLEncoder.encode("PDF测试.pdf", UTF8);
            codedfilename = name;
        } else if (null != agent && -1 != agent.indexOf(MOZILLA)) {
            codedfilename = new String("PDF测试.pdf".getBytes(UTF8), ISO88591);
        }

        headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + codedfilename + "\"");
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<>(os.toByteArray(), headers, statusCode);
        return entity;

    }

}

五、备注
	IText在2.17以后的版本开源协议为AGPL,商用时需谨慎,目前还是使用2.17版本。
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用FreemarkeriText可以方便地将HTML换为PDF。下面是一个基本的示例: 1. 首先,您需要引入iTextfreemarker的依赖项。如果您使用的是Maven,可以添加以下依赖项到pom.xml文件中: ``` <dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>2.1.7</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency> ``` 2. 创建Freemarker模板,例如: ``` <html> <head> <title>${title}</title> </head> <body> <h1>${heading}</h1> <p>${content}</p> </body> </html> ``` 3. 创建Java类来生成PDF文件。例如: ``` import java.io.*; import java.util.*; import com.lowagie.text.*; import com.lowagie.text.pdf.*; import freemarker.template.*; public class HtmlToPdf { public static void main(String[] args) throws Exception { // 创建数据模型 Map<String, Object> data = new HashMap<String, Object>(); data.put("title", "My PDF Document"); data.put("heading", "Hello World"); data.put("content", "This is my first PDF document."); // 创建Freemarker模板 Configuration cfg = new Configuration(Configuration.VERSION_2_3_31); cfg.setClassForTemplateLoading(HtmlToPdf.class, "/"); Template template = cfg.getTemplate("template.ftl"); // 将Freemarker模板渲染为HTML StringWriter writer = new StringWriter(); template.process(data, writer); String html = writer.toString(); // 创建PDF文档 Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("output.pdf")); document.open(); // 将HTML换为PDF InputStream is = new ByteArrayInputStream(html.getBytes()); XMLWorkerHelper.getInstance().parseXHtml(writer, document, is); // 关闭PDF文档 document.close(); } } ``` 这个示例将生成一个名为“output.pdf”的PDF文件,其中包含一个标题为“My PDF Document”的页面,以及一个标题为“Hello World”和内容为“This is my first PDF document.”的段落。 请注意,此示例仅是一个基本示例。您可以根据需要修改模板和Java代码以生成更复杂的PDF文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值