当前位置: 首页 > 工具软件 > xhtmlrenderer > 使用案例 >

xhtmlrenderer 多个html 转为一个pdf

太叔烨霖
2023-12-01
public class PDFUtil {

    public static void htmls2pdf(String[] htmlFiles, String pdfFile) {
   
        Document document = new Document();
        PdfCopy pdfCopy = null; //创建一个新文件
        try {
            pdfCopy = new PdfCopy(document, new FileOutputStream(pdfFile));
            document.open();
            for (String htmlFile : htmlFiles) {
            	String url = new File(htmlFile).toURI().toURL().toString();
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ITextRenderer renderer = new ITextRenderer();
                renderer.setDocument(url);
                // 解决中文不显示问题
                ITextFontResolver fontResolver = renderer.getFontResolver();
                String path = ResourceUtils.getURL("classpath:").getPath();
                fontResolver.addFont(path + "static/pdf/font/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                renderer.layout();
                renderer.createPDF(os);
                PdfReader pdfReader = new PdfReader(os.toByteArray());
                for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
                    PdfImportedPage importedPage = pdfCopy.getImportedPage(pdfReader, i);
                    pdfCopy.addPage(importedPage);
                }
                os.close();
            }
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }

    public static void main(String[] args) {
        try {
            String[] s = new String[]{
                    "C:\\Users\\lihaitao\\Desktop\\1.html", "C:\\Users\\lihaitao\\Desktop\\2.html"
            };
            htmls2pdf(s, "C:\\Users\\lihaitao\\Desktop\\cc.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 类似资料: