赞
踩
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>printDemo</title>
- </head>
- <body>
- <input type="button" value="打印此页面" onclick="printpage()" />
- <div>内容</div>
- <script>
- function printpage() {
- window.print()
- }
- </script>
- </body>
- </html>

注意一点:如果想要实现 window.print() 打印当前的页面,则要保证打印页面的 body 必须为 auto,否则只会打印第一页。还要注意一下权重问题。
- @media print{
- body {
- height: auto !important;
- }
- }
通过css强制断页,page-break-after:always;代表此标签之后强制断页。
注意:不能对绝对定位的元素使用以上三种分页属性。
请尽可能少地使用分页属性,并且避免在表格、浮动元素、带有边框的块元素中使用分页属性。
<p style="page-break-after:always;"></p>
表格分页截断bug:解决方法添加css即可自动分页
- table{
- page-break-inside: avoid;
- page-break-after: avoid;
- page-break-before: avoid;
- }
- @media print {
- @page {
- /* 纵向 */
- size: portrait;
-
- /* 横向 */
- size: landscape;
-
- /* 边距 上右下左 */
- margin: 1cm 2cm 1cm 2cm;
- }
- }
页眉打印默认有页眉页脚信息,展现到页面外边距范围,我们可以通过去除页面模型page的外边距,使得内容不会延伸到页面的边缘,再通过设置 body 元素的 margin 来保证 A4 纸打印出来的页面带有外边距
- @media print {
- @page {
- margin: 0;
- }
- body {
- margin: 1cm;
- }
- }
方法1:@media print 媒体查询里面让对应元素隐藏 display:none;
方法2:在js里面让他内容先变空等等
原理就是在页面不展示这个dom
方法一
在需要打印的正文内容所对应的html开始处加上 <!--startprint--> 标识,结尾处加上 <!--endprint--> 标识,截取打印标识之间的内容替换body的内容,调用打印print()方法。
- <body>
- <input type="button" value="打印此页面" onclick="printpage()" />
-
- <!--startprint-->
- <div id="printContent">打印内容</div>
- <!--endprint-->
-
- <script>
- function printpage() {
- let oldStr = window.document.body.innerHTML; // 获取body的内容
- let start = "<!--startprint-->"; // 开始打印标识, 17个字符
- let end = "<!--endprint-->"; // 结束打印标识
- let newStr = oldStr.substr(oldStr.indexOf(start) + 17); // 截取开始打印标识之后的内容
- newStr = newStr.substring(0, newStr.indexOf(end)); // 截取开始打印标识和结束打印标识之间的内容
- window.document.body.innerHTML = newStr; // 把需要打印的指定内容赋给body
- window.print(); // 调用浏览器的打印功能打印指定区域
- window.document.body.innerHTML = oldStr; // body替换为原来的内容
- }
- </script>
- </body>

方法二
将需要打印的内容用一个大的div包裹,打印时将body的内容替换为该div的内容,调用打印print()方法。
- <body>
-
- <input type="button" value="打印此页面" onclick="printpage()" />
- <div id="printContent">打印内容</div>
-
- <script>
- function printpage() {
- let newstr = document.getElementById("printContent").innerHTML;
- let oldstr = document.body.innerHTML;
- document.body.innerHTML = newstr;
- window.print();
- document.body.innerHTML = oldstr;
- return false;
- }
- </script>
- </body>

方法三
有两个事件可以监听到到打印事件,一个是onbeforeprint(),一个是onafterprint(),分别表示打印事件触发前后。
检测打印请求,提供一个打印前的处理事件onbeforeprint() 将一些不需要打印的元素隐藏,和打印后的处理事件 onafterprint()放开隐藏的元素。
- window.onbeforeprint = function(event) {
- //将一些不需要打印的元素隐藏
- };
- window.onafterprint = function(event) {
- //放开隐藏的元素
- };
首先安装依赖 :
将页面转换成图片
html2canvas 的作用就是根据 DOM 生成对应的图片。它的屏幕截图是基于 DOM 的,因此可能不会 100% 精确到真实的表示,因为它不会生成实际的屏幕截图,而是基于页面上可用的信息构建屏幕截图。
- npm install html2canvas --save
-
-
-
- yarn add html2canvas
将图片导出成PDF
JSPDF是一个JavaScript库,用于生成PDF文档。它可以直接在浏览器中生成PDF,也可以通过Node.js在服务器端生成PDF。JSPDF具有高度的自定义性和可扩展性,可以用于各种PDF生成需求。
- npm install jspdf --save
-
-
-
- yarn add jspdf
在网上有很多使用html2canvas和jspdf插件的代码,在导出时,有时候会出现导出内容有滚动条的话导出内容不全,只能导出可视部分,滚动条隐藏掉的内容不会展示出来。
解决方法:
1、在导出之前将元素的高度/宽度设置为滚动高度,如:
ele.style.height = ele.scrollHeight + 'px' // 获取元素的滚动高度,用于截取被滚动条隐藏的部分
2、转为图片之后再将高度/宽度设回来,
ele.style.height = ele.scrollHeight + 'px' // 获取元素的滚动高度,用于截取被滚动条隐藏的部分
完整代码:
- import jsPDF from 'jspdf'
- import html2canvas from 'html2canvas'
-
- /*
- * 使用说明
- * ele:需要导出pdf的容器元素(dom节点 不是id)
- * pdfFileName: 导出文件的名字 通过调用outPutPdfFn方法也可传参数改变
- * splitClassName: 避免分段截断的类名 当pdf有多页时需要传入此参数 , 避免pdf分页时截断元素 如表格<tr class="itemClass"></tr>
- * 调用方式 先 let pdf = new PdfLoader(ele, 'pdf' ,'itemClass');
- * 若想改变pdf名称 pdf.outPutPdfFn(fileName); outPutPdfFn方法返回一个promise 可以使用then方法处理pdf生成后的逻辑
- * */
- class PdfLoader {
- constructor(ele, pdfFileName, splitClassName) {
- this.ele = ele
- this.pdfFileName = pdfFileName
- this.splitClassName = splitClassName || ''
- this.A4_WIDTH = 841.89
- this.A4_HEIGHT = 595.28
- }
-
- async getPDF(resolve) {
- const ele = this.ele
- const pdfFileName = this.pdfFileName
- const eleW = ele.offsetWidth // 获得该容器的宽
- const eleH = ele.scrollHeight // 获得该容器的高
- const eleOffsetTop = ele.offsetTop // 获得该容器到文档顶部的距离
- const eleOffsetLeft = ele.offsetLeft // 获得该容器到文档最左的距离
- window.pageYoffset = 0
- document.documentElement.scrollTop = 0
- document.body.scrollTop = 0
- const canvas = document.createElement('canvas')
- let abs = 0
- const win_in =
- document.documentElement.clientWidth || document.body.clientWidth // 获得当前可视窗口的宽度(不包含滚动条)
- const win_out = window.innerWidth // 获得当前窗口的宽度(包含滚动条)
- if (win_out > win_in) {
- abs = (win_out - win_in) / 2 // 获得滚动条宽度的一半
- }
- canvas.width = eleW * 2 // 将画布宽&&高放大两倍
- canvas.height = eleH * 2
- const context = canvas.getContext('2d')
- context.scale(2, 2) // 增强图片清晰度
- context.translate(-eleOffsetLeft - abs, -eleOffsetTop)
- ele.style.height = ele.scrollHeight + 'px' // 获取元素的滚动高度,用于截取被滚动条隐藏的部分
- html2canvas(ele, {
- backgroundColor: null,
- allowTaint: false,
- dpi: window.devicePixelRatio * 4,
- width: ele.width,
- height: ele.width,
- windowWidth: ele.scrollWidth,
- scale: 4, // 按比例增加分辨率
- useCORS: true, // 允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
- }).then(async (canvas) => {
- const contentWidth = canvas.width
- const contentHeight = canvas.height
- ele.style.height = ele.clientHeight + 'px' // 获取元素的实际高度,不包括滚动条隐藏的部分
- // 一页pdf显示html页面生成的canvas高度;
- const pageHeight = (contentWidth / this.A4_WIDTH) * this.A4_HEIGHT // 这样写的目的在于保持宽高比例一致 pageHeight/canvas.width = a4纸高度/a4纸宽度// 宽度和canvas.width保持一致
- // 未生成pdf的html页面高度
- let leftHeight = contentHeight
- // 页面偏移
- let position = 0
- // a4纸的尺寸[595,842],单位像素,html页面生成的canvas在pdf中图片的宽高
- const imgWidth = this.A4_WIDTH - 10 // -10为了页面有右边距
- const imgHeight = (this.A4_WIDTH / contentWidth) * contentHeight
- const pageData = canvas.toDataURL('image/jpeg', 1.0)
- const pdf = jsPDF('l', 'pt', 'a4')
- // 有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
- // 当内容未超过pdf一页显示的范围,无需分页
- if (leftHeight < pageHeight) {
- // 在pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置在pdf中显示;
- pdf.addImage(pageData, 'JPEG', 5, 0, imgWidth, imgHeight)
- // pdf.addImage(pageData, 'JPEG', 20, 40, imgWidth, imgHeight);
- } else {
- // 分页
- while (leftHeight > 0) {
- pdf.addImage(
- pageData,
- 'JPEG',
- 5,
- position,
- imgWidth,
- imgHeight
- )
- leftHeight -= pageHeight
- position -= this.A4_HEIGHT
- // 避免添加空白页
- if (leftHeight > 0) {
- pdf.addPage()
- }
- }
- }
- pdf.save(pdfFileName + '.pdf', { returnPromise: true }).then(() => {
- // 去除添加的空div 防止页面混乱
- const doms = document.querySelectorAll('.emptyDiv')
- for (let i = 0; i < doms.length; i++) {
- doms[i].remove()
- }
- })
- this.ele.style.height = ''
- resolve()
- })
- }
- //此方法是防止(图表之类)内容因为A4纸张问题被截断
- async outPutPdfFn(pdfFileName) {
- return new Promise((resolve, reject) => {
- this.ele.style.height = 'initial'
- pdfFileName ? (this.pdfFileName = pdfFileName) : null
- const target = this.ele
- const pageHeight =
- (target.scrollWidth / this.A4_WIDTH) * this.A4_HEIGHT
- // 获取分割dom,此处为class类名为item的dom
- const domList = document.getElementsByClassName(this.splitClassName)
- // 进行分割操作,当dom内容已超出a4的高度,则将该dom前插入一个空dom,把他挤下去,分割
- let pageNum = 1 // pdf页数
- const eleBounding = this.ele.getBoundingClientRect()
- for (let i = 0; i < domList.length; i++) {
- const node = domList[i]
- const bound = node.getBoundingClientRect()
- const offset2Ele = bound.top - eleBounding.top
- const currentPage = Math.ceil(
- (bound.bottom - eleBounding.top) / pageHeight
- ) // 当前元素应该在哪一页
- if (pageNum < currentPage) {
- pageNum++
- const divParent = domList[i].parentNode // 获取该div的父节点
- const newNode = document.createElement('div')
- newNode.className = 'emptyDiv'
- newNode.style.background = 'white'
- newNode.style.height =
- pageHeight * (pageNum - 1) - offset2Ele + 30 + 'px' // +30为了在换下一页时有顶部的边距
- newNode.style.width = '100%'
- divParent.insertBefore(newNode, node) //在每一个节点前面插入一个空的新节点,防止内容被分割截断
- }
- }
- // 异步函数,导出成功后处理交互
- this.getPDF(resolve, reject)
- })
- }
- }
-
- export default PdfLoader

页面中调用:
- <script>
- import PdfLoader from "@/utils/html2pdf.js";
- export default {
- data() {
- return {};
- },
- methods: {
- handleExport() {
- let pdf = new PdfLoader(
- document.querySelector("#overviewpage"),
- "pdf"
- // "noSplitBox"
- );
- pdf.outPutPdfFn();
- },
- },
- };
- </script>

Vue生成PDF文件攻略:html2canvas与jspdf联手,中文乱码与自动换行难题攻克_html2canvas文档-CSDN博客
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。