- 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) {
- try {
- fileInputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (null != fileOutputStream) {
- try {
- fileOutputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
来源: http://www.bubuko.com/infodetail-3113321.html