Echarts Export to PDF

Source: Internet
Author: User
Tags base64 flush

It's been a long time since I wrote a blog. Recently, the company is vigorously implementing agile development. My project team is the third experimental project for Agile Development, each of whom has its own task, and each task has a predetermined amount of work. One of the tasks is to export the Echarts diagram and save it in PDF format.
Before doing this task, I searched the internet for a long time and found that there were no similar articles. It is also found that Echarts appears to support only PNG and JPG exports, and does not support PDF export. I just thought I could just convert PNG to PDF in the background.

First introduce the JSP interface code.

var Thischart = Echarts.init (document.getElementById (' mychart ')); $ (' #
    Activeresourcesexportbtn '). On (' click ', function () {var chartexporturl = ' isms/activeresource/export.do ';                                                      
    var picbase64info = Thischart.getdataurl ();//Gets the Base64 encoding for the Echarts graph, in PNG format. $ (' #chartForm '). Find (' input[name= ' Base64info "]). Val (picbase64info);//assigns the encoding to the input box $ (' #chartForm '). attr (' Action ', Chartexporturl). attr (' method ', ' post ');//settings submitted to the URL address $ (' #chartForm '
). attr (' action ', Chartexporturl). attr (' method ', ' post ');//set to submit by post $ (' #chartForm '). Submit ();

}); <form id= "Chartform" style= "Display:none" > <input id= "imagevalue" name= "Base64info" type= "text" maxlength= "5 0000 "/> </form> <div id=" MyChart "style=" Width:auto;height:500px;display:none "class=" MyChart "></ Div> 

The main function of the front-end code in the

is to get the base64 encoding of the Echarts graph, and then assign the value to an input box, which is submitted to the background through the form form. Here is the code behind the scenes.

@RequestMapping (value= "Export", method=requestmethod.post) @ResponseBody public void Chartexport (
        HttpServletResponse response,string base64info) throws IOException {String newfilename;
        NewFileName = "Chart" + System.currenttimemillis () + ". pdf";
        String newpngname = Newfilename.replacefirst (". pdf", ". png");
        String Exportfilepath = "D:/export" 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));//Generate PNG file Output.write (BU
            Ffer);
            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 ();
        } response.setcontenttype ("Application/octet-stream");
        InputStream input = null;
        OutputStream outputstring = null; try {response.setheader ("content-disposition", "attachment; Filename=" + Urlencoder.encode ("chart" + ". pdf", "UT

            F-8 ")); Set the browser popup download box, the front End with form form submission, I use Ajax no effect.
            input = new Bufferedinputstream (new FileInputStream (New File (Exportfilepath + newfilename));
            outputstring = new Bufferedoutputstream (Response.getoutputstream ());
            Copy (input, outputstring);
        Outputstring.flush ();
        } catch (Unsupportedencodingexception e) {e.printstacktrace ();
        }catch (IOException e) {e.printstacktrace ();
            }finally{Input.close (); OUtputstring.close (); *//PNG file to generate PDF file Public file PDF (string ImagePath, String moutputpdffilename) {Document doc = n
        EW 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; }//input stream read to output stream private void copy (Bufferedinputstreaminput,bufferedoutputstream outputstring) {byte [] but = new byt
        E[1024];
                try {while (Input.read ()!=-1) {int. = Input.read (But);
                Outputstring.write (But, 0, by);
            Outputstring.flush ();
        }} catch (IOException e) {e.printstacktrace (); }
    }

The above code is the controller layer of code, but also the main processing logic behind the scenes. You should pour the itext package before using the code, and you should use Itex to generate the PDF file. Most of the code is an IO stream, which is not covered in detail. Hope to be helpful to everyone.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.