简体   繁体   English

Phonegap / jsPDF问题将html保存为pdf

[英]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. 我不是大量的javascript / jquery用户,但是我已经开始更多地将其用于移动应用程序中...我一直在寻找答案,以解决尝试输出html时出现空白页面的问题作为使用jspdf的pdf文件,我发现的每个帖子都与blob有关。

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. 这是我的代码,我导出了一个空白的pdf文件,但我保留了pdf.save的内容,因此我在PC上导出了该文件的外观,但在ipad和nexus 7上保存了一个空白的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? 有人可以给我提示或指导我如何将您的解决方案整合到我的编码中,以便我可以保存html格式和图像吗?

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. 不能100%地确定我了解正在发生的事情,但是根据我的研究,您需要在写入文件之前将jsPDF的输出转换为ArrayBuffer。

@AdilWaqar I apologise for the delay in my response, I have been moving house. @AdilWaqar我对回复的延迟表示歉意,我一直在搬家。 Below I have included the full javascript I finished on to get pdf printing working. 下面,我包括完成pdf打印工作所要完成的全部javascript。 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. 它在android&IOS上运行完美,但是IOS的问题在于,一旦生成pdf,就无法通过文件管理器访问它。

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... localStorage在输出之前用于存储,它在该特定部分的输出html中的span字段上具有相同的ID名称,例如javascript中的第3部分有一些签名和一些文本框要输出,其中的localStorage在一个文本字段中输出是...

getItem('cwiRiskAccesAsessName')

the html output is... HTML输出是...

<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. 我使用jquery通过构建准备输出的html并在每个项目的id上添加前缀来预填充span字段,一旦完成,我就使用此简单的行来处理keyup上的自动填充。 note: ignore 'inpt' in onkeyup, that was for a prefix within another part of the data handling function 注意:忽略onkeyup中的'inpt',这是数据处理功能另一部分中的前缀

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 以下是完整的pdf输出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 ) } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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