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);
}
}