我想只打印QR码div而不是整页。任何人都可以帮助我。
这是我的代码:
<div id="qrcodeCanvas"></div> //Generating QR in this div
<a id="Html2Image" href="#qrcodeCanvas">Download</a>
<a id="mydiv" href="javascript:void(0);" onClick="PrintDiv();" >Print</a>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js' type='text/javascript'></script>
<script type="text/javascript" src="js/jquery.qrcode.js"></script>
<script type="text/javascript" src="js/qrcode.js"></script>
<script>
function PrintDiv()
{
}
</script>
<script>
var id = 'Content';
$('#qrcodeCanvas').qrcode(id);
var canvas = $('#qrcodeCanvas canvas');
var img = $(canvas)[0].toDataURL("image/png");
$("#Html2Image").attr("download", "QR_Code.png").attr("href", img); //Downloading QR image
</script>
提前感谢。
答案 0 :(得分:0)
我遇到了同样的问题并且来了这个解决方案
<!DOCTYPE html>
<html>
<body>
<div id="printableArea">
<div id="qrcodeCanvas"></div>
</div>
<script>
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
<input type="button" onclick="printDiv('printableArea')" value="print a qr!" />
</body>
</html>
致谢:asprin
答案 1 :(得分:0)
@ImmanuelNL的答案应该有效,但它会将一切。事件处理程序,对代码中元素的任何引用,一切都将被破坏。
相反,请考虑这种非破坏性方法:
var tmp = document.createDocumentFragment(),
printme = document.getElementById('printableArea').cloneNode(true);
while(document.body.firstChild) {
// move elements into the temporary space
tmp.appendChild(document.body.firstChild);
}
// put the cloned printable thing back, and print
document.body.appendChild(printme);
window.print();
while(document.body.firstChild) {
// empty the body again (remove the clone)
document.body.removeChild(document.body.firstChild);
}
// re-add the temporary fragment back into the page, restoring initial state
document.body.appendChild(tmp);