iText将HTML导出为PDF文件 - 知乎

maven依赖

<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>itextpdf</artifactId>
  <version>5.5.13.2</version>
</dependency>
<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>itext-asian</artifactId>
  <version>5.2.0</version>
</dependency>
<!-- HTML 转 PDF -->
<dependency>
  <groupId>com.itextpdf.tool</groupId>
  <artifactId>xmlworker</artifactId>
  <version>5.4.1</version>
</dependency>
<!-- 模板引擎 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

示例:HMTL转PDF,使用模板引擎

@Autowired 
@GetMapping("/create")
public void createPdf(HttpServletRequest request, HttpServletResponse response) {
    Document document = new Document(PageSize.A4);
    OutputStream outputStream;
    PdfWriter pdfWriter;
    ByteArrayInputStream byteArrayInputStream;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    XMLWorkerHelper xmlWorkerHelper;
    String html = "";
    try {
        pdfWriter = PdfWriter.getInstance(document, byteArrayOutputStream);
        document.open();
        xmlWorkerHelper = XMLWorkerHelper.getInstance();
        // 使用模板引擎TemplateEngine,生成HTML内容
        html = HTMLUtil.createHtml(templateEngine);
        byteArrayInputStream = new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8));
        xmlWorkerHelper.parseXHtml(pdfWriter, document, byteArrayInputStream, StandardCharsets.UTF_8);
        document.close();

        // inline(默认)当前页面打开;attachment 下载到本地
        response.setHeader("Content-Disposition", "attachment;filename=Test.pdf");
        response.setContentType("application/pdf");
        outputStream = response.getOutputStream();
        byteArrayOutputStream.writeTo(outputStream);
        outputStream.flush();
        outputStream.close();
    } catch (DocumentException | IOException e) {
        e.printStackTrace();
    }
}
public class HTMLUtil {
    public static String createHtml(TemplateEngine templateEngine) {
        String html = "";
        // TemplateEngine templateEngine = new TemplateEngine();
        Context context = new Context();
        html = templateEngine.process("/pdfTemplatePage", context);
        return html;
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Invalid nested tag head found, expected closing tag meta.   -->
    <!--    <meta charset="UTF-8" > -->
    <meta charset="UTF-8" />
    <title>PDF</title>
</head>
<body>
<p>Hello World!</p>
<p style="font-family: fangsong;font-size: 24px;">中文</p>
<p style="font-family: Microsoft YaHei;font-size: 24px;">中文</p>
<p style="font-size: 24px;">中文</p>
</body>
</html>

运行效果


原网址: 访问
创建于: 2023-08-08 18:16:00
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论