HTML Canvas打印预览优化:如何仅打印目标图片并排除其他元素?
解决打印仅显示目标图片的问题
你的问题出在打印样式的全局设置上——原来的代码里给所有元素设置了display: block,这会让页面上所有元素都出现在打印预览里。要只显示目标图片,得反过来:先隐藏所有元素,再单独让目标图片和必要的容器显示。
修改后的openPrintDialog函数代码如下:
function openPrintDialog(isLandscape, paperSize) { /*jshint multistr: true */ var style = '<style context="program"> \ @media print { \ /* 先隐藏所有页面元素 */ \ * { \ display: none !important; \ } \ \ /* 仅让承载图片的必要容器和图片显示 */ \ html, body, .hidden-print-image { \ display: block !important; \ margin: 0; \ padding: 0; \ text-align: center; \ width: 100%; \ height: 100%; \ } \ \ .hidden-print-image img { \ ' + (isLandscape ? 'max-width: ' + paperSize.heightMm + 'mm;' : 'max-width: ' + paperSize.widthMm + 'mm;') + '\ ' + (isLandscape ? 'max-height:' + paperSize.widthMm + 'mm;' : 'max-height: ' + paperSize.heightMm + 'mm;') + '\ margin: auto; \ } \ } \ </style>'; $('head').append(style); window.print(); $timeout(function() { $('[context=program]').remove(); $('.hidden-print-image').remove(); }, 2000); }
关键修改点:
- 把全局元素的默认样式改成
display: none !important,强制隐藏所有元素 - 仅显式设置
html、body和你的目标图片容器.hidden-print-image为显示状态,同时调整它们的边距、宽高,确保图片能在页面中居中 - 给图片的尺寸单位加上
mm(原来的代码里漏了单位,可能导致尺寸不生效) - 给图片加上
margin: auto,确保在容器中水平居中
这样修改后,打印预览里就只会显示你需要的目标图片,其他页面元素都会被隐藏。
内容的提问来源于stack exchange,提问作者chamara
相关产品推荐
相关产品推荐

