最近项目中,前端采用react+antd+dva的组合,
今天有一个新需求,
需要在后台管理系统中实现 点击打印 完成指定页面的打印功能。

我们道浏览器带有打印功能的实现,window.print()。

然而,在react中是没有dom节点的,不过我们也是可以转为dom节点的。就是在需要打印的内容部分节点添加一个ID

  只不过,这样打印出来的内容是没有带样式的,因为一般css文件并不会写到行内去,所以在生成html的文件字符串时,里面没有样式信息,在打印时就会布局混乱。
要想打印出来的效果与网页上显示的效果一致,就需要在生成html的文件字符串时,带上样式信息。

方法1:把样式信息写在行内
在文件信息不复杂时,可以写在行内

方法2:使用react-inline-css
使用这个npm包,可以在配置后把样式自动添加到行内

网页效果图:横版效果

打印预览竖版图:


代码下:

 import React, { PureComponent } from 'react';import moment from 'moment';import { connect } from 'dva';import { Card, Button, Form, Table, message,} from 'antd';import styles from './Funds.less';@connect(({ finance, loading }) => ({finance,loading: loading.models.list,}))@Form.create()export default class LoanSettleMent extends PureComponent {constructor(props) {super(props);this.state = {loading: true,};}componentDidMount() {const code = !isEmptyObject(this.props.match) ? this.props.match.params.id : 0;this.statisticalInfo({ receiptsCode: code });}// 结算单列表详情statisticalInfo(params) {this.props.dispatch({type: 'finance/statisticalInfo',payload: params,}).then(() => {this.setState({loading: false,})});}// 撤销操作fetchRevocation(params) {this.props.dispatch({type: 'finance/fetchRevocation',payload: params,}).then(() => {const { finance: { revocationData } } = this.props;const { code } = revocationData;if (code === 200) {message.info('撤销货款单成功!').then(() => {window.location.href = '/funds/loansettlement';});} else {message.info('撤销货款单失败!');}});}// 撤销cancer = () => {const code = !isEmptyObject(this.props.match) ? this.props.match.params.id : 0;this.fetchRevocation({receiptsCode: code,});};// 返回back = () => {window.history.back();};// 打印print(){window.document.body.innerHTML = window.document.getElementById('billDetails').innerHTML;  window.print(); window.location.reload();}render() {const { finance: { statisticalInfo }, loading } = this.props;let data = [],createName,createTime;if (statisticalInfo && !Array.isArray(statisticalInfo)) {data = statisticalInfo;createName = statisticalInfo.createName;createTime = statisticalInfo.createTime;}if (statisticalInfo != undefined) {data = statisticalInfo.goodsVos;}let _data = [],receiptsCode;if (statisticalInfo && !Array.isArray(statisticalInfo)) {_data = statisticalInfo;receiptsCode = statisticalInfo.receiptsCode;}const { supplierName, carNo, stallName, startTime, endTime, enable } = _data;const len = data.length;const columns = [{title: '品种',dataIndex: 'attrName',align: 'center',},{title: '销售货款',dataIndex: 'goodsAmount',align: 'left',render: (text, record, index) => {const { goodsAmount, goodsPaymentStr } = record;const type = goodsPaymentStr !== null ? goodsPaymentStr.split('负').length : -1;if (index < len - 1) {return <span>{goodsAmount ? Yuan(goodsAmount, 2) : ''}</span>;}return {children:type == 2 ? (<span className={styles.neg}>{goodsPaymentStr}</span>) : (<span className={styles.bold}>{goodsPaymentStr}</span>),props: {colSpan: 7,},};},},{title: '件数',dataIndex: 'number',align: 'center',render: (text, record, index) => {const { number } = record;if (index < len - 1) {return <span>{number ? number : ''}</span>;}return {children: '',props: {colSpan: 0,},};},},{title: '重量',dataIndex: 'weight',align: 'center',render: (text, record, index) => {const { weight } = record;if (index < len - 1) {return <span>{weight ? weight : ''}</span>;}return {children: '',props: {colSpan: 0,},};},},{title: '平均售价',dataIndex: 'averageAmount',align: 'center',render: (text, record, index) => {const { averageAmount } = record;if (index < len - 1) {return <span>{averageAmount ? Yuan(averageAmount, 2) : ''}</span>;}return {children: '',props: {colSpan: 0,},};},},{title: '平均重量',dataIndex: 'averageWeight',align: 'center',render: (text, record, index) => {const { averageWeight } = record;if (index < len - 1) {return <span>{averageWeight ? averageWeight : ''}</span>;}return {children: '',props: {colSpan: 0,},};},},{title: '费用类型',dataIndex: 'type',align: 'center',render: (text, record, index) => {const { type } = record;if (index < len - 1) {return <span>{type}</span>;}return {children: '',props: {colSpan: 0,},};},},{title: '扣款金额',dataIndex: 'amount',align: 'center',render: (text, record, index) => {const { amount } = record;if (index < len - 1) {return <span>{amount !== null ? Yuan(amount, 2) : ''}</span>;}return {children: '',props: {colSpan: 0,},};},},];return (<PageHeaderLayout><div className={styles.billDetails} id={'billDetails'}><Cardbordered={false}title=""><div className={styles.paymentbill}><div style={{display: 'flex', height: '60px', lineHeight: '60px'}}><h1 style={{flex: 1, textAlign: 'center'}}>{stallName}</h1><span style={{position: 'absolute', right: '10px', color: '#FF6666', fontWeight: '600'}}>{`NO:${receiptsCode !== undefined ? receiptsCode : ''}`}</span></div><div style={{display: 'flex'}}><h2 style={{flex: 1, textAlign: 'center'}}>商品销售车次结算单</h2><div style={{position: 'absolute', right: '10px'}}><Button type="primary" onClick={this.cancer} disabled={!enable} style={{marginRight: '5px'}}>撤销</Button><Button onClick={this.print.bind(this)} style={{marginRight: '5px'}}>打印</Button><Button type="primary" onClick={this.back} style={{marginRight: '5px'}}>返回</Button></div></div><div style={{display: 'flex'}}><h3 style={{flex: 1, textAlign: 'left'}}>{`货老板:${supplierName !== undefined ? supplierName : ''} ${carNo !== undefined ? fixedZeroTo4Bit(carNo, 4) : 0}车`}</h3><h3 style={{flex: 1}}>{`到货时间:${moment(startTime).format('YYYY-MM-DD')}`}</h3><h3 style={{flex: 1}}>{`售罄时间:${moment(endTime).format('YYYY-MM-DD')}`}</h3></div><img src={watermark} hidden={enable} style={{position: 'absolute', width: '100px', height: '100px', top: '120px', right: '80px',zIndex: 100}} /></div></Card><Cardbordered={false}title=""bodyStyle={{ padding: '0 16px' }}><TabledataSource={data}columns={columns}borderedpagination={false}loading={this.state.loading}/></Card><Card style={{ border: 0 }}><div style={{display: 'flex'}}><h3 style={{flex: 1}}>{`结算人:${createName !== undefined ? createName : ''}`}</h3><h3 style={{flex: 1, textAlign: 'right'}}>{`结算时间:${moment(createTime).format('YYYY-MM-DD')}`}</h3></div></Card></div></PageHeaderLayout>);}
}

