您好,欢迎访问一九零五行业门户网

react打印样式丢失怎么办

react打印样式丢失的解决办法:1、通过“npm install --save html2canvas npm install jspdf --save”命令安装jspdf;2、使用jspdf将需要打印的div转成pdf;3、使用react重新打印即可。
本教程操作环境:windows10系统、react18版、dell g3电脑。
react打印样式丢失怎么办?
vue print打印div样式丢失 (react通用)
使用网上的print.js插件,打印发现样式丢失。
解决方案 > 将html转成pdf,再打印pdf
使用jspdf将需要打印的div转成pdf(转成的pdf样式不会丢失,因为pdf.js是将div转成canvas)
安装jspdf
npm install --save html2canvas
npm install jspdf --save
上代码
utli.js 直接复制,注意outputpdf方法入参即可
import html2canvas from 'html2canvas';import jspdf from 'jspdf';// base64转blobexport function toblob(base64data) { let bytestring = base64data if (base64data.split(',')[0].indexof('base64') >= 0) { bytestring = atob(base64data.split(',')[1]); // base64 解码 } else { bytestring = unescape(base64data.split(',')[1]); } // 获取文件类型 const mimestring = base64data.split(';')[0].split(":")[1]; // mime类型 // arraybuffer 对象用来表示通用的、固定长度的原始二进制数据缓冲区 // let arraybuffer = new arraybuffer(bytestring.length) // 创建缓冲数组 // let uintarr = new uint8array(arraybuffer) // 创建视图 const uintarr = new uint8array(bytestring.length); // 创建视图 for (let i = 0; i < bytestring.length; i += 1) { uintarr[i] = bytestring.charcodeat(i); } // 生成blob const blob = new blob([uintarr], { type: mimestring }) // 使用 blob 创建一个指向类型化数组的url, url.createobjecturl是new blob文件的方法,可以生成一个普通的url,可以直接使用,比如用在img.src上 return blob;};/** * 输出pdf * @param {*} idname html元素 * @param {*} pdfname 输出pdf文件名 * @param {*} isdownload 是否直接下载 * @param {*} isprint 是否直接打印 * @param {*} callback 执行后的回调 */ export function outputpdf(idname, pdfname, isdownload = false, isprint = false, callback) { const element = document.getelementbyid(idname); // 这个dom元素是要导出的pdf的div容器 const w = element.offsetwidth; // 获得该容器的宽 const h = element.offsetheight; // 获得该容器的高 const offsettop = element.offsettop; // 获得该容器到文档顶部的距离 const offsetleft = element.offsetleft; // 获得该容器到文档最左的距离 const canvas = document.createelement("canvas"); let abs = 0; const wini = document.body.clientwidth; // 获得当前可视窗口的宽度(不包含滚动条) const wino = window.innerwidth; // 获得当前窗口的宽度(包含滚动条) if (wino > wini) { abs = (wino - wini) / 2; // 获得滚动条宽度的一半 } canvas.width = w * 2; // 将画布宽&&高放大两倍 canvas.height = h * 2; const context = canvas.getcontext('2d'); context.scale(2, 2); context.translate(-offsetleft - abs, -offsettop); // 这里默认横向没有滚动条的情况,因为offset.left(),有无滚动条的时候存在差值,因此translate的时候,要把这个差值去掉 html2canvas(element, { usecors: true, // 允许加载跨域的图片 allowtaint: true, scale: 2 // 提升画面质量,但是会增加文件大小 }).then(cs => { const contentwidth = cs.width; const contentheight = cs.height; // 一页pdf显示html页面生成的canvas高度 const pageheight = contentwidth / 592.28 * 841.89; // 未生成pdf的html页面高度 let leftheight = contentheight; // 页面偏移 let position = 0; // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高 const imgwidth = 595.28; const imgheight = 592.28 / contentwidth * contentheight; const pagedate = cs.todataurl('image/jpeg', 1.0); const pdf = new jspdf('', 'pt', 'a4'); // 有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面的高度(841.89) // 当内容未超过pdf一页显示的范围,无需分页 if (leftheight < pageheight) { pdf.addimage(pagedate, 'jpeg', 0, position, imgwidth, imgheight); } else { // 分页 while (leftheight > 0) { pdf.addimage(pagedate, 'jpeg', 0, position, imgwidth, imgheight) leftheight -= pageheight; position -= 841.89; // 避免添加空白页 if (leftheight > 0) { pdf.addpage() } } } if (isdownload) { pdf.save(`${pdfname}.pdf`); } if (isprint) { const link = window.url.createobjecturl(toblob(pdf.output('datauristring'))); const mywindow = window.open(link); mywindow.print(); } callback && callback(pdf); })}
需要打印部分
<div id="printdiv"></div>
vue 全部代码
<template> <a-modal v-model="visible" :title="title" :maskclosable="false" centered :width="1000" @cancel="close" > <div id="printdiv"> <div v-if="!pdfing"> <span></span> <span>入库单</span> <a @click="printchart">打印报表</a> </div> <div class="maintain-view-title pdfing" v-else> <span>入库单</span> </div> <a-form :colon="true" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }"> <a-row> <a-col :span="8"> <a-form-item label="入库单号"> <span>{{ viewinfo.accessnumber }}</span> </a-form-item> </a-col> <a-col :span="8"> <a-form-item label="供应商"> <span>{{ viewinfo.supplier }}</span> </a-form-item> </a-col> <a-col :span="8"> <a-form-item label="入库日期"> <span>{{ viewinfo.accessdate && $moment(viewinfo.accessdate).format('yyyy-mm-dd hh:mm:ss') }}</span> </a-form-item> </a-col> </a-row> <a-row> <a-col :span="8"> <a-form-item label="仓库"> <span>{{ viewinfo.warehouse }}</span> </a-form-item> </a-col> <a-col :span="8"> <a-form-item label="来源"> <span>{{ viewinfo.source }}</span> </a-form-item> </a-col> <a-col :span="8"> <a-form-item label="经办人"> <span>{{ viewinfo.handledby }}</span> </a-form-item> </a-col> </a-row> <a-row> <a-col :span="8"> <a-form-item label="采购单号"> <span>{{ viewinfo.purchaseorderno }}</span> </a-form-item> </a-col> <a-col :span="8"> <a-form-item label="发票号"> <span>{{ viewinfo.invoiceno }}</span> </a-form-item> </a-col> <a-col :span="8"> <a-form-item label="合同号"> <span>{{ viewinfo.contractno }}</span> </a-form-item> </a-col> </a-row> <a-row> <a-col :span="8"> <a-form-item label="入库类型"> <span>{{ viewinfo.accesstype }}</span> </a-form-item> </a-col> <a-col :span="8"> <a-form-item label="创建时间"> <span>{{ viewinfo.addtime }}</span> </a-form-item> </a-col> <a-col :span="8"> <a-form-item label="备注"> <span>{{ viewinfo.content }}</span> </a-form-item> </a-col> </a-row> </a-form> <a-table style="margintop: 10px;" :columns="columns" :data-source="data" :pagination="false" :loading="loading" row-key="id" > </a-table> </div> <template slot="footer"> <a-button key="back" type="primary" @click="close">取消</a-button> </template> </a-modal></template><script>import { outputpdf } from "@/utils/util";import { getstorageordertopdetail, getstorageorderbottomlistnopage } from "@/api/stock";export default { name: "stockstorageorderviewmodal", components: {}, data() { return { visible: false, form: null, title: "出库确认", loading: false, viewinfo: {}, columns: [ { title: "序号", key: "index", customrender: (text, render, index) => { return index + 1 }, align: "center" }, { title: "产品编号", key: "productnumber", dataindex: "productnumber" }, { title: "类别", key: "type", dataindex: "type" }, { title: "产品名称", key: "productname", dataindex: "productname" }, { title: "规格型号", dataindex: "specifications", dataindex: "specifications" }, { title: "计量单位", key: "unit", dataindex: "unit" }, { title: "批次", key: "batch", dataindex: "batch" }, { title: "数量", key: "number", dataindex: "number" }, { title: "单价", key: "price", dataindex: "price" }, { title: "金额", key: "total", dataindex: "total" }, { title: "已入库", key: "inbound", dataindex: "inbound" }, { title: "未入库", key: "notinbound", dataindex: "notinbound" } ], data: [], pdfing: false, // 打印中 }; }, methods: { // 显示弹框 show(id) { this.visible = true; // 获取上方数据 getstorageordertopdetail({ id }).then(res => { if (res.code === 0) { this.viewinfo = res.data; } }); // 获取下方表格数据 this.gettabledata(id); }, /** * 关闭弹框 */ close() { this.visible = false; this.$emit("cancel"); }, // 获取表格数据 gettabledata(warehouseregisterid) { const params = { warehouseregisterid }; getstorageorderbottomlistnopage(params).then(res => { this.loading = false; if (res.code === 0) { this.data = res.data; } else { this.$common.showerrormessage(res.msg || "请求出现错误,请稍后再试"); } }); }, // 打印 printchart() { this.pdfing = true; this.$nexttick(() => { outputpdf('printdiv', '入库单', false, true, () => { this.pdfing = false; }); }); } }};</script><style scoped>.maintain-view-title { display: flex; justify-content: space-between; align-items: center; &.pdfing { justify-content: center; } .maintain-view-title-label { font-weight: bold; font-size: 1.5em; }}.container-title-block { display: flex; justify-content: space-between; margin-top: 10px;}.viewform { /deep/.ant-form-item { margin-bottom: 0; }}</style>
推荐学习:《react视频教程》
以上就是react打印样式丢失怎么办的详细内容。
其它类似信息

推荐信息