Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
react-to-print
Advanced tools
The react-to-print npm package allows you to easily print React components. It provides a simple way to trigger the print functionality for specific parts of your application, making it useful for generating printable content from your React components.
Basic Printing
This feature allows you to print a specific React component. The `ReactToPrint` component takes a `trigger` prop, which is a function that returns a React element to trigger the print action, and a `content` prop, which is a function that returns the component to be printed.
import React, { useRef } from 'react';
import ReactToPrint from 'react-to-print';
class ComponentToPrint extends React.Component {
render() {
return (
<div>
<h1>Hello World!</h1>
<p>This is a printable component.</p>
</div>
);
}
}
const MyComponent = () => {
const componentRef = useRef();
return (
<div>
<ReactToPrint
trigger={() => <button>Print this out!</button>}
content={() => componentRef.current}
/>
<ComponentToPrint ref={componentRef} />
</div>
);
};
export default MyComponent;
Custom Styling for Print
This feature allows you to apply custom styles to the printed content. The `pageStyle` prop can be used to define CSS styles that will be applied when printing.
import React, { useRef } from 'react';
import ReactToPrint from 'react-to-print';
class ComponentToPrint extends React.Component {
render() {
return (
<div>
<h1 style={{ color: 'red' }}>Hello World!</h1>
<p>This is a printable component with custom styles.</p>
</div>
);
}
}
const MyComponent = () => {
const componentRef = useRef();
return (
<div>
<ReactToPrint
trigger={() => <button>Print this out!</button>}
content={() => componentRef.current}
pageStyle="@page { size: auto; margin: 20mm; } @media print { body { -webkit-print-color-adjust: exact; } }"
/>
<ComponentToPrint ref={componentRef} />
</div>
);
};
export default MyComponent;
Handling Print Callbacks
This feature allows you to handle callbacks before and after the print action. The `onBeforePrint` and `onAfterPrint` props can be used to execute functions at these stages.
import React, { useRef } from 'react';
import ReactToPrint from 'react-to-print';
class ComponentToPrint extends React.Component {
render() {
return (
<div>
<h1>Hello World!</h1>
<p>This is a printable component.</p>
</div>
);
}
}
const MyComponent = () => {
const componentRef = useRef();
const handleBeforePrint = () => {
console.log('Before print');
};
const handleAfterPrint = () => {
console.log('After print');
};
return (
<div>
<ReactToPrint
trigger={() => <button>Print this out!</button>}
content={() => componentRef.current}
onBeforePrint={handleBeforePrint}
onAfterPrint={handleAfterPrint}
/>
<ComponentToPrint ref={componentRef} />
</div>
);
};
export default MyComponent;
Print.js is a library that provides a simple way to print content from the web. It supports printing HTML elements, PDFs, images, and JSON data. Compared to react-to-print, Print.js is more versatile in terms of the types of content it can print, but it is not specifically designed for React components.
React-print is another library for printing React components. It offers similar functionality to react-to-print but is less popular and has fewer features. It is a simpler alternative for basic printing needs.
Print the content of a React component.
npm install --save react-to-print
import { useReactToPrint } from "react-to-print";
import { useRef } from "react";
const contentRef = useRef<HTMLDivElement>(null);
const reactToPrintFn = useReactToPrint({ contentRef });
return (
<div>
<button onClick={() => reactToPrintFn()}>Print</button>
<div ref={contentRef}>Content to print</div>
</div>
);
It is also possible to lazy set the ref if your content being printed is dynamic. See the LazyContent
example for more. This can also be useful for setting the ref in non-React code, such as util functions.
Option | Type | Description |
---|---|---|
bodyClass | string | One or more class names to pass to the print window, separated by spaces |
contentRef | React.RefObject<Element | Text> | The ref pointing to the content to be printed. Alternatively, pass the ref directly to the callback returned by useReactToPrint |
copyShadowRoots | boolean | Copy shadow root content into the print window. Warning: Use with care if you print large documents as traversing these can be slow. |
documentTitle | string | Set the title for printing when saving as a file |
fonts | { family: string, source: string; weight?: string; style?: string; }[] | A list of fonts to load into the printing iframe. This is useful if you are using custom fonts |
ignoreGlobalStyles | boolean | Ignore all <style> and <link type="stylesheet" /> tags |
nonce | string | Set the nonce attribute for allow-listing script and style elements for Content Security Policy (CSP) |
onAfterPrint | () => void | Callback function that triggers after the print dialog is closed regardless of if the user selected to print or cancel |
onBeforePrint | () => Promise<void> | Callback function that triggers before print. This can be used to change the content on the page before printing as an alternative to, or in conjunction with, @media print queries |
onPrintError | (errorLocation: 'onBeforePrint' | 'print', error: Error) => void | Called if there is a printing error serious enough that printing cannot continue. Currently limited to Promise rejections in onBeforePrint , and print . |
pageStyle | string | react-to-print sets some basic styles to help improve page printing, notably, removing the header and footer that most browsers add. Use this to override these styles and provide your own |
preserveAfterPrint | boolean | Preserve the print iframe after printing. This can be useful for debugging by inspecting the print iframe |
print | (iframe: HTMLIFrameElement) => Promise<void> | If passed, this function will be used instead of window.print to print the content. Use this to print in non-browser environments such as Electron |
suppressErrors | boolean | When passed, prevents console logging of errors |
react-to-print
should be compatible with most modern browsers.
While printing on mobile browsers generally works, printing within a WebView (when your page is opened by an app such as Facebook or Slack, but not by the full browser itself) is known to generally not work. Some WebViews don't make the correct API available. Others make it available but cause printing to no-op.
We are actively researching resolutions to this issue, but it likely requires changes by Google/Chromium and Apple/WebKit. See #384 for more information. If you know of a way we can solve this your help would be greatly appreciated.
window.print
)onAfterPrint
may fire immediately (before the print dialog is closed) on newer versions of Safari where window.print
does not blockType 'undefined' is not assignable to type 'ReactInstance | null'.
. You likely need to set your ref to initially be null
: useRef(null)
documentTitle
will not work if react-to-print
is run within an iframe
. If react-to-print
is run within an iframe
and your script has access to the parent document, you may be able to manually set and then restore the parent document's title
during the print. This can be done by leveraging the onBeforePrint
and onAfterPrint
callbacks.
When printing, only styles that directly target the printed nodes will be applied as the parent nodes of the printed nodes will not exist in the print DOM. For example, in the code below, if the <p>
tag is the root of the ComponentToPrint
then the red styling will not be applied. Be sure to target all printed content directly and not from unprinted parents.
<div className="parent">
<p>Hello</p>
</div>
div.parent p { color:red; }
The connect
method from react-redux
returns a functional component that cannot be assigned a reference to be used within the contentRef
. To use a component wrapped in connect
within contentRef
, create an intermediate component that simply renders your component wrapped in connect
. See 280 for more.
When rendering multiple components to print, ensure each is passed a unique ref. Then, either use a unique useReactToPrint
call for each component, or, using a single useReactToPrint
call pass the refs at print-time to the printing function returned by the hook. If you share refs across components only the last component will be printed. See 323 for more.
The simplest way to hide or show content during printing is to use a CSS Media Query.
.printContent {
display: none;
@media print {
display: block;
}
}
const contentRef = useRef<HTMLDivElement>(null);
const reactToPrintFn = useReactToPrint({ contentRef });
return (
<div>
<button onClick={reactToPrintFn}>Print</button>
<div className="printContent" ref={contentRef}>Content to print</div>
</div>
);
react-to-print
be used to download a PDF without using the Print Preview window?Not directly. We aren't able to print a PDF as we lose control once the print preview window opens. However, it is possible to use react-to-print
to gather the content you want to print and pass it to a library that can generate a PDF.
const handlePrint = useReactToPrint({
...,
print: async (printIframe: HTMLIframeElement) => {
// Do whatever you want here, including asynchronous work
await generateAndSavePDF(printIframe);
},
});
For examples of how others have done this, see #484
react-to-print
be used to change the settings within the print preview dialog?No. The window.print
API does not provide a way to change these settings. Only various CSS hints can be provided, with each browser potentially treating them differently.
ComponentToPrint
be a Class component?Not directly. To print a Class based component you will need to manually forward the contentRef
as a prop:
class ComponentToPrint extends Component {
render() {
return (
<div ref={this.props.innerRef}>
Print content
</div>
)
}
}
function App {
const contentRef = useRef(null);
const handlePrint = useReactToPrint({ contentRef });
return (
<div>
<button onClick={handlePrint}>Print</button>
<ComponentToPrint innerRef={contentRef} />
</div>
);
}
onAfterPrint
fire even if the user cancels printingonAfterPrint
fires when the print dialog closes, regardless of why it closes. This is the behavior of the onafterprint
browser event.
react-to-print
skip <link rel="stylesheet" href="">
tags<link>
s with empty href
attributes are invalid HTML. In addition, they can cause all sorts of undesirable behavior. 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.
Note: related to the above, img
tags with empty src
attributes are also invalid, and we may not attempt to load them.
ComponentToPrint
show only while printingIf you've created a component that is intended only for printing and should not render in the parent component, wrap that component in a div
with style set to { display: "none" }
, like so:
<div style={{ display: "none" }}><ComponentToPrint ref={componentRef} /></div>
This will hide ComponentToPrint
but keep it in the DOM so that it can be copied for printing.
onBeforePrint
Recall that setting state is asynchronous. As such, you need to pass a Promise
and wait for the state to update.
const [isPrinting, setIsPrinting] = useState(false);
const contentRef = useRef(null);
// We store the resolve Promise being used in `onBeforePrint` here
const promiseResolveRef = useRef(null);
// We watch for the state to change here, and for the Promise resolve to be available
useEffect(() => {
if (isPrinting && promiseResolveRef.current) {
// Resolves the Promise, letting `react-to-print` know that the DOM updates are completed
promiseResolveRef.current();
}
}, [isPrinting]);
const handlePrint = useReactToPrint({
contentRef,
onBeforePrint: () => {
return new Promise((resolve) => {
promiseResolveRef.current = resolve;
setIsPrinting(true);
});
},
onAfterPrint: () => {
// Reset the Promise resolve so we can print again
promiseResolveRef.current = null;
setIsPrinting(false);
}
});
Note: for Class components, pass the Promise resolve
to the callback for this.setState
: this.setState({ isPrinting: false }, resolve)
Unfortunately there is no standard browser API for interacting with the print dialog. All react-to-print
is able to do is open the dialog and give it the desired content to print. We cannot modify settings such as the default paper size, if the user has background graphics selected or not, etc.
video
elementsreact-to-print
tries to wait for video
elements to load before printing but a large part of this is up to the browser. Further, the image displayed will usually be the first frame of the video, which might not be what you expect to show. To ensure the proper image is displayed in the print we highly recommend setting the poster
attribute of the video
, which allows specifying an image to be a placeholder for the video until the video loads.
react-to-print
can be used for printing in Electron, but you will need to provide your own print
method since Electron does not natively support the window.print
method. Please see this answer on StackOverflow for how to do this.
There is a fully-working example of how to use react-to-print
with Electron available here.
link
elements not displaying styles properlySome frameworks such as Ruby on Rails will set media="screen"
on <link>
elements that don't have screen
set. This can cause styles to appear incorrectly when printing. To fix, explicitly set media="screen"
on your <link>
elements. For <link>
elements meant to apply only when printing, set media="print"
.
While you should be able to place these styles anywhere, sometimes the browser doesn't always pick them up. To force orientation of the page you can include the following in the component being printed:
<style type="text/css" media="print">{"\
@page {\ size: landscape;\ }\
"}</style>
The default page size is usually A4. Most browsers do not allow JavaScript or CSS to set the page size. For the browsers that do, it is usually done using the CSS page size
property. Check caniuse
to see if the browsers you develop against support this.
@media print {
@page {
size: 50mm 150mm;
}
}
To set custom margin to the page,
First, create a function to return the page margin,
const getPageMargins = () => {
return `@page { margin: ${marginTop} ${marginRight} ${marginBottom} ${marginLeft} !important; }`;
};
Now, within the JSX call this function within the style tags,
<style>{getPageMargins()}</style>
PS: This style tag should be inside the component that is being passed in as the content ref.
In the component that is passed in as the content ref, add the following:
@media print {
@page { size: landscape; }
}
Instead of using { display: 'none'; }
, try using { overflow: hidden; height: 0; }
pageStyle
pageStyle
should be a CSS string. For example: ".divider { break-after: always; }"
Many have found setting the following CSS helpful. See #26 for more.
@media print {
html, body {
height: 100vh; /* Use 100% here to support printing more than a single page*/
margin: 0 !important;
padding: 0 !important;
overflow: hidden;
}
}
Another thing to try, especially if you are seeing this issue on mobile browsers, is to set preserveAfterPrint: true
as it's possible the browser is causing the print iframe to be removed before printing has completed.
We often (#327, #343, #382) see issues reported where the developer is using Bootstrap or a similar grid system, and everything works great until the user goes to print and suddenly it seems the styles are off. We've found that often the issue is the grid library uses the smallest sized columns during printing, such as the xs
size on Bootstrap's grid, a size developers often don't plan for. The simplest solution is to ensure your grid will adapt to this size appropriately, though this may not be acceptable since you may want the large view to print rather than the smaller view. Another solution is to override the grid column definition. Some newer versions of libraries have specific tools for dealing with printing, for example, Bootstrap 4's Display property.
What to know:
break-inside
(replaces page-break-inside
)break-before
(replaces page-break-before
)break-after
(replaces page-break-after
)Define a page-break class to apply to elements which could be sensibly split into a page.
<div className="print-container" style={{ margin: "0", padding: "0" }}>
{listOfContent.map(yourContent => (
<>
<div className="page-break" />
<div>{yourContent}</div>
</>
)}
</div>
In your styles, define your @media print
styles, which should include setting your preference for CSS page-break-
(see w3's reference for options) to auto
, and ensuring that your page-break
element does not affect non-print styles.
@media all {
.page-break {
display: none;
}
}
@media print {
html, body {
height: initial !important;
overflow: initial !important;
-webkit-print-color-adjust: exact;
}
}
@media print {
.page-break {
margin-top: 1rem;
display: block;
page-break-before: auto;
}
}
@page {
size: auto;
margin: 20mm;
}
If your content rendered as print media does not automatically break multi-page content into multiple pages, the issue may be
CSS page-break-
properties to define how your document should behave when printedoverflow: scroll
, when rendered to print, will result in cut off content instead of page breaks to include the contentposition: absolute
, when rendered to print, may result in reformatted, rotated, or re-scaled content, causing unintended affects to print page layout and page breaksflex
may interfere with page breaks, try using display: block
If you need to print the content of a scrolling container, you may encounter the following issues:
To solve these problems, you need to modify the properties of the scrolling container when printing. You can pass a function to the print
property, which will be called when printing. In this function, you can use the DOM API to query the scrolling container that needs to be modified, and then modify its properties to control the scroll position.
const customToPrint = (printWindow) => {
const printContent = printWindow.contentDocument || printWindow.contentWindow?.document;
const printedScrollContainer = printContent.querySelector('.scroll-container');
const originScrollContainer = document.querySelector('.scroll-container');
// Set the scroll position of the printed container to match the origin container
printedScrollContainer.scrollTop = originScrollContainer.scrollTop;
// You can also set the `overflow` and `height` properties of the printed container to show all content.
// printedScrollContainer.style.overflow = "visible";
// printedScrollContainer.style.height = "fit-content";
printWindow.contentWindow.print();
}
const handlePrint = useReactToPrint({
// ...
print: customToPrint,
});
In addition to the methods in the above example, you can also simply add a CSS class name to the scrolling container when printing to show all content.
Set the container to overflow: visible; height: fit-content
when printing, cancel the scrolling behavior when the content overflows, and make the height adapt to the content.
@media print {
.scroll-container {
overflow: visible;
height: fit-content;
}
}
Note:
- If the styles do not take effect, you can try using the
!important
modifier.- The styles provided in the above instructions are for reference only. Complex situations may require more styles to achieve the desired result.
NOTE: The library is built and tested locally using Node ^20.
npm ci
npm start
FAQs
Print React components in the browser
The npm package react-to-print receives a total of 569,343 weekly downloads. As such, react-to-print popularity was classified as popular.
We found that react-to-print demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.