栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

html转Pdf[包含文件上传]

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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";
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/310563.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号