html转pdf

需求是html转pdf后上传到阿里云oss并将url返回

直接上工具类

public static String html2pdf(String html,String tempFilePath,String fileName) throws Exception{

        /*BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
        Font font = new Font(bfChinese, 12, Font.NORMAL);*/  // 增加段落时使用
        Document document = new Document(PageSize.A4, 20, 20, 10, 10);
        //String pdffile = "E:\\Download\\test.pdf";
        OutputStream os = new FileOutputStream(tempFilePath);
        PdfWriter mPdfWriter = PdfWriter.getInstance(document, os);
        document.open();

        ByteArrayInputStream bin = new ByteArrayInputStream(html.getBytes("UTF-8"));
        XMLWorkerHelper.getInstance().parseXHtml(mPdfWriter, document, bin, Charset.forName("UTF-8"), new ChinaFontProvide());
        document.close();
        mPdfWriter.flush();
        mPdfWriter.close();


        FileInputStream is = new FileInputStream(tempFilePath);
        String filePath = UUID.randomUUID().toString()+"/"+fileName;
        String url= AliOssUtil.upload(DOMAIN_DP,HANGZHOU_ENDPOINT, BUCKET_NAME_DP, filePath, is);
        is.close();
        return url;
    }

值得提一下的是,这种方式是在本地生成临时文件,然后上传,在业务逻辑中有删除临时文件的代码,所以在流使用完毕后,记得flush和close,否则在删除的时候会提示文件被占用。

一下是业务逻辑代码

/**
     * html转pdf
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"/html2pdf", "/v2/html2pdf"}, produces = "application/json;charset=UTF-8")
    public R html2pdf(@RequestBody Html2PdfRequest request,HttpServletResponse response,HttpServletRequest httpServletRequest) {

        String html = request.getHtml();
        try {
            String temppath = httpServletRequest.getServletContext().getRealPath("/") + "temp" + File.separatorChar + UUID.randomUUID().toString();

            File newfile = FileUtil.getNewFile(temppath + File.separatorChar + "html2pdf_temp");
            FileOutputStream fileOutputStream = new FileOutputStream(newfile);
            fileOutputStream.write("".getBytes());

            String fileName = URLEncoder.encode(request.getFileName() + ".pdf", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            String url = PDFUtil.html2pdf(html,newfile.getAbsolutePath(),request.getFileName() + ".pdf");
            fileOutputStream.flush();
            fileOutputStream.close();
            FileUtils.deleteDirectory(new File(temppath));
            return R.ok().put("url",url);
        } catch (Exception e) {
            logger.error(e);
            return R.error("下载异常");
        }
    }

至此,即为前端提供了html转pdf的接口。

Adobe Reader XI 闪退问题

上一篇

pdf转png图片乱码问题(字体缺失,centos安装字体)

下一篇
评论
发表评论 说点什么
还没有评论
83
0