HTML轉成pdf:
<!-- pdf 相關jar包 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
public class PdfUtil2 {
//根據html檔案生成pdf
public static void parseHtml2PdfByFilePath(String pdfFilePath, String htmlFilePath, String fontPath) {
Document document = new Document();
PdfWriter writer = null;
FileOutputStream fileOutputStream = null;
FileInputStream fileInputStream = null;
try {
fileOutputStream = new FileOutputStream(pdfFilePath);
writer = PdfWriter.getInstance(document, fileOutputStream);
// 設定底部距離60,解決重疊問題
document.setPageSize(PageSize.A4);
document.setMargins(50, 45, 50, 60);
document.setMarginMirroring(false);
document.open();
StringBuffer sb = new StringBuffer();
fileInputStream = new FileInputStream(htmlFilePath);
BufferedReader br = new BufferedReader(new InputStreamReader(fileInputStream, "UTF-8"));
String readStr = "";
while ((readStr = br.readLine()) != null) {
sb.append(readStr);
}
XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(sb.toString().getBytes("Utf-8")), null, Charset.forName("UTF-8"), new MyFontProvider(fontPath));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != document) {
document.close();
if (null != writer) {
writer.close();
if (null != fileInputStream) {
fileInputStream.close();
} catch (IOException e) {
if (null != fileOutputStream) {
fileOutputStream.close();
/**
html中文字型設定類
@ClassName MyFontProvider
@Description
*/
public class MyFontProvider extends XMLWorkerFontProvider {
private String fontPath;
public MyFontProvider(String filePath) {
this.fontPath = filePath;
@Override
public Font getFont(final String fontname, final String encoding, final boolean embedded, final float size, final int style, final BaseColor color) {
BaseFont bf = null;
bf = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
} catch (DocumentException | IOException e) {
Font font = new Font(bf, size, style, color);
font.setColor(color);
return font;