jsPDF和cordova无法查看pdf文件

jsPDF and cordova Cant view the pdf file

我正在尝试为我的应用程序生成 PDF 发票,我可以转到 'console.log ("write success");' 行,但我就是找不到该文件。请帮忙!!!我怎样才能将它保存到我手机的文件夹中???

console.log("generating pdf...");
var doc = new jsPDF();

doc.text(20, 20, 'HELLO!');

doc.setFont("courier");
doc.setFontType("normal");
doc.text(20, 30, 'This is a PDF document generated using JSPDF.');
doc.text(20, 50, 'YES, Inside of PhoneGap!');

var pdfOutput = doc.output();
console.log( pdfOutput );

//NEXT SAVE IT TO THE DEVICE'S LOCAL FILE SYSTEM
console.log("file system...");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {

   console.log(fileSystem.name);
   console.log(fileSystem.root.name);
   console.log(fileSystem.root.fullPath);



fileSystem.root.getFile("test.pdf", {create: true}, function(entry) {
      var fileEntry = entry;
      console.log(entry);

      entry.createWriter(function(writer) {
         writer.onwrite = function(evt) {
         console.log("write success");
      };

      console.log("writing to file");
         writer.write( pdfOutput );
      }, function(error) {
         console.log(error);
      });

   }, function(error){
      console.log(error);
   });
},
function(event){
 console.log( evt.target.error.code );

您正在将文件保存在系统的根路径中。

如果要select文件夹,请勾选cordova file plugin

因此,如果您想要 select 一个 public 文件夹,以便您可以在您的应用之外检查您的文件,请检查此 link

https://github.com/apache/cordova-plugin-file#android-file-system-layout

然后选择 private = no.

例如:

window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {
          dir.getFile("test.pdf", {create: true, exclusive: false}, function (fileEntry) {
            fileEntry.createWriter(function (writer) {
writer.onwrite = function(evt) {
         console.log("write success");
      };

      console.log("writing to file");
         writer.write( pdfOutput );
      }

            },function () {


              console.log("ERROR SAVEFILE");

            });
          });
        });

并且你的文件会放在你的sdcard/files目录下

关于打开它,我假设您没有任何 pdf 查看器插件,因此 inAppBrowser 是无需使用任何插件的解决方案,并在您的应用程序中打开它

安装inAppBrowser

并打开它:

window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {


          dir.getFile(filename, {create:false}, function(fileEntry) { //EXISTS
            var url = "file:/" + cordova.file.externalDataDirectory + "/test.pdf";
            window.open(url, '_blank');
          }, function() { //NOT EXISTS

          });
        });

我还没有测试过,看起来inAppBrowser 不喜欢太多的本地文件。请post你的结果

我觉得下面一行可能是问题所在,"window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {})"

在我阅读的一些帖子中,提到 requestfilsystem 方法和 LocalFileSystem.PERSISTENT 参数在 android 中不起作用,除非设备已获得 root 权限。

我使用 - "window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory,successCallback, errorCallback);"

让它工作

我建议你看看这个 我在 Android 和 iOS 设备上发布了相同的文件创建代码。

此外,如果您想在您选择的应用程序中打开 PDF,您可以使用 cordova 文件打开器插件。您可以在下面的

中查看文件打开器示例代码