在 PhoneGap 应用内部生成 PDF 文档


前段时间,有人问我能否在PhoneGap应用中生成pdf文件,答案是肯定的而且实现起来也很简单。我使用JSPDF这个标准的JavaScript类库来实现这个功能:

下面是示例:首先在命令行创建一个PhoneGap工程create a new PhoneGap project

加入控制台输出和写文件插件:

phonegap create . "jspdf.sample" "JSPDF App"
phonegap local plugin add org.apache.cordova.file
phonegap local plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-console.git

然后,下载JSPDF代码download the JSPDF project code, 将目标码拷贝到PhoneGap工程目录下。我放在 www/js下。然后,在main HTML文件中引入该文件。

<script type="text/javascript" src="js/jspdf.source.js"></script>

我用的是'dist'目录下未经压缩/最小化的源文件。

接下来我们开始生成PDF文件。下面的代码片段利用PhoneGap的文件处理 API PhoneGap's File API. 来生成一个简单的PDF文件并保存至设备的本地。这个应该算是*AFTER* the deviceready事件。

 

其中console.log只是为了调试使用:

//FIRST GENERATE THE PDF DOCUMENT
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 );
});

PDF创建过程其实很简单。只要使用doc.output()获取到已创建文件的字符串标识就能做相应的操作。不论是保存到本地,发送到服务器甚至是直接发送到本地设备上的PDF阅读器中.

更新更详细的资料可以从JSPDF open source project on GitHubonline examples 上获取到。

上面代码生成的PDF文件可以从这里获取You can download the sample PDF here

PhoneGap 的详细介绍:请点这里
PhoneGap 的下载地址:请点这里

推荐阅读:

Ubuntu 13.04 安装 Chrome 依赖问题解决

openSUSE安装Chrome浏览器

Ubuntu中Chrome浏览器方便的证书管理功能

CentOS 6.x 安装Google Chrome浏览器

相关内容