告别媒体查询,轻松打印完整样式的html内容!打印html时保持样式一致一直是个难题,媒体查询常常让问题复杂化。本文介绍一种无需媒体查询的简便方法。
解决方案:使用jspdf将HTML转换为图像
我们将利用JavaScript库jspdf,将HTML内容转换为图像,再将该图像嵌入到一个打印时才显示的隐藏元素中。
HTML结构
立即学习“前端免费学习笔记(深入)”;
HTML主体包含两个主要元素:
一个包含主内容的div,id为root-container。一个隐藏的img元素,id为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元素中。打印时,主内容隐藏,图像显示。
优势
避免了媒体查询的复杂性。样式直接嵌入图像,确保打印输出与屏幕显示一致。
通过这种方法,您可以轻松获得样式完整、一致的打印输出,无需再为媒体查询而烦恼。
以上就是告别媒体查询:打印完全样式的HTML内容的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2640381.html