Export Excel, PDF and download pictures

Created: 2020-03-16; test: chrome v80.0.3987.122 normal

Export Excel (use xlsx)

  • Installation package introduced xlsx import XLSX from 'xlsx/dist/xlsx.mini.min.js';

The principle: a description thereof will JSON conversion table according to the protocol for the spreadsheet zip compressed character, then through a series of methods to convert it to Blob URL; (principles related code below)

function blobify(strData) {
    var buf = new ArrayBuffer(strData.length), view = new Uint8Array(buf);
    for (var i=0; i!=strData.length; ++i) view[i] = strData.charCodeAt(i) & 0xFF;
    return buf;
}
var excelBlob = new Blob([blobify(data)], {type:"application/octet-stream"});
var blobURL=URL.createObjectURL(excelBlob);

Related business codes are as follows:

exportData = () => {
    /**
     * @des 生成excel
     * @param { Array } data ([[name, score],['hew', 80]]) 
     * @param { String } name 表格名称
     */
    const fn = (data, name) => {
        name = name || 'table';
        /** 设置文件名以及格式, 默认xlsx */
        const filename = /\./.test(name) ? name : `${name}.xlsx`;
        /** Excel第一个sheet的名称 */
        const wsName = 'sheet'; 
        const newBook = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet(data);
        /** 将数据添加到工作薄 */
        XLSX.utils.book_append_sheet(newBook, ws, wsName);  
        XLSX.writeFile(newBook, filename);
    }

    fn([
        ['h1','h2','h3', 'h4'], 
        [1,2,3,4],
        [true, false, null, 5],
        [true, false, null, '中文'],
    ], '表格')
}

Export PDF

  • Introducing jspdf and html2canvas

import * as jsPDF from 'jspdf'

import html2canvas from 'html2canvas';
html2canvas principle is to read the DOM, and draw on the canvas according to the rules, but some css styles can not be achieved

  • The main code
 html2canvas(document.querySelector('.need-pdf')).then((canvas) => {
    let canvasWidth = canvas.width
    let canvasHeight = canvas.height
    // a4纸的尺寸[595.28,841.89]
    let pageHeight = canvasWidth / 592.28 * 841.89
    let imgWidth = 595.28
    let imgHeight = 592.28 / canvasWidth * canvasHeight
    let pageData = canvas.toDataURL('image/jpeg', 1.0)

    let pdf = new jsPDF('', 'pt', 'a4')
    if (canvasHeight < pageHeight) {
        // 参数说明:图片数据,格式,距左边距,距上边距,图宽,图高,...(其它参数)  这里的单位都和上面创建pdf实例时一致
        pdf.addImage(pageData, 'JPEG', 20, 0, imgWidth, imgHeight)
    } else {
        // 分页操作,以下操作方式较为粗糙,分页处直接分割内容 
        let theRestHeight = canvasHeight;
        let y = 0;
        while (theRestHeight > 0) {
            // 原理是将同一张图放在不同页面,但上移不同的距离,实现分页
            pdf.addImage(pageData, 'JPEG', 0, y, imgWidth, imgHeight)
            theRestHeight -= pageHeight
            y -= 841.89
            if (theRestHeight > 0) {
                pdf.addPage()
            }
        }
    }
    pdf.save('table.pdf')
})

Download image

  • Use a label

IE compatibility issues, must be a source picture (non-homologous will open in a new tab), download image format to keep property values

<a href="xxx" alt="no" download="new-name.jpg">下载图片</a>
  • If it is put cdn or image server (server is also set to allow cross-domain)
const canvasEle = document.createElement('canvas');
const ctx = canvasEle.getContext('2d');

const imgEle = new Image();
imgEle.setAttribute('crossOrigin', 'anonymous'); 
imgEle.onload = function() {
    canvasEle.width = this.width;
    canvasEle.height = this.height;
    ctx.drawImage(this, 0 , 0, this.width, this.height);

    const aEle = document.createElement('a');
    aEle.setAttribute('href', canvasEle.toDataURL('image/jpeg'));
    aEle.setAttribute('download', 'cross.jpg');
    aEle.click();
}
imgEle.src = 'xxx.jpg';
  • Use ajax request to also as above, but does not need to be compatible crossOrigin
function dl() {
    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
        var url = URL.createObjectURL(this.response);
        var img = new Image();
        img.onload = function () {
            const aEle = document.createElement('a');
            aEle.setAttribute('href', canvasEle.toDataURL('image/jpeg'));
            aEle.setAttribute('download', 'cross.jpg');
            aEle.click();
            // 释放内存
            URL.revokeObjectURL(url);
        };
        img.src = url;
    };
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.send();
}

Welcome to exchange Github

Guess you like

Origin www.cnblogs.com/he-wei/p/12502827.html