The phonegap tutorial USES the jspdf library to generate the pdf file of pdf generation method in the application

  • 2020-05-24 06:06:19
  • OfStack

Start by creating an PhoneGap project on the command line


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

Then, download the JSPDF code download the JSPDF project code and copy the object code to the PhoneGap project directory. I put it under www/js. This file is then introduced in the main HTML file.


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

I used an uncompressed/minimized source file in the 'dist' directory.

Next we start generating the PDF file. The following code snippet USES PhoneGap's files to process API PhoneGap's File API to generate a simple PDF file and save it locally to the device. This should be the *AFTER* the deviceready incident.
console.log is only used for debugging:


//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 );
});

The PDF creation process is actually quite simple. You can simply use doc.output () to get the string identifier of the created file. Whether it is saved locally, sent to the server, or even sent directly to the PDF reader on the local device.


Related articles: