2017-09-25 02:06:28 +00:00
|
|
|
import React from 'react';
|
2017-07-16 21:02:13 +00:00
|
|
|
import { renderToString } from 'react-dom/server';
|
|
|
|
|
2017-09-25 02:06:28 +00:00
|
|
|
interface PrintOptions {
|
|
|
|
styles?: string;
|
|
|
|
printTimeout?: number;
|
|
|
|
popupFeatures?: object;
|
|
|
|
}
|
2017-07-16 21:02:13 +00:00
|
|
|
|
2017-09-25 02:06:28 +00:00
|
|
|
export default function(
|
|
|
|
element: React.ReactElement<any>,
|
|
|
|
opts: PrintOptions = {}
|
|
|
|
) {
|
2017-07-16 21:02:13 +00:00
|
|
|
const options = {
|
|
|
|
styles: '',
|
|
|
|
printTimeout: 500,
|
|
|
|
popupFeatures: {},
|
|
|
|
...opts
|
|
|
|
};
|
|
|
|
|
|
|
|
// Convert popupFeatures into a key=value,key=value string. See
|
|
|
|
// https://developer.mozilla.org/en-US/docs/Web/API/Window/open#Window_features
|
|
|
|
// for more information.
|
|
|
|
const featuresStr = Object.keys(options.popupFeatures)
|
|
|
|
.map(key => `${key}=${options.popupFeatures[key]}`)
|
|
|
|
.join(',');
|
|
|
|
|
|
|
|
const popup = window.open('about:blank', 'printWindow', featuresStr);
|
2017-11-30 05:35:17 +00:00
|
|
|
if (popup) {
|
|
|
|
popup.document.open();
|
|
|
|
popup.document.write(`
|
2017-07-16 21:02:13 +00:00
|
|
|
<html>
|
|
|
|
<head>
|
|
|
|
<style>${options.styles}</style>
|
|
|
|
<script>
|
|
|
|
setTimeout(function() {
|
|
|
|
window.print();
|
|
|
|
}, ${options.printTimeout});
|
|
|
|
</script>
|
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
${renderToString(element)}
|
|
|
|
<script>
|
|
|
|
// FIXME consider if we REALLY want it
|
|
|
|
var width = document.body.children[0].offsetWidth;
|
|
|
|
var height = document.body.children[0].offsetHeight;
|
|
|
|
window.moveTo(0, 0);
|
|
|
|
// FIXME Chrome could be larger (i guess?)
|
|
|
|
window.resizeTo(width + 60, height + 60);
|
|
|
|
</script>
|
|
|
|
</body>
|
|
|
|
</html>
|
|
|
|
`);
|
2017-11-30 05:35:17 +00:00
|
|
|
}
|
2017-07-16 21:02:13 +00:00
|
|
|
}
|