java html转pdf
引入依赖
<!--html 转 pdf -->
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf</artifactId>
<version>9.0.7</version>
</dependency>
java代码实现
package com.cudatec.infra.se.controller;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
/**
* @program:
* @description:
* @author:
* @create:
**/
public class TestController {
public static void main(String[] args) {
String outputFile = "test.pdf";
InputStream inputStream = null;
Document doc = null;
try {
OutputStream out = new FileOutputStream(outputFile);
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
ITextRenderer renderer = new ITextRenderer();
inputStream = new ByteArrayInputStream(buildContent().getBytes("utf-8"));
doc =builder.parse(inputStream);
renderer.setDocument(doc, null);
renderer.layout();
renderer.createPDF(out, true);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static String buildContent() throws IOException {
//resourse 下html加载
InputStream inputStream = this.getClass().getResourceAsStream("/template/demo.html");
BufferedReader fileReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer = new StringBuffer();
String line = "";
try {
while ((line = fileReader.readLine()) != null) {
buffer.append(line);
}
} catch (Exception e) {
//异常日志打印
} finally {
inputStream.close();
fileReader.close();
}
String value = buffer.toString();
return value;
}
}
如果帮助到了你,麻烦关注下,谢谢!