How can I set the filename for base64 pdf in ifram

2019-04-29 04:18发布

问题:

I have a report PDF in base64, I want to show the file embedded in the HTML page. To do this I use the iFrame and works, but the problem is that I can't set the name of the PDF so that when downloaded it will be saved with the name assigned.

Can I set the filename?, if yes, how can I do it?

this is my code:

var iFrameBlock = $("<iframe>").attr({
      "src": base64file_encode,
      "width": "100%",
      "height": "100%",
      "frameborder": "0"
});

$("#previewPDF").html(iFrameBlock);
The result: Preview of PDF

And when I try download the file, the name to be saved is "download.pdf" Save dialog

I tried differents ways, but do not work either:

  1. Adding attribute download="filename.pdf"

       
       var iFrameBlock = $("<iframe>").attr({
          "src": base64file_encode,
          "width": "100%",
          "height": "100%",
          "frameborder": "0",
          "download": "filename.pdf"
       });
       
       

  2. I tried to change the value inside the iframe, but I could find the correct attribute and the Chrome denied the action.

       
       var iframe = $("iframe")[0];
       var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
       //here I suppose is the label of the filename
       $(iframeDocument).find("viewer-pdf-toolbar");
       
       

However, I want prevent use any other library.

Thank you for your time

回答1:

The iframe element can't do that, but as an alternative you can add anchor tag.

var iFrameBlock = $("<iframe>").attr({
    "id": "iframe",
    "src": base64file_encode,
    "width": "100%",
    "height": "100%",
    "frameborder": "0"
});
var aTag = $("<a>Dwonload</a>").attr({
    "href": base64file_encode,
    "download": "yourName.pdf"
});
$("#previewPDF").html(iFrameBlock);
aTag.insertAfter($("#iframe"));

Regards, KJ.