使用 JavaScript 在客户端将 base64 字符串保存为 PDF [英] Save base64 string as PDF at client side with JavaScript

查看:51
本文介绍了使用 JavaScript 在客户端将 base64 字符串保存为 PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

<!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>

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

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

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

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.

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

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

推荐答案

您可以创建如下所示的锚点来下载 base64 pdf:

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

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

其中的 pdfData 是base64编码的PDF等的 数据:应用/PDF; BASE64,JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBvYmoKPDwvTGVuZ3RoIDMgMCBSL0ZpbHRlci9GbGF0ZURlY29kZT4 + CnN0cmVhbQp4nO1cyY4ktxG911fUWUC3kjsTaBTQ1Ytg32QN4IPgk23JMDQ2LB/0 + 2YsZAQzmZk1PSPIEB ..."

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

这篇关于使用 JavaScript 在客户端将 base64 字符串保存为 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