[英]Print page using html2canvas
我正在使用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()
,圖像顯示在新窗口中,但沒有觸發打印功能。 有什么不對?
試試這個,它會起作用:
html2canvas($("#mydiv"), {
onrendered: function(canvas) {
var myImage = canvas.toDataURL("image/png");
var tWindow = window.open("");
$(tWindow.document.body)
.html("<img id='Image' src=" + myImage + " style='width:100%;'></img>")
.ready(function() {
tWindow.focus();
tWindow.print();
});
}
});
香草JS解決方案
// render HTML to canvas based on target element
html2canvas(document.querySelector('<YOUR SELECTOR>'), {
// if the canvas is rendered
onrendered: function (canvas) {
// create a new window
var nWindow = window.open('');
// append the canvas to the body
nWindow.document.body.appendChild(canvas);
// focus on the window
nWindow.focus();
// print the window
nWindow.print();
// reload the page
location.reload();
}
});
最后我想出了解決方案。 我之前使用的處理應該分成兩部分。
1)當頁面加載時,使用html2canvas將頁面渲染成圖像並將其存儲在隱藏的div中。
html2canvas(divprint, {
onrendered: function(canvas) {
var canvasImg = canvas.toDataURL("image/jpg");
$('#divhidden').html('<img src="'+canvasImg+'" alt="">');
}
});
2)點擊打印按鈕后,打開一個新窗口,編寫存儲的div內容和加載完成時打印的jquery函數。
$("#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();
})
我做了這個
function myprint() {
html2canvas(jQuery('div.cart'), { // replace div.cart with your selector
onrendered: function (canvas) {
var myImage = canvas.toDataURL("image/png");
var tmp = document.body.innerHTML;
document.body.innerHTML = '<img src="'+myImage+'" alt="">';
var printWindow = window.print();
document.body.innerHTML = tmp;
}
});
}
try this code, it is working.
<div id="mydiv">asdasfadsadfasfd</div>
<script>
html2canvas($("#mydiv"), {
onrendered: function (canvas) {
var myImage = canvas.toDataURL("image/png");
var printWindow = window.print(myImage);
}
});
</script>
html2canvas(document.querySelector("#mydiv")).then(canvas => {
var myImage = canvas.toDataURL("image/png");
var tWindow = window.open("");
$(tWindow.document.body)
.html("<img id='Image' src=" + myImage + " style='width:100%;'></img>")
.ready(function() {
tWindow.focus();
tWindow.print();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.