Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-to-print

Package Overview
Dependencies
Maintainers
1
Versions
94
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-to-print - npm Package Compare versions

Comparing version 1.0.21 to 2.0.0-alpha.7

lib/index.d.ts

2

lib/index.js

@@ -1,2 +0,2 @@

"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var React=_interopDefault(require("react")),reactDom=require("react-dom"),propTypes=_interopDefault(require("prop-types")),classCallCheck=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},createClass=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),inherits=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},possibleConstructorReturn=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},toConsumableArray=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)},ReactToPrint=function(e){function t(){var e,n,o,r;classCallCheck(this,t);for(var a=arguments.length,i=Array(a),l=0;l<a;l++)i[l]=arguments[l];return n=o=possibleConstructorReturn(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(i))),o.handlePrint=function(){var e=o.props,t=e.content,n=e.copyStyles,r=e.onAfterPrint,a=e.pageStyle;console.log(a);var i=window.open("","Print","status=no, toolbar=no, scrollbars=yes","false");r&&(i.onbeforeunload=r);var l=t(),c=reactDom.findDOMNode(l),s=[].concat(toConsumableArray(c.getElementsByTagName("img"))),u=document.querySelectorAll('link[rel="stylesheet"]');o.imageTotal=s.length,o.imageLoaded=0,o.linkTotal=u.length,o.linkLoaded=0;var d=function(e){"image"===e?o.imageLoaded++:"link"===e&&o.linkLoaded++,o.imageLoaded===o.imageTotal&&o.linkLoaded===o.linkTotal&&o.triggerPrint(i)};if([].concat(toConsumableArray(s)).forEach(function(e){/^data:/.test(e.src)&&(e.crossOrigin="anonymous"),e.setAttribute("src",e.src),e.onload=d.bind(null,"image"),e.onerror=d.bind(null,"image"),e.crossOrigin="use-credentials"}),!1!==n){var p=document.querySelectorAll('style, link[rel="stylesheet"]');[].concat(toConsumableArray(p)).forEach(function(e){var t=(i.contentDocument||i.document).createElement(e.tagName);e.textContent?t.textContent=e.textContent:e.innerText&&(t.innerText=e.innerText);[].concat(toConsumableArray(e.attributes)).forEach(function(e){var n=e.nodeValue;if("href"===e.nodeName&&!1===/^https?:\/\//.test(e.nodeValue)&&!1===/^blob:/.test(e.nodeValue)){var o="../"===e.nodeValue.substr(0,3)?document.location.pathname.replace(/[^/]*$/,""):"/";n=n.replace(/\/+/,""),n=document.location.protocol+"//"+document.location.host+o+n}t.setAttribute(e.nodeName,n)}),"LINK"===e.tagName&&(t.onload=d.bind(null,"link"),t.onerror=d.bind(null,"link")),i.document.head.appendChild(t)})}if(document.body.className){document.body.className.split(" ").filter(function(e){return e}).map(function(e){return i.document.body.classList.add(e)})}o.props.bodyClass.length&&i.document.body.classList.add(o.props.bodyClass);var f=void 0===a?"@page { size: auto; margin: 0mm; } @media print { body { -webkit-print-color-adjust: exact; } }":a,m=i.document.createElement("style");m.appendChild(i.document.createTextNode(f)),i.document.head.appendChild(m),i.document.body.innerHTML=c.outerHTML,0!==o.imageTotal&&!1!==n||o.triggerPrint(i),o.props.debug&&(console.log("** DEBUG MODE **"),console.log(i.document))},r=n,possibleConstructorReturn(o,r)}return inherits(t,e),createClass(t,[{key:"triggerPrint",value:function(e){var t=this;this.props.onBeforePrint&&this.props.onBeforePrint(),setTimeout(function(){t.props.debug||(e.print(),t.props.closeAfterPrint&&e.close())},500)}},{key:"render",value:function(){var e=this;return React.cloneElement(this.props.trigger(),{ref:function(t){return e.triggerRef=t},onClick:this.handlePrint})}}]),t}(React.Component);ReactToPrint.defaultProps={copyStyles:!0,closeAfterPrint:!0,bodyClass:"",debug:!1},module.exports=ReactToPrint;
"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}function _defineProperty(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&_setPrototypeOf(e,t)}function _getPrototypeOf(e){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _possibleConstructorReturn(e,t){return!t||"object"!=typeof t&&"function"!=typeof t?_assertThisInitialized(e):t}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_nonIterableSpread()}function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var t=0,r=new Array(e.length);t<e.length;t++)r[t]=e[t];return r}}function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}var React=_interopDefault(require("react")),reactDom=require("react-dom"),propTypes=_interopDefault(require("prop-types")),ReactToPrint=function(e){function t(){var e,r;_classCallCheck(this,t);for(var n=arguments.length,o=new Array(n),i=0;i<n;i++)o[i]=arguments[i];return r=_possibleConstructorReturn(this,(e=_getPrototypeOf(t)).call.apply(e,[this].concat(o))),_defineProperty(_assertThisInitialized(_assertThisInitialized(r)),"removeWindow",function(e){setTimeout(function(){e.parentNode.removeChild(e)},500)}),_defineProperty(_assertThisInitialized(_assertThisInitialized(r)),"triggerPrint",function(e){var t=r.props,n=t.onBeforePrint,o=t.onAfterPrint;n&&n(),setTimeout(function(){e.contentWindow.focus(),e.contentWindow.print(),r.removeWindow(e),o&&o()},500)}),_defineProperty(_assertThisInitialized(_assertThisInitialized(r)),"handlePrint",function(){var e=r.props,t=e.bodyClass,n=e.content,o=e.copyStyles,i=e.pageStyle,a=n();if(void 0!==a){var l=document.createElement("iframe");l.style.position="absolute",l.style.top="-1000px",l.style.left="-1000px";var s=reactDom.findDOMNode(a),c=document.querySelectorAll('link[rel="stylesheet"]');r.linkTotal=c.length||0,r.linksLoaded=[],r.linksErrored=[];var u=function(e,t){t?r.linksLoaded.push(e):(console.error("'react-to-print' was unable to load a link. It may be invalid. 'react-to-print' will continue attempting to print the page. The link the errored was:",e),r.linksErrored.push(e)),r.linksLoaded.length+r.linksErrored.length===r.linkTotal&&r.triggerPrint(l)};l.onload=function(){window.navigator&&window.navigator.userAgent.indexOf("Trident/7.0")>-1&&(l.onload=null);var e=l.contentDocument||l.contentWindow.document,n=_toConsumableArray(s.querySelectorAll("canvas"));e.open(),e.write(s.outerHTML),e.close();var a=void 0===i?"@page { size: auto; margin: 0mm; } @media print { body { -webkit-print-color-adjust: exact; } }":i,c=e.createElement("style");c.appendChild(e.createTextNode(a)),e.head.appendChild(c),t.length&&e.body.classList.add(t);if(_toConsumableArray(e.querySelectorAll("canvas")).forEach(function(e,t){e.getContext("2d").drawImage(n[t],0,0)}),!1!==o){_toConsumableArray(document.querySelectorAll('style, link[rel="stylesheet"]')).forEach(function(t,r){if("STYLE"===t.tagName){var n=e.createElement(t.tagName);if(t.sheet){for(var o="",i=0;i<t.sheet.cssRules.length;i++)"string"==typeof t.sheet.cssRules[i].cssText&&(o+="".concat(t.sheet.cssRules[i].cssText,"\r\n"));n.setAttribute("id","react-to-print-".concat(r)),n.appendChild(e.createTextNode(o)),e.head.appendChild(n)}}else{var a=_toConsumableArray(t.attributes),l=a.filter(function(e){return"href"===e.nodeName});if(!!l.length&&!!l[0].nodeValue){var s=e.createElement(t.tagName);a.forEach(function(e){s.setAttribute(e.nodeName,e.nodeValue)}),s.onload=u.bind(null,s,!0),s.onerror=u.bind(null,s,!1),e.head.appendChild(s)}else console.warn("'react-to-print' encountered a <link> tag with an empty 'href' attribute. In addition to being invalid HTML, this can cause problems in many browsers, and so the <link> was not loaded. The <link> is:",t),u(t,!0)}})}0!==r.linkTotal&&!1!==o||r.triggerPrint(l)},document.body.appendChild(l)}else console.error("Refs are not available for stateless components. For 'react-to-print' to work only Class based components can be printed")}),_defineProperty(_assertThisInitialized(_assertThisInitialized(r)),"setRef",function(e){r.triggerRef=e}),r}return _inherits(t,React.Component),_createClass(t,[{key:"render",value:function(){var e=this.props.trigger;return React.cloneElement(e(),{onClick:this.handlePrint,ref:this.setRef})}}]),t}();_defineProperty(ReactToPrint,"defaultProps",{bodyClass:"",copyStyles:!0,onAfterPrint:void 0,onBeforePrint:void 0,pageStyle:void 0}),module.exports=ReactToPrint;
//# sourceMappingURL=index.js.map
{
"name": "react-to-print",
"version": "1.0.21",
"version": "2.0.0-alpha.7",
"description": "Print React components in the browser",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"files": [

@@ -11,2 +12,4 @@ "lib"

"build": "rollup -c",
"build:ts": "tsc -p .",
"lint": "eslint . --color",
"webpack": "webpack --progress",

@@ -31,23 +34,36 @@ "webpack-dev-server": "webpack-dev-server --colors --progress"

"homepage": "https://github.com/gregnb/react-to-print#readme",
"peerDependencies": {
"react": "^15.0.0 || ^16.0.0",
"react-dom": "^15.0.0 || ^16.0.0"
},
"dependencies": {
"prop-types": "^15.6.0",
"react": "^16.2.0"
"prop-types": "^15.6.2"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-external-helpers": "^6.22.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-react-remove-prop-types": "^0.4.13",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"eslint": "^4.12.1",
"react-dom": "^16.2.0",
"@babel/cli": "^7.2.0",
"@babel/core": "^7.2.2",
"@babel/plugin-proposal-class-properties": "^7.2.1",
"@babel/plugin-proposal-object-rest-spread": "^7.2.0",
"@babel/preset-env": "^7.2.0",
"@babel/preset-react": "^7.0.0",
"@types/prop-types": "^15.5.8",
"@types/react": "^16.7.18",
"@types/react-dom": "^16.0.11",
"babel-eslint": "^10.0.1",
"babel-loader": "^8.0.4",
"babel-plugin-transform-react-remove-prop-types": "^0.4.21",
"eslint": "^5.10.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-jsx-a11y": "^6.1.2",
"eslint-plugin-react": "^7.11.1",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"rollup": "^0.52.0",
"rollup-plugin-babel": "^3.0.2",
"rollup-plugin-babel": "^4.1.0",
"rollup-plugin-commonjs": "^8.2.6",
"rollup-plugin-replace": "^2.0.0",
"rollup-plugin-copy": "~0.2.0",
"rollup-plugin-replace": "^2.1.0",
"rollup-plugin-uglify": "^2.0.1",
"typescript": "^3.0.0",
"webpack": "^3.9.1",

@@ -54,0 +70,0 @@ "webpack-dev-server": "^2.9.5"

@@ -11,7 +11,7 @@ <div align="center">

So you've created a React component but would love to give end users the ability to print out the contents of that component. This package aims to solve that by popping up a new print window with CSS styles copied over as well.
So you've created a React component but would love to give end users the ability to print out the contents of that component. This package aims to solve that by popping up a new print window with CSS styles copied over as well.
## Install
`npm install react-to-print --save-dev `
`npm install react-to-print --save-dev`

@@ -22,10 +22,10 @@ ## Demo

## Usage
## Example
### Calling from class components
```js
import React from 'react';
import ReactToPrint from 'react-to-print';
import React from "react";
import ReactToPrint from "react-to-print";
class ComponentToPrint extends React.Component {

@@ -75,7 +75,55 @@ render() {

}
```
### Calling from functional components with [hooks](https://reactjs.org/docs/hooks-intro.html)
```js
import React, { useRef } from 'react';
import ReactToPrint from 'react-to-print';
class ComponentToPrint extends React.Component {
render() {
return (
<table>
<thead>
<th>column 1</th>
<th>column 2</th>
<th>column 3</th>
</thead>
<tbody>
<tr>
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
</tr>
<tr>
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
</tr>
<tr>
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
</tr>
</tbody>
</table>
);
}
}
const Example = () => {
const componentRef = useRef();
return (
<div>
<ReactToPrint
trigger={() => <button>Print this out!</button>}
content={() => componentRef.current}
/>
<ComponentToPrint ref={componentRef} />
</div>
);
};
```
## API

@@ -87,11 +135,16 @@

|Name|Type|Description
|:--:|:-----|:-----|
|**`trigger`**|function|A function that returns a React Component or HTML element
|**`content`**|function|A function that returns a component reference value. The content of this reference value is then used for print
|**`copyStyles`**|boolean|Copies all &lt;style> and &lt;link type="stylesheet" /> from <head> inside the parent window into the print window. (default: true)
|**`onBeforePrint`**|function|A callback function that triggers before print
|**`onAfterPrint`**|function|A callback function that triggers after print
|**`closeAfterPrint`**|boolean|Close the print window after action
|**`pageStyle`**|string|Override default print window styling
|**`bodyClass`**|string|Optional class to pass to the print window body
| Name | Type | Description |
| :-------------------: | :------- | :---------------------------------------------------------------------------------------------------------------------------------- |
| **`trigger`** | function | A function that returns a React Component or HTML element |
| **`content`** | function | A function that returns a component reference value. The content of this reference value is then used for print |
| **`copyStyles`** | boolean | Copies all &lt;style> and &lt;link type="stylesheet" /> from <head> inside the parent window into the print window. (default: true) |
| **`onBeforePrint`** | function | A callback function that triggers before print |
| **`onAfterPrint`** | function | A callback function that triggers after print |
| **`closeAfterPrint`** | boolean | Close the print window after action |
| **`pageStyle`** | string | Override default print window styling |
| **`bodyClass`** | string | Optional class to pass to the print window body |
## FAQ
**Why does `react-to-print` skip `<link rel="stylesheet" href="">` tags?**
`<link>`s with empty `href` attributes are [INVALID HTML](https://www.w3.org/TR/html50/document-metadata.html#attr-link-href). In addition, they can cause all sorts of [undesirable behavior](https://gtmetrix.com/avoid-empty-src-or-href.html). For example, many browsers - including modern ones, when presented with `<link href="">` will attempt to load the current page. Some even attempt to load the current page's parent directory.

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc