将HTML文件转换为PDF文件
一、导入依赖
<!-- itext生成Pdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.8</version>
</dependency>
二、编写HTML文件
注意:HTML文件内不能有为闭合的端口,比如要将标签改为格式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
<div>
<h1>Hello Word!</h1>
<h2>Hello Word!</h2>
<h3>Hello Word!</h3>
<h4>Hello Word!</h4>
<h5>Hello Word!</h5>
<h6>Hello Word!</h6>
<h7>Hello Word!</h7>
</div>
</body>
</html>
三、编写controller类
package com.cn.controller;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import static org.apache.tomcat.util.file.ConfigFileLoader.getInputStream;
@Controller
public class TestController {
@GetMapping("/TestPDF")
@ResponseBody
public String TestPDF2() throws Exception{
//第一步,创建一个 iTextSharp.text.Document对象的实例:
Document document = new Document();
//第二步,为该Document创建一个Writer实例:
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\HelloWorld2.pdf"));
//第三步,打开当前Document
document.open();
//第四步,为当前Document添加内容:
//document.add(new Paragraph("Hello World"));
XMLWorkerHelper.getInstance().parseXHtml(writer, document,