打印html中的图片

浏览器 window 对象提供了 print 方法,就可以对整个页面进行打印。只需要点击按钮执行以下方法即可。

1
2
js
复制代码window.print()

调用此方法,会打印出整个 html 里的内容,即 document 对象下所有的页面节点。而我们需要的是只打印页面的某个元素部分,即只打印图片。

浏览器在 具体的dom 节点上并没有部署 print 方法,不过我们可以转变个思路,我们可以将需要打印的元素提取出来,同时构造一个新的window对象,将提取出来的元素插入到这个window对象下,再调用打印即可

html
1
2
3
4
5
6
7
<div id="box">
<el-image
style="width: 300px; height: 300px;"
:src="imageUrl"
:fit="fit">
</el-image>
</div>
js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
ORCodePrint(){
this.imageDialogVisible=false;
const el = document.querySelector("#box")
var docStr = el.innerHTML;
const printContent = el.innerHTML +
"<p style='text-align: center;margin-top: 55%;font-size: 30px'>"+this.currentRow.first_area_name+"-"+this.currentRow.second_area_name+"-"+this.currentRow.specific_area_name+"</p>";
var newWindow=window.open("打印窗口","_blank");
newWindow.document.write(printContent);
console.log(docStr)
// newWindow.document.write("\n"+this.currentRow.id);
newWindow.document.close();
newWindow.print();
newWindow.close();
}