itextpdf convert html string to Pdf
Posted 北冥鱼_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了itextpdf convert html string to Pdf相关的知识,希望对你有一定的参考价值。
一、导入依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>4.0.0</version>
</dependency>
<!-- 中文字体-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>font-asian</artifactId>
<version>7.2.0</version>
</dependency>
二、解决中文乱码问题
/**
* @description: html导出PDF支持中文,避免乱码
* @author: chang
* @create: 2021-11-04 14:25
**/
public class ChineseFontProvider extends XMLWorkerFontProvider
@Override
public Font getFont(String fontname, String encoding, float size, int style)
try
BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
// BaseFont bfChinese = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
return new Font(bfChinese,13,style);
// return new Font(bfChinese,size,style);
catch (Exception e)
e.printStackTrace();
return super.getFont(fontname, encoding, size, style);
三、由html字符串生成pdf
public static void convertHtmlToPdf() throws IOException
String htmlStr = "<!DOCTYPE html>\\n" +
"<html>\\n" +
"<head>\\n" +
"<meta charset=\\"utf-8\\">\\n" +
"<title>文档标题</title>\\n" +
"</head>\\n" +
"<body>\\n" +
"\\t<h1>我的第一个HTML页面</h1>\\n" +
"\\t<p>我的第一个段落。</p>\\n" +
"</body>\\n" +
"</html>\\n" +
"\\n";
Document document = new Document();
try
PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(FILE_BASE_PATH+"htmlToPDF.pdf"));
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer,document,new ByteArrayInputStream(htmlStr.getBytes(StandardCharsets.UTF_8)),null, Charset.forName("UTF-8"),new ChineseFontProvider());
document.close();
catch (DocumentException e)
e.printStackTrace();
参考链接:
以上是关于itextpdf convert html string to Pdf的主要内容,如果未能解决你的问题,请参考以下文章
itextpdf convert html string to Pdf
itextpdf convert html string to Pdf