一般直接使用window.print();是直接打印了整个页面,但只打印其中的一部分时就需要一些方法了

1、在页面的代码头部处加入JavaScript:

<script language=javascript>function doPrint() { bdhtml = window.document.body.innerHTML; sprnstr = "<!--startprint-->"; //开始打印标识字符串有17个字符eprnstr = "<!--endprint-->"; //结束打印标识字符串prnhtml = bdhtml.substr(bdhtml.indexOf(sprnstr)+17); //从开始打印标识之后的内容prnhtmlstr = prnhtml.substring(0,prnhtml.indexOf(eprnstr)); //截取开始标识和结束标识之间的内容window.document.body.innerHTML = prnhtmlstr ; //把需要打印的指定内容赋给body.innerHTMLwindow.print(); //调用浏览器的打印功能打印指定区域window.document.body.innerHTML = bdhtml;//重新给页面内容赋值;}
</script>

2、在页面正文处加上<!–startprint–>与<!–endprint–>标识。

也就是在需要用户打印保存的正文所对应的html处附加上。同时,如果采用小偷程序获得远程数据并需打印,可将此等数据置于该定义标签之内即可。

3、截取内容部分已完成,现在加个“打印”的链接:

要打印的内容在
<!–startprint–>startprint与endprint之间的区域
<!–endprint–>里。
添加打印链接事件<a href="javascript:;" onClick="doPrint()">打印</a>

react项目中实现打印预览功能相关推荐

  1. 网页中JS实现(调用)打印预览功能

    近期的项目中需要在页面中实现打印预览功能--点击网页中的"打印"(Print),弹出打印预览窗口,点击窗口页面中的"开始打印"(Print),则出现浏览器的打印 ...

  2. vue 项目中实现pdf预览 pdf打印 pdf下载

    在Vue项目中实现PDF预览.打印和下载可以通过以下步骤来实现: 安装pdf.js pdf.js是一个JavaScript库,可以用于在Web上渲染PDF文件. 可以使用npm安装pdf.js,命令如 ...

  3. C#实现打印与打印预览功能

    C#实现打印与打印预览功能 发表日期:2010年12月31日 作者:whitewin 点击:102次 在windows应用程序中文档的打印是一项非常重要的功能,在以前一直是一个非常复杂的工作,Micr ...

  4. DELPHI 打印预览功能

    在很多应用程序中,都需要程序具有打印预览功能,以避免用户由于选择不当出现打印错误. 预览实现方式为通过创建一个Tpanel的派生类并公开它的canvas属性比例尺或视区范围,使用较为不方便,笔者通过实 ...

  5. 在网页中调用打印预览及打印设置

    在网页中调用打印预览及打印设置 以下内容为程序代码: <OBJECT  id=WB classid=CLSID:8856F961-340A-11D0-A96B-00C04FD705A2 heig ...

  6. MFC 基于多文档的打印和打印预览功能的实现

    一.基础知识 1 网上有很多的关于打印的程序,一定要看清楚,是基于对话框dialog的打印功能,还是基于文档的打印功能. 如果分不清基于对话框和文档的区别,建议新建一个单文档.多文档和对话框的工程,看 ...

  7. 计算机无法使用打印机预览,电脑中excel打印预览无法查看的处理方法

    我们在处理数据时,经常都会使用到excel应用.不过,最近一位用户反馈自己电脑中excel的打印预览突然无法查看了.这是怎么回事呢?我们要如何操作?接下来,就随系统城小编一起看看该问题的解决方法吧! ...

  8. 敲的php代码怎么预览,php如何实现打印预览功能

    php实现打印预览功能的方法:首先获取当前页的html代码:然后设置打印开始区域和打印结束区域:接着从开始和结束代码向后取html:最好确定要打印的内容即可. 推荐:<PHP视频教程> p ...

  9. 纯手写table展示树形数据,实现浏览器打印预览功能

    更新: 略显尴尬,在测试进行了各种数据测试之后,发现处理数据还是有些问题,有问题才能进步嘛,哈哈哈,还好发现及时,今天下午又进行了修改,对合并数据的地方修改了很多,详细内容见新的dealData方法: ...

最新文章

  1. HTML与CSS(图解4):表格
  2. 关于在hdfs上对数据创建外部表的原因
  3. 机房收费--组合查询
  4. Maven的发布plugin配置
  5. OSI七层模型、数据封装与解封装过程、TCP三次握手、四次挥手
  6. 网络技术等级考试知识点
  7. 前端学习(3152):react-hello-react之初始化react
  8. linux把root用户删了,linux root用户没法删除文件
  9. 大白话讲解如何给github上项目贡献代码
  10. 2013校队选拔——最短路——二分最大边的最小值
  11. 网管学习笔记-hybrid口配置
  12. 【NOIP提高】飞扬的小鸟
  13. matlab logspace 虚数,《MATLAB智能算法超级学习手册》一一1.2 矩阵的表示
  14. 精通正则表达式学习记录 第二章 入门示例扩展
  15. 【洛谷】P3367 【模板】并查集
  16. 各类编程开发网址分享
  17. 安卓毕业设计选题基于Uniapp+SSM实现的智能课堂管理APP在线学习网
  18. 微信服务商子商户支付
  19. 单片机软件设计架构(C语言)
  20. Android实践:做一个可视频交互的智能小车

热门文章

  1. Kotlin中的also、let、run、with、apply函数的用法
  2. 2D spine动画 消融
  3. LeetCode数据结构基础---2021/8/18
  4. WIN8系统的远程桌面漏洞 利用QQ拼音纯净版实现提权
  5. 程序员的10大境界,计算科学的10层楼,比尔盖茨看了会自卑,牛顿看了会落泪!
  6. 暴雪将终止与网易合作:《魔兽世界》面临在大陆暂停服务
  7. HDU - 1686 Oulipo KMP
  8. 让你平步青云的十个谈话技巧(转)
  9. 带你入门多目标跟踪(一)领域概述
  10. SyGate4.0实现局域网共享上网