简体   繁体   English

用Javascript下载PDF文件

[英]Download a PDF file in Javascript

I'd like to download a pdf file with javascript. 我想用javascript下载pdf文件。 The file content will be encoded in base64. 文件内容将以base64编码。

Please help me to investagate why I can't download the pdf file. 请帮助我调查为什么我无法下载pdf文件。

index.php: index.php:

<?php
    $file_content =  base64_encode(file_get_contents("1.pdf"));
?>
<!DOCTYPE>
<html>
    <head>
        <title>Download PDF </title>
    </head>

    <body>
        <div>Hello World!</div>
        <input type="button" onclick="download()" value="download"/>

        <script>
            function download() {
                var str = "<?php echo $file_content;?>";
                var a = document.createElement("a");
                document.body.appendChild(a);
                a.style = "display: none";
                var data = window.atob(str);
                var blob = new Blob([data], {type: "application/pdf"});
                var url = window.URL.createObjectURL(blob);
                a.href = url;
                a.download = "download.pdf";
                a.click();
                window.URL.revokeObjectURL(url);            
            }
        </script>
    </body>
</html>

Based on this Medium post , here's a solution that uses the base64 string directly: 根据此Medium帖子 ,这是一个直接使用base64字符串的解决方案:

function download() {
    var a = document.createElement("a");
    a.style = "display: none";
    a.href = "data:application/pdf;base64,<?= $file_content ?>";
    a.download = "download.pdf";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

Further reading: Data_URIs 进一步阅读: Data_URIs

download attribute will help you to download the file. download属性将帮助您下载文件。

var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));

Another possible solution: 另一个可能的解决方案:

If you want to download it using blob content than return response must be declared as arraybuffer 如果要使用blob内容下载它,则必须将return response声明为arraybuffer

Example: 例:

$http.post('/postmethod',{params}, {responseType: 'arraybuffer'})
   .success(function (data) {
       var file = new Blob([data], {type: 'application/pdf'});
       var fileURL = URL.createObjectURL(file);
       window.open(fileURL);
});

Open the PDF file into new window from where you can save it. 将PDF文件打开到新窗口,从中可以保存它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM