当前位置: 移动技术网 > 移动技术>移动开发>Android > phonegap教程使用jspdf库在应用中生成pdf文件(pdf生成方法)

phonegap教程使用jspdf库在应用中生成pdf文件(pdf生成方法)

2019年07月24日  | 移动技术网移动技术  | 我要评论

首先在命令行创建一个phonegap工程

复制代码 代码如下:

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阅读器中。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网