当用户点击导出按钮时,我将div中存在的数据导出为PDF。我想显示每个div内容以显示在PDF中的各个页面中。
以上方案适用于演示https://plnkr.co/edit/KvkVlYmmmJiZ71sghb1l?p=preview
同样适用于下面的代码,它不起作用。 在这里演示:https://plnkr.co/edit/P9nUSRY5TytkonM6dUHl?p=preview
js code:
$scope.export = function() {
var pdf = new jsPDF('landscape');
var source = $('#append-source');
$('.myDivClass').each(function(){
var html = "<div>"+$(this) + "</div><!--ADD_PAGE-->";//the code is broken with this line
// var html = $(this);
source.append(html);
});
console.log(source);
pdf.addHTML(
source, 0, 0, {
pagesplit: true
},
function(dispose){
pdf.save('test3.pdf');
}
);
}
答案 0 :(得分:1)
不建议在角度应用中使用这样的jquery。要了解原因,请查看此处:Can we use both jQuery and Angular in our Web Application?
但是,如果将以下内容放入控制器,则可以执行以下操作:
$scope.export = function() {
var pdf = new jsPDF('landscape');
var source = "";
var width1 = pdf.internal.pageSize.width;
$('.myDivClass').each(function(){
var textForPdfPage = $(this).children().eq(1).children()[0].textContent;
var html = "<div>"+ textForPdfPage + " </div><!--ADD_PAGE-->";
source+=html;
});
margins = {
top: 80,
bottom: 60,
left: 10,
width: '100%'
};
pdf.fromHTML(
source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, { // y coord
'width': width1 // max width of content on PDF
},
function (dispose) {
pdf.save('test.pdf');
},
margins
);
}
您的主要问题是,当您尝试创建html字符串时,您只使用了$(this)
。 $(this)
为您提供了一个jquery对象。您要放在页面上的字符串位于此对象中,并使用jquery .children()
方法进行访问。
答案 1 :(得分:0)
以下是使用addHTML()代替fromHTML()执行操作的方法:
$scope.export = function() {
var pdf = new jsPDF('landscape');
var pdfName = 'test.pdf';
var options = {};
var $divs = $('.myDivClass') //jQuery object of all the myDivClass divs
var numRecursionsNeeded = $divs.length -1; //the number of times we need to call addHtml (once per div)
var currentRecursion=0;
//Found a trick for using addHtml more than once per pdf. Call addHtml in the callback function of addHtml recursively.
function recursiveAddHtmlAndSave(currentRecursion, totalRecursions){
//Once we have done all the divs save the pdf
if(currentRecursion==totalRecursions){
pdf.save(pdfName);
}else{
currentRecursion++;
pdf.addPage();
//$('.myDivClass')[currentRecursion] selects one of the divs out of the jquery collection as a html element
//addHtml requires an html element. Not a string like fromHtml.
pdf.addHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
console.log(currentRecursion);
recursiveAddHtmlAndSave(currentRecursion, totalRecursions)
});
}
}
pdf.addHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
recursiveAddHtmlAndSave(currentRecursion, numRecursionsNeeded);
});
}
我离开了另一个答案,所以人们可以看到两种方式。