猿问

Pdf.js:使用base64文件源而不是url呈现pdf文件

我正在尝试使用pdf.js从pdf渲染页面


通常,使用网址,我可以这样做:


PDFJS.getDocument("http://www.server.com/file.pdf").then(function getPdfHelloWorld(pdf) {

  //

  // Fetch the first page

  //

  pdf.getPage(1).then(function getPageHelloWorld(page) {

    var scale = 1.5;

    var viewport = page.getViewport(scale);


    //

    // Prepare canvas using PDF page dimensions

    //

    var canvas = document.getElementById('the-canvas');

    var context = canvas.getContext('2d');

    canvas.height = viewport.height;

    canvas.width = viewport.width;


    //

    // Render PDF page into canvas context

    //

    page.render({canvasContext: context, viewport: viewport});

  });

});

但在这种情况下,我将文件放在base64而不是url:


data:application/pdf;base64,JVBERi0xLjUKJdDUxdgKNSAwIG9iaiA8PAovTGVuZ3RoIDE2NjUgICAgICAKL0ZpbHRlciAvRmxhdGVEZWNvZGUKPj4Kc3RyZWFtCnjarVhLc9s2...

怎么做到这一点?


手掌心
浏览 2840回答 3
3回答

慕森卡

根据示例,直接支持base64编码,虽然我自己没有测试过。获取你的base64字符串(从一个文件派生或用任何其他方法加载,POST / GET,websockets等),将其转换为带有atob的二进制文件,然后将其解析为PDFJS API上的getDocument,如PDFJS.getDocument({data: base64PdfData});Codetoffel,答案确实可以正常工作我虽然。

慕村225694

使用Accepted Answer对IE进行检查并将dataURI转换为UInt8Array; PDFJS接受的表格&nbsp; &nbsp; &nbsp; &nbsp; Ext.isIE ? pdfAsDataUri = me.convertDataURIToBinary(pdfAsDataUri): '';&nbsp; &nbsp; &nbsp; &nbsp; convertDataURIToBinary: function(dataURI) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var BASE64_MARKER = ';base64,',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; base64 = dataURI.substring(base64Index),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; raw = window.atob(base64),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rawLength = raw.length,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; array = new Uint8Array(new ArrayBuffer(rawLength));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (var i = 0; i < rawLength; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; array[i] = raw.charCodeAt(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return array;&nbsp; &nbsp; &nbsp; &nbsp; },
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答