1

我正在尝试使用 PDFjs 在 Cordova iOS(可能还有后来的 Android)中显示 PDF。似乎 PDFjs 需要从网络服务器提供的文件才能使用其正常的加载功能,但它会接受编码为 Uint8Array 的 PDF。

我试图使用 Cordova 的FileAPI方法,它具有加载到 Uint8Array 的方法来加载可以从Documents文件夹加载的 PDF,但据我所知,API 似乎无法访问www.

PDF 最初需要与应用程序捆绑在一起,如果它们不同步,则需要通过应用程序进行更新,所以我希望能够将它们作为源的一部分,然后将它们复制到 Documents 文件夹中可操作/可重写。

如何将文件www夹中的文件复制到Documents文件夹中?我想这是一个常见的场景,但在网上找到这样的例子时遇到了麻烦。

任何帮助表示赞赏。

里卡德

更新

到目前为止,我已经能够使用文件传输从单独的网络服务器下载文件:

var fileTransfer = new FileTransfer();

fileTransfer.download(
    'http://localhost:8080/data/output8.pdf',// This is a webserver I am running
    _fileSystem.root.fullPath+'/output8.pdf',
    function(entry) {
        console.log("download complete: " + entry.fullPath);
    },
    function(error) {
        console.log("download error source " + error.source);
        console.log("download error target " + error.target);
        console.log("upload error code" + error.code);
    }
);

因此,如果我想从远程服务器下载所有 PDF,但我需要从www文件夹中下载它们,而且我似乎找不到执行此操作的路径,那就太好了。我试过了file:///data/output8.pdfdata/output8.pdf/data/output8.pdf

引用这些路径的正确方法是什么?

更新 2 - 死胡同无法保存为二进制文件

所以我仍然坚持几个小时后。我已经正确渲染了 PDFjs,但仅来自我从网络服务器提供的文件,然后 FileTransfer 到本地文件系统,而不是我与应用程序捆绑在一起的文件。我设法使用 XHR 将文件从 www 加载到 ArrayBuffer 但无法保存。

var xhr = new XMLHttpRequest();
xhr.open('GET','data/output8.pdf',true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e){
    var itWorked=this.status==0&&(this.response instanceof ArrayBuffer);
    console.log(itWorked?'looks like it worked':'hmm there was an issue: '+this.status);
    var myArrayBuffer = this.response;

    theFileSystem.root.getFile('output8.pdf',{create:true},function(entry){
        entry.createWriter(function(fileWriter){
          fileWriter.onwrite = function(){
            console.log('file has been written');
          };
            // Turns out the following does not work in 
            // Cordova which cannot write binary to a file.
            var blob = new Uint8Array(myArrayBuffer);
        fileWriter.write(blob);//Doesnt work
    },fail);
    },fail);                
}
xhr.ontimeout=function(e){
    console.log('timeout');
}
xhr.send();
4

2 回答 2

2

经过一夜好眠后,我设法解决了这个问题。解决方案是确定相对绝对路径,然后将路径 URL编码如下:

var fileTransfer = new FileTransfer();
var relativeFileLocation = 'data/output8.pdf';
var fileSystemFileLocation = '/output8.pdf';
var docsPath = fileSystem.root.fullPath;
var wwwPath = docsPath.substring(0, docsPath.lastIndexOf('/'))+'/testios27.app/www/'
var filePath = wwwPath+relativeFileLocation;
fileTransfer.download(
    'file://'+encodeURI(filePath),
    theFileSystem.root.fullPath+'/output8.pdf', // Ouput path
    onTransferComplete,
    fail);

主要存在的问题是路径可能需要针对不同的平台进行不同的计算。

于 2013-05-24T00:09:29.700 回答
0

回答 michal 如何获得完整路径。

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;  window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);function gotFS(fileSystem) {
alert("entered gotFS: " + fileSystem.root.fullPath);
}
于 2015-09-07T14:10:22.637 回答