1.maven jar包依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.13</version>
</dependency>
2.核心代码
public static ByteArrayOutputStream htmlToPdf(String htmlStr){
Document document = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
document = new Document(PageSize.A3);
PdfWriter pdfWriter = PdfWriter.getInstance(document,
baos);
document.open();
XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, new ByteArrayInputStream(htmlStr.getBytes()), Charset.forName("UTF-8"),new AsianFontProvider());
} catch (DocumentException e) {log.error("HtmlToPDF 获取实例pdfWriter失败....",e);
throw new BusException();
}catch (IOException e) {
log.error("HtmlToPDF 转换pdf失败....",e);
throw new BusException();
} catch (RuntimeWorkerException e) {
log.error("html标签未闭合...", e);
throw new BusException();
} catch (Exception e) {
log.error("HtmlToPDF 转换pdf失败....", e);
throw new BusException();
} finally {
if (document != null) {
try {
document.close();
} catch (Exception e) {
log.error("document关闭异常...",e);
throw new BusException();
}
}
}
return baos;
}
/**
*
* @version 1.0
* @date 2020/3/22 15:43
* @description 解决pdf文件中文不显示的问题
**/
@Slf4j
public class AsianFontProvider extends XMLWorkerFontProvider {
public Font getFont(final String fontname, final String encoding,
final boolean embedded, final float size, final int style,
final BaseColor color) {
BaseFont bf = null;
try {
bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (Exception e) {
log.error("生成pdf文件,添加字体失败",e);
}
Font font = new Font(bf, size, style, color);
font.setColor(color);
return font;
}
}