javascript
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: infra-acm
* @description:
* @author: xuwenjie
* @create: 2020-09-25 10:33
**/
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 {
//加载邮件html模板
String fileName = "demo.html";
InputStream inputStream = ClassLoader.getSystemResourceAsStream(fileName);
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();
//可以对value操作
return value;
}
}
//依赖
javascript
<!--html 转 pdf -->
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf</artifactId>
<version>9.0.7</version>
</dependency>