在cordova javascript中打开PDF

时间:2016-05-13 09:34:43

标签: javascript cordova cordova-plugins

我使用文件插件生成了PDF发票。现在我想在应用程序中打开该文件。我试过inAppBrowser,但它给了一个空页面。我尝试过fileopener,它没有给出成功或失败的消息。如何指定文件的路径。请帮助!!

在应用程序浏览器方法

var cdr='';
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {
cdr=dir;
alert("cdr "+cdr);
      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");

        });
      });
    });

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

alert("open file");
      dir.getFile("test.pdf", {create:false}, function(fileEntry) { //EXISTS

      alert("native url "+cdr.toNativeURL());
        var url =cdr.toNativeURL()  + "test.pdf";
        alert(url);
        window.open(url, '_blank');
      }, function() { //NOT EXISTS
 alert("no file found");
      });
    });

}

Fileopener方法

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

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


            },function () {


              console.log("vidhya ERROR SAVEFILE");

            });
          });
        });
    function openFile(cdr) {

    var fs;
    function fsSuccess(fileSystem)
    {
        fs = fileSystem;
        console.log("vidhya "+fs);
    }

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

    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fsSuccess, fsFail);


        console.log("vidhya opening file " +cdr.toNativeURL());
    cordova.plugins.fileOpener2.open(
       fs.root.toURL() +'test.pdf',
        "application/pdf", //mimetype
        {
            error: function(e) {
                alert("Error Opening the File.Unsupported document format.");
            },
            success: function() {
                // success callback handler
                alert("success");
            }
        }
    );
    }

我的文件已保存在/ internal storage / Android / Data / app_folder / files / test.pdf

2 个答案:

答案 0 :(得分:3)

这就是我在混合移动应用程序中运行的方式:

var cdr;
sessionStorage.platform = device.platform;
var fileTransfer = new FileTransfer();

if (sessionStorage.platform.toLowerCase() == "android") {
    window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, onFileSystemSuccess, onError);
} else {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onError);
}

function onError(e) {
    navigator.notification.alert("Error : Downloading Failed");
};

function onFileSystemSuccess(fileSystem) {
    var entry = "";
    if (sessionStorage.platform.toLowerCase() == "android") {
        entry = fileSystem;
    } else {
        entry = fileSystem.root;
    }
    entry.getDirectory("Cordova", {
        create: true,
        exclusive: false
    }, onGetDirectorySuccess, onGetDirectoryFail);
};

function onGetDirectorySuccess(dir) {
    dir.getDirectory("My_App", {
        create: true,
        exclusive: false
    }, onGetDirectorySuccess1, onGetDirectoryFail);
};

function onGetDirectorySuccess1(dir) {
    cdr = dir;
    dir.getFile(filename, {
        create: true,
        exclusive: false
    }, gotFileEntry, errorHandler);
};

function gotFileEntry(fileEntry) {
    var documentUrl = "http://myserverurl.com/test.pdf";
    var uri = documentUrl;
    fileTransfer.download(uri, cdr.nativeURL + docFileNameToView,
        function(entry) {
            openFile();
        },
        function(error) {
            navigator.notification.alert("Error");
        },
        false
    );
};

function openFile() {
    cordova.plugins.fileOpener2.open(
        cdr.nativeURL + docFileNameToView,
        'application/pdf', {
            error: function(e) {
                navigator.notification.alert("Error Opening the File.Unsupported document format.");
            },
            success: function() {

            }
        }
    );
};

function fail(error) {

    navigator.notification.alert("Error");
};

function errorHandler(e) {

    navigator.notification.alert("Error");
};

function onGetDirectoryFail(error) {

    navigator.notification.alert("Error");
};

此代码使用cordova文件传输插件下载pdf和文件开启器插件以查看pdf。此示例代码还使用设备插件获取设备平台(iOS或Android)和对话框插件以显示通知。

代码在iOS 9和Android 6设备上测试过,运行正常。在Android中,文件存储在storage/emulated/0/Cordova/My_App文件夹

答案 1 :(得分:2)

如果有人在打开存储在设备中的文件时遇到问题,即使指定了正确的目标文件路径,请确保正确下载文件而不会损坏。

由于下载不当或损坏,很多时候文件打开失败。您还可以使用chrome inspect devices option在下载过程中跟踪任何错误。还要确保使用最新版本的文件传输插件以避免下载错误。