xhtmlrenderer 多个html 转为一个pdf

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();
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值