使用openhtmltopdf 工具进行转PDF
springBoot后台如何共用一个css文件
1.首先在META-INF路径下添加一个公共的css文件,然后在springboot启动设置静态资源,要确保项目启动后能够访问到此文件,如:
META-INF/resources/static/css/index.css
测试访问是否成功:http://localhost:8000/static/css/index.css
如果不能访问,请检查是否有白名单设置
String html = "html 内容";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.toStream(baos);
builder.useFastMode();
builder.useFont(() -> TcFonts.readFont(fontFamily), fontFamily);
builder.withW3cDocument(new W3CDom().fromJsoup(Jsoup.parse(html)),"/");
builder.run();
return baos.toByteArray();
} finally {
html = null;
if (baos != null) {
baos.close();
}
}
读取静态文件超时或失败,我这边给出两个解决方案:
1.修改HTTP默认时长
重写com.openhtmltopdf.swing.NaiveUserAgent 类
//默认
//final static int CONNECTION_TIMEOUT = 10_000;
//final static int READ_TIMEOUT = 30_000;
//增加一倍
final static int CONNECTION_TIMEOUT = 30_000;
final static int READ_TIMEOUT = 60_000;