Render a react component to an html document that shares all the links and styles for printing, and convert it to a data URI for window.open
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { PureComponent, PropTypes } from 'react'; | |
import { render, unmountComponentAtNode } from 'react-dom'; | |
import { Base64 } from 'js-base64'; | |
import Promise from 'bluebird'; | |
const htmlDocTemplate = ({ links, pageStyles, body, title = 'Print' }) => (` | |
<html> | |
<head> | |
<title>${title}</title> | |
${links} | |
<style>${pageStyles}</style> | |
</head> | |
<body>${body}</body> | |
<script>window.print();</script> | |
</html> | |
`); | |
const templateToUri = html => ( | |
`data:text/html;base64,${encodeURIComponent(Base64.encode(html))}` | |
); | |
export default function renderComponentToPrintHtml(component) { | |
return new Promise((resolve, reject) => { | |
const _el = document.createElement('div'); | |
_el.style.display = 'none'; | |
document.body.appendChild(_el); | |
try { | |
render(component, _el); | |
// collect all the link tags that link to stylesheets | |
const links = _.chain(document.getElementsByTagName('link')) | |
.filter(l => l.rel && l.rel.toLowerCase() == 'stylesheet') | |
.map(l => l.outerHTML) | |
.value().join('\n'); | |
// collect all the style tags in the document | |
const pageStyles = _.map(document.getElementsByTagName('style'), el => el.innerHTML).join('\n'); | |
resolve( | |
templateToUri( | |
htmlDocTemplate({ links, pageStyles, body: _el.innerHTML }) | |
) | |
); | |
unmountComponentAtNode(_el); | |
} catch (err) { | |
reject(err); | |
} | |
document.body.removeChild(_el); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This isn't an asynchronous function as written, but it could be re-written to use a web worker (web workers don't have access to the DOM so this is a lot more work)