html转Pdf[包含文件上传]

    /**
     * @param mess     富文本编辑器里的html信息
     * @param fileName 文件名
     * @return
     * @description html转Pdf[文件上传]
     */
    public String htmlToPdfUpload(String mess, String fileName) throws IOException {
        // 每次根据时间创建文件夹,作为文件和压缩文件保存目录
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = formatter.format(new Date());

        File f = new File(filePath);
        if (!f.exists()) {
            f.mkdirs();
        }

        //一、先生成html文件
        File dest = new File(filePath + File.separator + fileName + time + ".htm");
        //字节输出流
        FileOutputStream fos = new FileOutputStream(dest);
        //接收字节输入流
        InputStream is = org.apache.commons.io.IOUtils.toInputStream(mess, "UTF-8");
        //为字节输入流加缓冲
        BufferedInputStream bis = new BufferedInputStream(is);
        //为字节输出流加缓冲
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        int length;
        byte[] bytes = new byte[1024 * 20];
        while ((length = bis.read(bytes, 0, bytes.length)) != -1) {
            fos.write(bytes, 0, length);
        }
        bos.close();
        fos.close();
        bis.close();
        is.close();

        //二、html文件转成pdf
        try {
            String HTML = dest.getPath();
            Document document = new Document(PageSize.LETTER);
            PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(filePath + File.separator + fileName + time + ".pdf"));
            document.open();
            document.addAuthor("test");
            document.addCreator("test");
            document.addSubject("test");
            document.addCreationDate();
            document.addTitle("XHTML to PDF");

            XMLWorkerHelper worker = XMLWorkerHelper.getInstance();

            worker.parseXHtml(pdfWriter, document, new FileInputStream(HTML), (InputStream) null, new AsianFontProvider());
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        dest.delete();
        return fileName + time + ".pdf";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值