Echarts导出为pdf格式

导出Echarts图,并且存储为pdf格式。 发现Echarts好像是只支持png和jpg的导出,不支持pdf导出。我就想着只能够将png在后台转为pdf了。

首先介绍一下jsp界面的代码。

var thisChart = echarts.init(document.getElementById('myChart'));
$('#activeResourcesExportBtn').on('click',function(){  
    var chartExportUrl = 'isms/activeResource/export.do';
    var picBase64Info = thisChart.getDataURL();//获取echarts图的base64编码,为png格式。                                                      
    $('#chartForm').find('input[name="base64Info"]').val(picBase64Info);//将编码赋值给输入框
    $('#chartForm').attr('action',chartExportUrl).attr('method', 'post');//设置提交到的url地址                                                 
    $('#chartForm').attr('action',chartExportUrl).attr('method', 'post');//设置提交方式为post
    $('#chartForm').submit();
});

<form id="chartForm" style="display:none">
    <input id="imageValue" name="base64Info" type="text" maxlength="50000"/>
</form>
<div id="myChart" style="width:auto;height:500px;display:none" class="myChart"></div>
上面的前端代码主要的作用是获取echarts图的base64编码,然后把值赋给一个input输入框,通过form表单提交到后台。下面是后台的代码。

跟转载的,我有自己修改一些。将文件下载输出的这一块,改成ResponseEntity方式。

@Controller
@RequestMapping("/performance")
public class ExportPdfController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExportPdfController.class);

    @RequestMapping(value = "export", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity chartExport(HttpServletResponse response, String base64Info, HttpServletRequest request) throws IOException {
        String newFileName;
        newFileName = "统计图" + System.currentTimeMillis() + ".pdf";
        String newPngName = newFileName.replaceFirst(".pdf", ".png");
        String exportFilePath = "d:/test";
        base64Info = base64Info.replaceAll(" ", "+");
        BASE64Decoder decoder = new BASE64Decoder();
        String[] arr = base64Info.split("base64,");
        byte[] buffer;
        try {
            buffer = decoder.decodeBuffer(arr[1]);
        } catch (IOException e) {
            throw new RuntimeException();
        }
        OutputStream output = null;
        try {
            output = new FileOutputStream(new File(exportFilePath + newPngName));//生成png文件
            output.write(buffer);
            output.flush();
            output.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Pdf(exportFilePath + newPngName, exportFilePath + newFileName);
        File f = new File(exportFilePath + newPngName);
        if (f.exists()) {
            f.delete();
        }

        try {
            byte[] fileBytes = FileUtils.readFileToByteArray(new File(exportFilePath + newFileName));
            HttpHeaders headers = new HttpHeaders();
            String fileName = newFileName;
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            }
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setPragma("public");
            headers.setCacheControl("max-age=0");
            return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            LOGGER.error("IOException:", e);
            return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
        }

    }

    //通过png文件来生成pdf文件
    public File Pdf(String imagePath, String mOutputPdfFileName) {
        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
        try {
            PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName));
            doc.open();
            doc.newPage();
            Image png1 = Image.getInstance(imagePath);
            float heigth = png1.getHeight();
            float width = png1.getWidth();
            int percent = this.getPercent2(heigth, width);
            png1.setAlignment(Image.MIDDLE);
            png1.setAlignment(Image.TEXTWRAP);
            png1.scalePercent(percent + 3);
            doc.add(png1);
            doc.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        File mOutputPdfFile = new File(mOutputPdfFileName);
        if (!mOutputPdfFile.exists()) {
            mOutputPdfFile.deleteOnExit();
            return null;
        }
        return mOutputPdfFile;
    }

    private int getPercent2(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        p2 = 530 / w * 100;
        p = Math.round(p2);
        return p;
    }

    //输入流读取到输出流
    private void copy(BufferedInputStream input, BufferedOutputStream outputString) {
        byte[] but = new byte[1024];
        try {
            while (input.read() != -1) {
                int by = input.read(but);
                outputString.write(but, 0, by);
                outputString.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

面的代码是controller层的代码,也是后台主要的处理逻辑。在使用代码之前应该倒入itext包,应为是用itex来生成pdf文件。大部分的代码都是io流的东西,就不详细介绍了。希望能对大家有所帮助。


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值