使用 JavaScript 在客户端将 base64 字符串保存为 PDF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11415665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:46:15  来源:igfitidea点击:

Save base64 string as PDF at client side with JavaScript

javascriptinternet-explorerfirefoxpdfbase64

提问by owsata

So here my problem: I have a pdf file as a base64 String that i am getting from the server. I would like to use this string to either display the PDF directly to the browser or give it a option of "Save as..." when clicking on a link. Here the code i am using:

所以这里是我的问题:我有一个 pdf 文件作为我从服务器获取的 base64 字符串。我想使用此字符串直接向浏览器显示 PDF 或在单击链接时为其提供“另存为...”选项。这是我正在使用的代码:

<!doctype>
<html>
<head>
   <title>jsPDF</title>
   <script type="text/javascript" src="../libs/base64.js"></script>
   <script type="text/javascript" src="../libs/sprintf.js"></script>
   <script type="text/javascript" src="../jspdf.js"></script>

       <script type="text/javascript">

        function demo1() {
            jsPDF.init();
            jsPDF.addPage();
            jsPDF.text(20, 20, 'Hello world!');
            jsPDF.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');

            // Making Data URI
            var out = jsPDF.output();
            var url = 'data:application/pdf;base64,' + Base64.encode(out);

            document.location.href = url;
         }
    </script>
</head>
<body>

<a href="javascript:demo1()">Run Code</a>

</body>
</html>

Its working fine with Chrome and Safari. Firefox does recognize the pdf but does not display it as FF requires extensions to be present but the data-URI has none in this case. The reason I'm insisting here, if chrome and safari get it to work, then there has to be a solution for FF and IE

它适用于 Chrome 和 Safari。Firefox 确实识别 pdf,但不会显示它,因为 FF 需要存在扩展名,但在这种情况下数据 URI 没有。我在这里坚持的原因,如果 chrome 和 safari 让它工作,那么必须有一个 FF 和 IE 的解决方案

I know there are a few relevant questions to this but not really the exact one and now also a bit old ones. I know a workaround would be to have the pdf generated at server side but I would like to generate it at client side.

我知道有一些相关的问题,但不是真正的确切问题,现在也有点旧。我知道一种解决方法是在服务器端生成 pdf,但我想在客户端生成它。

So please intelligent folks, is it possible through some hacks or additional JS download plugins?

所以请聪明的人,是否有可能通过一些黑客或额外的 JS 下载插件?

回答by Gabriel C

You can create an anchor like the one showed below to download the base64pdf:

您可以创建一个如下所示的锚点来下载base64pdf:

<a download=pdfTitle href=pdfData title='Download pdf document' />

where pdfDatais your base64 encoded pdf like "data:application/pdf;base64,JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBvYmoKPDwvTGVuZ3RoIDMgMCBSL0ZpbHRlci9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nO1cyY4ktxG911fUWUC3kjsTaBTQ1Ytg32QN4IPgk23JMDQ2LB/0+2YsZAQzmZk1PSPIEB..."

其中pdfData是您的base64编码的PDF像“数据:应用程序/ PDF格式; BASE64,JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBvYmoKPDwvTGVuZ3RoIDMgMCBSL0ZpbHRlci9GbGF0ZURlY29kZT4 + CnN0cmVhbQp4nO1cyY4ktxG911fUWUC3kjsTaBTQ1Ytg32QN4IPgk23JMDQ2LB / 0 + 2YsZAQzmZk1PSPIEB ......”

回答by Denys Séguret

You should be able to download the file using

您应该能够使用下载文件

window.open("data:application/pdf;base64," + Base64.encode(out));

回答by Ka0s

I know this question is old, but also wanted to accomplish this and came across it while looking. For internet explorer I used code from hereto save a Blob. To create a blob from the base64 string there were many results on this site, so its not my code I just can't remember the specific source:

我知道这个问题很老,但也想完成这个并且在看的时候遇到了它。对于 Internet Explorer,我使用这里的代码来保存 Blob。要从 base64 字符串创建一个 blob,这个站点上有很多结果,所以它不是我的代码,我只是不记得具体的来源:

function b64toBlob(b64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 512;
    b64Data = b64Data.replace(/^[^,]+,/, '');
    b64Data = b64Data.replace(/\s/g, '');
    var byteCharacters = window.atob(b64Data);
    var byteArrays = [];

    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        var slice = byteCharacters.slice(offset, offset + sliceSize);

        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        var byteArray = new Uint8Array(byteNumbers);

        byteArrays.push(byteArray);
    }

    var blob = new Blob(byteArrays, {type: contentType});
    return blob;

Using the linked filesaver:

使用链接的文件保护程序:

if (window.saveAs) { window.saveAs(blob, name); }
    else { navigator.saveBlob(blob, name); }

回答by adnan javed

you can use this function to download file from base64.

您可以使用此功能从 base64 下载文件。

function downloadPDF(pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "abc.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();}

This code will made an anchor tag with href and download file. if you want to use button then you can call click method on your button click.

此代码将使用 href 和下载文件制作一个锚标记。如果要使用按钮,则可以在单击按钮时调用 click 方法。

i hope this will help of you thanks

我希望这会帮助你谢谢

回答by Hoang Tran Son

You will do not need any library for this. JavaScript support this already. Here is my end-to-end solution.

为此,您不需要任何库。JavaScript 已经支持这一点。这是我的端到端解决方案。

const xhr = new XMLHttpRequest();
xhr.open('GET', 'your-end-point', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.responseType = 'blob';
xhr.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
       if (window.navigator.msSaveOrOpenBlob) {
           window.navigator.msSaveBlob(this.response, "fileName.pdf");
        } else {
           const downloadLink = window.document.createElement('a');
           const contentTypeHeader = xhr.getResponseHeader("Content-Type");
           downloadLink.href = window.URL.createObjectURL(new Blob([this.response], { type: contentTypeHeader }));
           downloadLink.download = "fileName.pdf";
           document.body.appendChild(downloadLink);
           downloadLink.click();
           document.body.removeChild(downloadLink);
        }
    }
};
xhr.send(null);

This also work for .xlsor .zipfile. You just need to change file name to fileName.xlsor fileName.zip. This depends on your case.

这也适用于.xls.zip文件。您只需要将文件名更改为fileName.xlsfileName.zip。这取决于你的情况。