Phonegap / jsPDF问题将html保存为pdf

时间:2014-04-29 14:47:51

标签: javascript jquery cordova

我不是一个庞大的javascript / jquery用户,但我已经开始在移动应用程序中使用它...我一直在寻找一个答案来解决我在尝试时获取空白页面的问题使用jspdf将html输出为pdf,我发现的每个帖子都与blob有关。

这是我的代码我输出了一个空白的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
    )

有人可以给我一个提示或指出我正确的方向,如何将您的解决方案纳入我的编码,这样我就可以保存html格式&图象?

2 个答案:

答案 0 :(得分:1)

我刚才有同样的问题。 这是我为解决它所做的工作。

替换

writer.write( pdfOutput );

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

不是100%确定我理解发生了什么,但是根据我一直在研究的内容,您需要在写入文件之前将输出从jsPDF转换为ArrayBuffer。

答案 1 :(得分:0)

@AdilWaqar我为我的回复延迟道歉,我一直在搬家。下面我已经包含了我完成的完整的javascript以获得pdf打印工作。它在android&amp; IOS但IOS的问题是,一旦生成了pdf,您就无法通过文件管理器访问它。

localStorage在输出之前用于存储,它在该特定部分的输出html中的span字段上具有相同的id名称,例如javascript中的第3部分有一些签名和一些文本框要输出,localStorage for输出中的一个文本域是......

getItem('cwiRiskAccesAsessName')

html输出是......

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

我使用jquery来预先填充span字段,方法是为输出构建html并为每个项的id添加前缀,一旦完成,我就用这条简单的线来处理keyup上的自动填充。注意:忽略&#39; inpt&#39;在onkeyup中,这是在数据处理函数的另一部分中的前缀

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

以下是完整的pdf输出javascript

&#13;
&#13;
/* 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
		)
}
&#13;
&#13;
&#13;