I want to convert html to pdf with itext in my java code,but it seems that the strong tag and em tag don't work.I try to search solutions in the network and tracing my code to find out why,but failed.Here are my java code , my html file and generated pdf snapshot below.
public static boolean html2pdf(String htmlContent, String path) {
try (FileOutputStream fos = new FileOutputStream(path);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(htmlContent.getBytes())) {
Document document = new Document();
PdfWriter pdfWriter = PdfWriter.getInstance(document, fos);
document.open();
XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, byteArrayInputStream,
Charset.forName("UTF-8"), new MyFontProvider());
document.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
static class MyFontProvider extends XMLWorkerFontProvider {
@Override
public Font getFont(String fontname, String encoding, float size, int style) {
Font cnFont = null;
try {
BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
cnFont = new Font(baseFont);
} catch (Exception e) {
e.printStackTrace();
}
if (cnFont == null) {
cnFont = super.getFont(fontname, encoding, size, style);
}
return cnFont;
}
}
and my dependencies:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<!DOCTYPE html>
<html>
<head>
<title>title</title>
</head>
<body>
<p >
<strong>overstrike</strong>
</p>
<p>
<em>incline</em>
</p>
</body>
</html>
Solved
I solved this by using itext7.