最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Display byte array as PDF in browser with print button? - Stack Overflow

programmeradmin5浏览0评论

I am working on an application where I have to display PDF on browser. I am getting PDF byte array from third party via webAPI. One of the way i found out to display pdf is as below.

var pdfAsDataUri = "data:application/pdf;base64,"+byteArray;
window.open(pdfAsDataUri);

I don't like this approach because it displays base64 encoded format in URL, is there any other way to convert byte array into PDF and display in on HTML page along with the print dialog (window.print()).

I am working on an application where I have to display PDF on browser. I am getting PDF byte array from third party via webAPI. One of the way i found out to display pdf is as below.

var pdfAsDataUri = "data:application/pdf;base64,"+byteArray;
window.open(pdfAsDataUri);

I don't like this approach because it displays base64 encoded format in URL, is there any other way to convert byte array into PDF and display in on HTML page along with the print dialog (window.print()).

Share Improve this question edited Dec 20, 2016 at 7:08 Alexander O'Mara 60.6k19 gold badges172 silver badges181 bronze badges asked Dec 9, 2016 at 11:40 Manish MakkadManish Makkad 2371 gold badge6 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

In modern browsers, you can use a Blob to create an object URL which can then be used instead of a base64 URL (which has some limitations in different browsers, like length limits).

Here's a working example that does that. This sample displays the PDF inside an iframe, but you can really do whatever you want with that objectURL like open it in a new tab or whatever.

var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
    // Create the Blob URL:
    var buffer = xhr.response;
    var blob = new Blob([buffer], {
        type: 'application/pdf'
    });
    var objectURL = URL.createObjectURL(blob);

    // Create an iframe to demonstrate it:
    var iframe = document.createElement('iframe');
    iframe.className = 'sample-iframe';
    iframe.src = objectURL;
    document.body.appendChild(iframe);
    console.log(objectURL);
};
xhr.open('GET', 'https://gist.githubusercontent./AlexanderOMara/4cd0ae77a3027a8363eecb5929b30ee3/raw/900734831709f3cb94718649ca8f7f9715adeb78/hello-world.pdf', true);
xhr.send();
html, body {
  width: 100%;
  height: 100%;
}  
.sample-iframe {
  width: 90%;
  height: 90%;
}

Of course, the browser's built-in print function for the PDF will work also.

发布评论

评论列表(0)

  1. 暂无评论