1.maven依赖文件
<!-- 引入xmlWorkHelper -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.12</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.8</version>
</dependency>
2.注意:根据html生成对应的pdf文件,html里面的标签必须是闭合的
3.代码展示:
public class PdfParserUtil {
public static void pdfProcess(String htmlString, String pdfFileAimPath) throws Exception {
Document document = new Document(PageSize.A4);
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFileAimPath));
document.open();
document.addAuthor("Soren");
document.addCreator("Soren");
document.addCreationDate();
document.addTitle("测试生成pdf");
XMLWorkerHelper helper = XMLWorkerHelper.getInstance();
InputStream inputStream = null;
helper.parseXHtml(pdfWriter, document, new ByteArrayInputStream(htmlString.getBytes("utf-8")), inputStream, Charset.forName("UTF-8"));
document.close();
}
public static void main(String[] args) throws Exception {
String path = "E:\\测试pad.pdf";
String htmlString = "<!DOCTYPE html>\n" +
"<html>\n" +
" <head>\n" +
" <meta charset=\"utf-8\"/>\n" +
" <meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\"/>\n" +
" <title>vue-test</title>\n" +
" </head>\n" +
" <body>\n" +
" <div id=\"app\"></div>\n" +
" <!-- built files will be auto injected -->\n" +
" <h3>Hello World!!!!!!!!!!!!!!!!!!!!!!!!!!!</h3>\n" +
" <img src=\"C:\\Users\\wanglu\\Desktop\\go语言资料\\39通信过程的组包和解包.PNG\"/>\n" +
" </body>\n" +
"</html>";
PdfParserUtil.pdfProcess(htmlString, path);
}
}