问题描述
我正在使用 html2canvas
在我的网站上构建打印页面功能.
I'm building a print page function on my web using html2canvas
.
function printthispage() {
html2canvas($("#mydiv"), {
onrendered: function (canvas) {
var myImage = canvas.toDataURL("image/png");
var printWindow = window.open(myImage);
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
}
});
}
但是,窗口会立即打开和关闭.我尝试删除 close()
,该图像显示在新窗口中,但未触发任何打印功能.有什么问题吗?
However the window opened and closed immediately. I've tried removing close()
, the image showed on new window but no print function was triggered. Is there something wrong?
推荐答案
最后,我找出了解决方案.我以前使用的处理方法应分为两部分.
Finally I figure out the solution. The previous handling I used should be made into 2 parts.
1)加载页面后,使用html2canvas将页面呈现为图像并将其存储在隐藏的div中.
1) use html2canvas to render the page into image and store it in a hidden div, when the page is loaded.
html2canvas(divprint, {
onrendered: function(canvas) {
var canvasImg = canvas.toDataURL("image/jpg");
$('#divhidden').html('<img src="'+canvasImg+'" alt="">');
}
});
2)单击打印按钮后,打开一个新窗口,在完成加载后编写存储的div内容和jquery函数以进行打印.
2) Once a print button is clicked, open a new window, write the stored div content and jquery function for printing when the loading is done.
$("#printbutton").click(function(e){
var printContent = document.getElementById("divhidden");
var printWindow = window.open("", "","left=50,top=50");
printWindow.document.write(printContent.innerHTML);
printWindow.document.write("<script src=\'http://code.jquery.com/jquery-1.10.1.min.js\'><\/script>");
printWindow.document.write("<script>$(window).load(function(){ print(); close(); });<\/script>");
printWindow.document.close();
})
这篇关于使用html2canvas打印页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!