Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
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' }) => (`
const templateToUri = html => (
export default function renderComponentToPrintHtml(component) {
return new Promise((resolve, reject) => {
const _el = document.createElement('div'); = 'none';
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)
// collect all the style tags in the document
const pageStyles ='style'), el => el.innerHTML).join('\n');
htmlDocTemplate({ links, pageStyles, body: _el.innerHTML })
} catch (err) {
Copy link

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment