简体   繁体   中英

Phonegap/jsPDF issue saving html as pdf

I'm not a massive javascript/jquery user but I've started to get more into it for use in mobile apps... I've been looking for an answer to solve my problem of getting a blank page when trying to output html as a pdf using jspdf and every post I find has something to do with blobs.

this is my code I have that exports a blank pdf I have left the pdf.save in so I get an export on my PC as a sample of what it should look like but on my ipad and nexus 7 it saves a blank pdf.

var pdf = new jsPDF('p', 'pt', 'letter'), source = $('#home')[0], specialElementHandlers = {
    '#bypassme': function(element, renderer){
        return true
    }
}
margins = {top: 80,bottom: 60,left: 40,width: 522};
pdf.fromHTML(source, margins.left, margins.top, {
    'width': margins.width // max width of content on PDF
    , 'elementHandlers': specialElementHandlers
},
function (dispose) {
    pdf.save('home.pdf');
    console.log( pdfOutput );

    var pdfOutput = doc.output();
    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) {
             alert("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 );
        });
  },
    margins
    )

Could someone give me a tip or point me in the right direction on how to incorporate your solution into my coding so I can save html formatting & images?

I just had this same issue. Here's what I did to solve it.

Replace the line

writer.write( pdfOutput );

with this:

var data = pdfOutput;
var buffer = new ArrayBuffer(data.length);
var array = new Uint8Array(buffer);
for (var i = 0; i < data.length; i++) {
  array[i] = data.charCodeAt(i);
}
writer.write(buffer);

Not 100% sure that I understand what's happening, but from what I have been researching, you need to convert the output from jsPDF to an ArrayBuffer before writing to the file.

@AdilWaqar I apologise for the delay in my response, I have been moving house. Below I have included the full javascript I finished on to get pdf printing working. it works perfect in android & IOS but the issue with IOS is that once the pdf has been generated you cannot gain access to it via a file manager.

The localStorage was used for storage before output, it has same id name on the span fields in the output html for that specific section, for example section 3 in the javascript had some signatures and some text boxes to output, the localStorage for one textfield in the output is...

getItem('cwiRiskAccesAsessName')

the html output is...

<tr><td>Assessor Name:</td><td><span id="EXPcwiRiskAccesAsessName"></span></td></tr>

I used jquery to pre-populate the span fields by building the html ready for output and adding a prefix to the id of each item, once done I used this simple line to deal with auto population on keyup. note: ignore 'inpt' in onkeyup, that was for a prefix within another part of the data handling function

onKeyUp="dataHandling(this,1,'inpt');"
var saveData = localStorage.setItem(source.id,source.value);var getData = localStorage.getItem(source.id);$("#EXP"+source.id).text(getData);

Below is the full pdf output javascript

 /* STORAGE-OUTPUT */ function storageOutput(){for (var i = 0; i < localStorage.length; i++){ /* do something with localStorage.getItem(localStorage.key(i));*/ $("#storageHolder").append(localStorage.key(i)+'<br/>');} } /* SETUP */ function setup(){ window.requestFileSystem(LocalFileSystem.PERSISTENT,0,onRequestFileSystemSuccess,null); function onRequestFileSystemSuccess(fileSystem){ var entry=fileSystem.root;entry.getDirectory("MAIN-DIRECTORY",{create:true,exclusive:false},onGetDirectorySuccess,onGetDirectoryFail); } function onGetDirectorySuccess(dir){} function onGetDirectoryFail(error){ alert('Directory Setup Fail');} }/*CLEAR LOCALSTORAGE*/function clearLS(){ localStorage.clear();alert(localStorage.length); } function savePDF(id,filename) { var folderName = 'MAIN-DIRECTORY/'+localStorage.getItem('householderAddress')+', '+localStorage.getItem('householderPostcode'); var saveData = localStorage.setItem('saveLocation',folderName); var getData = localStorage.getItem('saveLocation'); window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onRequestFileSystemSuccess, null); function onRequestFileSystemSuccess(fileSystem) { var entry=fileSystem.root; entry.getDirectory(getData, {create: true, exclusive: false}, onGetDirectorySuccess, onGetDirectoryFail); } function onGetDirectorySuccess(dir){} function onGetDirectoryFail(error){} if(id==1){ var pdf = new jsPDF('p', 'pt', 'a4'),source = $('#savesec1')[0] , specialElementHandlers = { '#bypassme': function(element, renderer){ return true } } } else if (id==2){ var pdf = new jsPDF('p', 'pt', 'a4'),source = $('#savesec2')[0] , specialElementHandlers = { '#bypassme': function(element, renderer){ return true } } } else if (id==3){ var pdf = new jsPDF('p', 'pt', 'a4'),source = $('#savesec3')[0] , specialElementHandlers = { '#bypassme': function(element, renderer){ return true } } } margins = {top: 40,bottom: 60,left: 40,width: 522}; pdf.fromHTML(source, margins.left, margins.top, { 'width': margins.width // max width of content on PDF , 'elementHandlers': specialElementHandlers }, function(dispose){ /*SECTION 2*/ if(id==2){ pdf.addImage(localStorage.getItem('householderSig1'),'PNG',135,270,150,50);pdf.addImage(localStorage.getItem('assessSig1'),'PNG',135,410,150,50); } /*SECTION 3*/ else if(id==3){ pdf.addPage();pdf.setFontSize(15);pdf.setFontType("normal");pdf.text(20,30,'Assessor Name: '+localStorage.getItem('cwiRiskAccesAsessName'));pdf.text(20,45,'Assessor Agency: '+localStorage.getItem('cwiRiskAccesAsessAgency'));pdf.text(20,60, 'Date: '+localStorage.getItem('assessSig3Date'));pdf.text(20,75, 'Assessor Signature: ');pdf.addImage(localStorage.getItem('assessSig3'),'PNG',20,85,250,100);pdf.addPage();pdf.setFontSize(25);pdf.setFontType("normal");pdf.text(20,40,'Plan View:');pdf.addImage(localStorage.getItem('drawingOutput'),'PNG',20,40,500,500);pdf.addPage();pdf.setFontSize(15);pdf.setFontType("normal");pdf.text(20,30,'Front Elevation: '+localStorage.getItem('cwiRiskFrontNotes'));pdf.text(20,430,'Rear Elevation: '+localStorage.getItem('cwiRiskRearNotes'));pdf.addImage(localStorage.getItem('cwiRiskFrontOutput'),'PNG',40,40,500,350);pdf.addImage(localStorage.getItem('cwiRiskRearOutput'),'PNG', 40, 440, 500, 350);pdf.addPage();pdf.setFontSize(15);pdf.setFontType("normal");pdf.text(20,30,'Left Side Elevation: '+localStorage.getItem('cwiRiskLeftNotes'));pdf.text(20,430,'Right Side Elevation: '+localStorage.getItem('cwiRiskRightNotes'));pdf.addImage(localStorage.getItem('cwiRiskLeftOutput'),'PNG',40,40,500,350);pdf.addImage(localStorage.getItem('cwiRiskRightOutput'),'PNG',40,440,500,350); } /* GENERIC IMAGE OUTPUT pdf.addImage(imgData, 'PNG', 40, 400, 400, 160); pdf.addImage(imgData, 'PNG', 40, 600, 400, 160); for (var i=0;i<dataSources.length;i++){ pdf.addPage(); alert(dataSources[i].text); } pdf.save(filename+'.pdf');*/ var pdfOutput = pdf.output(); //console.log( pdfOutput ); window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) { fileSystem.root.getFile(getData+'/'+filename+'.pdf', {create: true}, function(entry) { var fileEntry = entry; //console.log(entry); entry.createWriter(function(writer) { writer.onwrite = function(evt) { alert("PDF Saved Successfully"); }; console.log("writing to file"); var data = pdfOutput; var buffer = new ArrayBuffer(data.length); var array = new Uint8Array(buffer); for (var i = 0; i < data.length; i++) { array[i] = data.charCodeAt(i); } writer.write(buffer); }, function(error) { alert(error); }); }, function(error){ console.log(error); }); }, function(event){ console.log( evt.target.error.code ); }); }, margins ) } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM