我正在尝试使用HTML2Canvas将我的元素转换为PNG文件,稍后将该PNG转换为PDF。为此我有功能:
function makeImage(){
var $printSection = createPrintSection();
addElement(document.getElementById("accordion"),$printSection);
addElement(document.getElementById("fullHistory"),$printSection);
return $printSection;
}
如果没有名为printSection的div,则createPrintSection创建div:
function createPrintSection(){
var $printSection = document.getElementById("printSection");
if (!$printSection){
var $printSection = document.createElement("div");
$printSection.id = "printSection";
document.body.appendChild($printSection);
}
$printSection.innerHTML = "";
return $printSection;
}
现在addelement会:
function addElement(elem,parent) {
var domClone = elem.cloneNode(true);
parent.appendChild(domClone);
}
如果我在给它一个值之后放入console.log(domClone),它表明它已成功完成它。但是,它不会被添加到它的父子节点($ printSection - 执行console.log($ printSection)将返回一个空div到控制台)。有什么想法可能会发生吗?
这是我的完整代码:
function tryThis(){
var $printSection = makeImage();
console.log($printSection);
html2canvas($printSection, {
onrendered: function(canvas) {
var imgData = canvas.toDataURL(
'image/png');
console.log(imgData);
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10);
var name = document.getElementById("tabelinimi").textContent;
if (name.length < 2){
name = "nameless";
}
var deit = datemaker();
var stringB = name+"_table_"+deit+".pdf";
doc.save(stringB);
}
});
removePrintSection()
}
function makeImage(){
var printSection = createPrintSection();
console.log(printSection);
addElement(document.getElementById("accordion"),printSection);
addElement(document.getElementById("fullHistory"),printSection);
return printSection;
}
function datemaker(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = mm+'.'+dd+'.'+yyyy;
return today;
}
function createPrintSection(){
var $printSection = document.getElementById("printSection");
if (!$printSection){
var $printSection = document.createElement("div");
$printSection.id = "printSection";
document.body.appendChild($printSection);
}
$printSection.innerHTML = "";
return $printSection;
}
function addElement(elem,parent) {
var domClone = elem.cloneNode(true);
domClone.id = elem.id+"_copy";
console.log("DomClone: ");
console.log(domClone);
parent.appendChild(domClone);
console.log("Parent: ");
console.log(parent);
}
function removePrintSection(){
var $printSection = document.getElementById("printSection");
if (!$printSection){
return;
}
else{
$printSection.innerHTML = "";
}
}
这是来自控制台的图片摘录:
我通过点击HTML按钮调出tryThis()。