I have trouble integrating pdf.js into an Android Ionic application. I want pdf.js to render a pdf to a prepared canvas.
The problem occurs when I am trying to load the document using:
PDFJS.getDocument(FILE_PATH)
which always ends up with an error. I did some research, there are a lot of questions on SO and the internet on loading files to pdf.js but either they discuss loading pdfs from server, not file://
urls, or they propose some changes in native android code, which I would like to avoid: if possible I am looking for a pure JS cordova solution, or a plugin.
I tried experimenting with PDFJS.disableWorker
. Setting this to false results in cannot read property 'length' of null
, setting to true results in errors while loading the file that xhr
request couldn't load the file.
I should have all the necessary read permission set in the configuration file.
My question is, if anyone successfully loaded a local (file://..
) pdf into a cordova application using pdf.js, preferably using JS or a plugin, because I would like to expand to other platforms, if possible.
Thanks
As user async5 pointed out, PDFJS.getDocument()
accepts input in 3 different formats. Apart from URL, it also accepts Uint8Array
data. So two more steps are needed to get file in desired format, first is to load the file as array buffer and the second is to convert it to Uint8Array. Following is working, pure JS example for Ionic, using Cordova File plugin:
$cordovaFile.readAsArrayBuffer(DIRECTORY_URL, FILENAME).then(function(arraybuffer) { //DIRECTORY_URL starts with file://
var uInt8Arr = new Uint8Array(arraybuffer);
PDFJS.getDocument(uInt8Arr).then(function(pdf) {
//do whatever you want with the pdf, for example render it using 'pdf.getPage(page) and page.render() functions
}, function (error) {
console.log("PDFjs error:" + error.message);
});
}, function(error){
console.log("Load array buffer error:" + error.message);
});
this is an Cordova example, without using Ionic
window.resolveLocalFileSystemURI(FILE_URL, function(e){
e.file(function(f){
var reader = new FileReader();
reader.onloadend = function(evt) {
PDFJS.getDocument(new Uint8Array(evt.target.result)).then(function(pdf) {
//do whatever you want with the pdf, for example render it using 'pdf.getPage(page) and page.render() functions
}, function (error) {
console.log("PDFjs error:" + error.message);
});
};
reader.readAsArrayBuffer(f);
});
}, function(e){
console.log("error getting file");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With