我正在尝试使用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...
如何做到这一点?
答案 0 :(得分:92)
http://mozilla.github.com/pdf.js/build/pdf.js
/**
* This is the main entry point for loading a PDF and interacting with it.
* NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
* is used, which means it must follow the same origin rules that any XHR does
* e.g. No cross domain requests without CORS.
*
* @param {string|TypedAray|object} source Can be an url to where a PDF is
* located, a typed array (Uint8Array) already populated with data or
* and parameter object with the following possible fields:
* - url - The URL of the PDF.
* - data - A typed array with PDF data.
* - httpHeaders - Basic authentication headers.
* - password - For decrypting password-protected PDFs.
*
* @return {Promise} A promise that is resolved with {PDFDocumentProxy} object.
*/
因此,标准的XMLHttpRequest(XHR)用于检索文档。 问题是XMLHttpRequests不支持数据:uris(例如data:application / pdf; base64,JVBERi0xLjUK ......)。
但是有可能将类型化的Javascript数组传递给该函数。 您唯一需要做的就是将base64字符串转换为Uint8Array。您可以使用https://gist.github.com/1032746
中的此功能var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
<强> TL;博士强>
var pdfAsDataUri = "data:application/pdf;base64,JVBERi0xLjUK..."; // shortened
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)
答案 1 :(得分:2)
According to the examples base64编码,但我自己没有对其进行过测试。获取你的base64字符串(从一个文件派生或用任何其他方法加载,POST / GET,websockets等),将其转换为带有atob的二进制文件,然后将其解析为PDFJS API上的getDocument,如PDFJS.getDocument({data: base64PdfData});
Codetoffel答案虽然确实对我有用。
答案 2 :(得分:0)
使用Accepted Answer对IE进行检查并将dataURI转换为UInt8Array; PDFJS接受的表格
{
"load" : 15.0,
"latitude" : 32.7874,
"longitude" : -96.7989
}