告别媒体查询,轻松打印完整样式的HTML内容!打印HTML时保持样式一致一直是个难题,媒体查询常常让问题复杂化。本文介绍一种无需媒体查询的简便方法。
解决方案:使用jspdf将HTML转换为图像
我们将利用JavaScript库jspdf,将HTML内容转换为图像,再将该图像嵌入到一个打印时才显示的隐藏元素中。
HTML结构
HTML主体包含两个主要元素:
root-container
。printed-image
,位于root-container
外部,用于存放jspdf生成的图像。
![]()
JavaScript代码
以下代码会在页面加载时生成图像,并提供一个打印图像的函数:
// 页面加载时生成图像
$(document).ready(function() {
generateImage();
});
// 打印图像函数 (绑定到打印按钮)
function printImage() {
window.print();
}
// 将内容转换为图像的函数
function generateImage() {
const style = document.createElement('style');
document.head.appendChild(style);
style.sheet?.insertRule('body > div:last-child img { display: inline-block; }');
html2canvas(document.getElementById('content-to-print'), {
useCors: true,
scale: 3,
backgroundColor: '#fff',
scrollX: 0,
scrollY: 0,
windowWidth: document.documentElement.scrollWidth,
windowHeight: document.documentElement.scrollHeight
}).then(function(canvas) {
const { jspdf } = window.jspdf;
const imgData = canvas.toDataURL('image/png');
const pdf = new jspdf('p', 'mm', 'a4');
const imgWidth = 210;
const pageHeight = 285;
const imgHeight = canvas.height * imgWidth / canvas.width;
const heightLeft = imgHeight;
let position = -7;
pdf.setFillColor(255, 255, 255);
pdf.rect(0, 0, imgWidth, pageHeight, 'f');
pdf.addImage(imgData, 'png', 0, position, imgWidth, imgHeight);
$('#printed-image').prop('src', imgData);
});
}
CSS代码
添加打印样式,隐藏主内容,打印时显示生成的图像:
/* 默认样式 */
#printed-image {
display: none;
}
/* 打印样式 */
@media print {
#root-container {
display: none !important;
}
#printed-image {
display: block !important;
margin: auto;
max-width: 100%;
}
}
工作流程
页面加载时,HTML内容转换为图像,并存储在隐藏的img元素中。打印时,主内容隐藏,图像显示。
优势
通过这种方法,您可以轻松获得样式完整、一致的打印输出,无需再为媒体查询而烦恼。