Echarts、Highcharts、html2canvas圖片導出到excle文件中

echarts導出圖片

首先定義一個div
<div  class="col-md-8">
    <div id="main" class="main">
    </div>
</div>
js代碼-----------------------
var myChart = ec.init(document.getElementById('main')); 
 var picBase64Info1 = myChart.getDataURL();   //獲取base64編碼  
$("#canvasImg").val(picBase64Info1);把base64碼,放到隱藏域中,傳到後臺

後臺代碼---------------------------------------
String canvasImg= super.GetParameterStr("canvasImg");//獲得base64碼,然後轉化一下
         if(canvasImg!="" && !canvasImg.equals("")){         canvasImg=canvasImg.substring("data:image/jpeg;base64,"  
                        .length()-1);
                }
                downExcle(canvasImg);//處理圖片方法
public File downExcle(String arrayData) {
        BufferedImage bufferImg = null;
        String name = "temp" + (int) (Math.random() * 100000) + ".xls";
        File f = new File(name);
        List<BufferedImage> images = new ArrayList<>();
        try {
            // 第一步,創建一個webbook,對應一個Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("sheet");
            // 畫圖的頂級管理器,一個sheet只能獲取一個(一定要注意這點)
            HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
             String savePathImg1 = "temp" + (int) (Math.random() * 100000)+ ".jpg";
            BASE64Decoder decoder = new BASE64Decoder();
            if (!"".equals(arrayData)) {

                byte[] b = decoder.decodeBuffer(arrayData);
                for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {// 調整異常數據
                        b[i] += 256;
                    }
                }
                // 生成圖片
                OutputStream out = new FileOutputStream(savePathImg1);
                out.write(b);
                out.flush();
                out.close();
                // 先把讀進來的圖片放到一個ByteArrayOutputStream中,以便產生ByteArray
                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                Image src = Toolkit.getDefaultToolkit().getImage(savePathImg1);
                bufferImg = this.toBufferedImage(src);// Image to BufferedImage
                ImageIO.write(bufferImg, "jpg", byteArrayOut);
                //這個是控制圖片大小,在excle的位置。前面四個參數不用修改,主要修改後面的參數
                HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0,
                        (short) 10, 0, (short) 25, 25);
                anchor.setAnchorType(3);
                // 插入圖片
                patriarch.createPicture(anchor, wb.addPicture(
                        byteArrayOut.toByteArray(),
                        HSSFWorkbook.PICTURE_TYPE_JPEG));
            }
            TtabColDefine tb = new TtabColDefine();
            tb.setColName("基準日期");
            // 動態獲得行業字段
            //List<String> tabCols = getTabCols("");
            // 設置列頭樣式
            //setTitleCellStyles(wb, sheet, tabCols);
            // 設置數據樣式
            //setDataCellStyles(wb, sheet);
            // 創建一行列頭數據
            //creatAppRowHead(sheet, 1, tabCols);
            // 填充行數據
            // creatRows(arrayData, sheet, tabCols);
            FileOutputStream fout = new FileOutputStream(f);
            wb.write(fout);
            fout.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return f;
    }

public  BufferedImage toBufferedImage(Image image) {  
    if (image instanceof BufferedImage) {  
        return (BufferedImage) image;  
    }  
    // This code ensures that all the pixels in the image are loaded  
    image = new ImageIcon(image).getImage();  
    BufferedImage bimage = null;  
    GraphicsEnvironment ge = GraphicsEnvironment  
            .getLocalGraphicsEnvironment();  
    try {  
        int transparency = Transparency.OPAQUE;  
        GraphicsDevice gs = ge.getDefaultScreenDevice();  
        GraphicsConfiguration gc = gs.getDefaultConfiguration();  
        bimage = gc.createCompatibleImage(image.getWidth(null),  
                image.getHeight(null), transparency);  
    } catch (HeadlessException e) {  
        // The system does not have a screen  
    }  
    if (bimage == null) {  
        // Create a buffered image using the default color model  
        int type = BufferedImage.TYPE_INT_RGB;  
        bimage = new BufferedImage(image.getWidth(null),  
                image.getHeight(null), type);  
    }  
    // Copy image to buffered image  
    Graphics g = bimage.createGraphics();  
    // Paint the image onto the buffered image  
    g.drawImage(image, 0, 0, null);  
    g.dispose();  
    return bimage;  
}

Highcharts導出圖片

highcharts是要獲得圖片的svg數據
var svg_line = $("#main").highcharts().getSVG();
也是放到隱藏域中,傳到後臺
後臺處理局部方法---------------------------
String svg_line = super.GetParameterStr("svg_line ");
String savePathImg = "temp"+ (int) (Math.random() * 100000) +".png";
                    convertToPng(svg_line , savePathImg);
                    Image src = Toolkit.getDefaultToolkit().getImage(
                            savePathImg);
                BufferedImage bufferImg = this.toBufferedImage(src);
                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                ImageIO.write(bufferImg, "png", byteArrayOut);
                //這個是控制圖片大小,在excle的位置。前面四個參數不用修改,主要修改後面的參數
                HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0,
                        (short) 0, 1, (short) 10, 18 );
                anchor.setAnchorType(0);
                // 插入圖片
                patriarch.createPicture(anchor, wb.addPicture(
                        byteArrayOut.toByteArray(),
                        HSSFWorkbook.PICTURE_TYPE_PNG));


/** 
     * 將svg字符串轉換爲png 
     *  
     * @param svgCode 
     *            svg代碼 
     * @param pngFilePath 
     *            保存的路徑 
     * @throws TranscoderException 
     *             svg代碼異常 
     * @throws IOException 
     *             io錯誤 
     */  
    public static void convertToPng(String svgCode, String pngFilePath) {  

        File file = new File(pngFilePath);  

        FileOutputStream outputStream = null;  
        try {  
            file.createNewFile();  
            outputStream = new FileOutputStream(file);  
            convertToPng(svgCode, outputStream);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (outputStream != null) {  
                try {  
                    outputStream.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  

    /** 
     * 將svgCode轉換成png文件,直接輸出到流中 
     *  
     * @param svgCode 
     *            svg代碼 
     * @param outputStream 
     *            輸出流 
     * @throws TranscoderException 
     *             異常 
     * @throws IOException 
     *             io異常 
     */  
    public static void convertToPng(String svgCode, OutputStream outputStream) {  
        try {  
            byte[] bytes = svgCode.getBytes("utf-8");  
            PNGTranscoder t = new PNGTranscoder();  
            TranscoderInput input = new TranscoderInput(  
                    new ByteArrayInputStream(bytes));  
            TranscoderOutput output = new TranscoderOutput(outputStream);  
            t.transcode(input, output);  
            outputStream.flush();  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (outputStream != null) {  
                try {  
                    outputStream.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  

html2canvas
引用個html2canvas.js

這裏也是生成base64碼,放到隱藏域中。處理方法和echarts一樣。但是圖片清晰度不是很好
var myImage='';
        html2canvas( $("#main") ,{ 
            onrendered: function(canvas){ 
             myImage = canvas.toDataURL();
            //動態生成input框 
            $("#dataval").val(myImage);
            } 
        }); 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章