<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>base64转pdf</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <!-- <style>
        iframe {
            height: 800px;
            width: 800px
        }
    </style> -->


</head>

<body>
    <div>
        <a class="down" href=""></a>
    </div>
    <button onclick="myFunction()">download Img</button>

    <button onclick="myFunction2()">download pdf </button>
</body>
<script>

    function myFunction() {
        let base64 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA8CAMAAAANIilAAAAAWlBMVEUAAACxRCuxRCuxRCuxRCuxRCuxRCuxRCu+YkvCbFaxRCuxRCuxRCu1TjbLgGvcqZXpx7X25dXHdmDgs6CxRCvt0cCxRCuxRCuxRCvy28rYn4vUlYDlvavPinWNi1WmAAAAGXRSTlMAMHCfv/9Q7///EIDf/0D/jyDPE4UYLgAAAa9JREFUeAHUlVWiKyEUBBlp3InL/pf5NMKJDbme+i+0adhtun4YcWAc+o41wweBP0j1D4k/iIG3mNpYwPkQ04kYsgOs0VOuEUAu6YqSAWEeqjML+Hm6ydwDdnZ/xQsgU5XqGVjcWftyBVfSQ4rDannL7QTUOk2wVhDdTdenBjyxT+4mNbG5speV22CTfesVfGrGY6UreQGVnkBhUWUDbv2MvHY4p8WipKcosKc8I6eKkB2ukBuytoxDzrVAlckocRu3rZMKoQ8T+2pa3IUE0B+mtvXEeMSunvrfrjnZ8UbdJ6/JrvkfeUBJb6Bg+CMLR65wq06kf+zVkS2xnWCso/e0xZljnE4QO6NjPQJN3gNZkTigZwPi2+SIgY1Ib5MTRgb5VlmCQd2UCbdl9W1yfqllE1m+VZZgI94qY7wZT8qDePYIb5APD6NDfpuc0R3K4A2yE7SGmmRSQxz5LXIGp9XbJJPqpaXfKnuY6+9miweE6++GfnRhe5fyu/Q6JAAAgIEQ2OH7h52eQlwKjhc6SyzEXVihoAFKAeKAjwZXIDNgHTYBB6XXaL1GPWWLKYMdPI0QlJmGcQ+vAAAAAElFTkSuQmCC';
        function dataURLtoBlob(dataurl) {
            var arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], { type: mime });
        }
        //调用
        let blob = dataURLtoBlob(base64);
        let link = document.createElement('a')
        link.download = 'abc.pdf' // 要下载的文件名
        link.href = URL.createObjectURL(blob);
        // 触发点击
        document.body.appendChild(link);
        link.click();
        // 然后移除
        document.body.removeChild(link);
    }

    /**
       * desc: base64对象转blob文件对象
       * @param urlData  :数据的base64对象
       * @param type  :类型 png,pdf,doc,mp3等;
       * @returns {Blob}:Blob文件对象
       */
    function base64ToBlob(urlData, type) {
        let arr = urlData.split(',');
        let array = arr[0].match(/:(.*?);/);
        let mime = (array && array.length > 1 ? array[1] : type) || type;
        // 去掉url的头,并转化为byte
        let bytes = window.atob(arr[1]);
        // 处理异常,将ascii码小于0的转换为大于0
        let ab = new ArrayBuffer(bytes.length);
        // 生成视图(直接针对内存):8位无符号整数,长度1个字节
        let ia = new Uint8Array(ab);
        for (let i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i);
        }
        return new Blob([ab], {
            type: mime
        });
    }

    /**
     * desc: 下载导出文件
     * @param blob  :返回数据的blob对象或链接
     * @param fileName  :下载后文件名标记
     * @param fileType  :文件类 word(docx) excel(xlsx) ppt等
     */
    function downloadExportFile(blob, fileName, fileType) {
        let downloadElement = document.createElement('a');
        let href = blob;
        if (typeof blob == 'string') {
            downloadElement.target = '_blank';
        } else {
            href = window.URL.createObjectURL(blob); //创建下载的链接
        }
        downloadElement.href = href;
        downloadElement.download = fileName + '.' + fileType; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //触发点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        if (typeof blob != 'string') {
            window.URL.revokeObjectURL(href); //释放掉blob对象
        }
    }

    /**
     * desc: base64转文件并下载
     * @param base64 {String} : base64数据
     * @param fileType {String} : 要导出的文件类型png,pdf,doc,mp3等
     * @param fileName {String} : 文件名
     */
    function downloadFile(base64, fileName, fileType) {
        let typeHeader = 'data:application/' + fileType + ';base64,' // 定义base64 头部文件类型
        let converedBase64 = typeHeader + base64;  // 拼接最终的base64
        let blob = base64ToBlob(converedBase64, fileType)  // 转成blob对象
        downloadExportFile(blob, fileName, fileType) // 下载文件
    }

    function myFunction2() {
        downloadFile("base64","123.pdf","pdf");
    }
</script>

</html>

 

posted on 2021-10-14 11:59  许一朵岁月  阅读(1815)  评论(0编辑  收藏  举报