【Java】生成PDF

使用openhtmltopdf

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.24</version>
</dependency>
<dependency>
    <groupId>com.openhtmltopdf</groupId>
    <artifactId>openhtmltopdf-core</artifactId>
    <version>1.0.10</version>
</dependency>
<dependency>
    <groupId>com.openhtmltopdf</groupId>
    <artifactId>openhtmltopdf-pdfbox</artifactId>
    <version>1.0.10</version>
</dependency>
		
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;

void outPdfFile(List<String> ids, String pdfPath) throws Exception {
    String html = "<html><head><meta charset='UTF-8'/></head><body style='font-family: 微软雅黑,宋体,仿宋'></body><p>你好PDF</p></html>";
    PdfRendererBuilder builder = new PdfRendererBuilder();
    builder.useFont(ResourceUtils.getFile("classpath:fonts/msyh.ttc"), "微软雅黑");
	builder.useFont(ResourceUtils.getFile("classpath:fonts/simsun.ttc"), "宋体");
	builder.useFont(ResourceUtils.getFile("classpath:fonts/simfang.ttf"), "仿宋");
	builder.useFont(ResourceUtils.getFile("classpath:fonts/simhei.ttf"), "黑体");
	builder.useFont(ResourceUtils.getFile("classpath:fonts/simkai.ttf"), "楷体");
	builder.useFont(ResourceUtils.getFile("classpath:fonts/simli.ttf"), "隶书");
    builder.withHtmlContent(html, "");
    builder.toStream(new FileOutputStream(pdfPath));
    builder.run();
}

 

posted @ 2025-05-20 15:14  谷粒-笔记  阅读(50)  评论(0)    收藏  举报