Material-UI @page rule?

Viewed 788

I'm trying to use the Material-UI styles with react-to-print for printing components, but I have an specific component that should have an specific page size. For that, I would like to do something like this:

const styles = (theme: Theme) => ({
 container: {
     display: "none",
     '@media print': {
         display: "block"
     },
     '@page': {
         size: "auto"
     }
}});

But when I use the @page rule I get this error: Cannot read property 'addRule' of null. If I remove @page, there is no problem. Is there an easy fix for this?

For any reference, this is my complete component:

import React, { Component } from 'react';
import { Theme, WithStyles, withStyles } from '@material-ui/core';

interface IProps extends WithStyles<typeof styles> {

}

interface IState {

}

const styles = (theme: Theme) => ({
    container: {
        display: "none",
        '@media print': {
            display: "block"
        },
        '@page': {
            size: "5cm 5cm"
        }
    }
});

class ComponentToPrint extends Component<IProps, IState> {
    render() {
        const { classes } = this.props;
        return (
            <div className={classes.container}>
                Hola
            </div>
        );
    }
}

export default withStyles(styles)(ComponentToPrint);

I'm new using the Material-UI styles, but I really need to have local styles in my printable components. If you think in some easier solution, I'm open to new ideas.

1 Answers

JSS not provide @Page solution so you need dynamic create style and append into head.

const css = '@page { size: landscape; }';
const head = document.head || document.getElementsByTagName('head')[0];
const style = document.createElement('style');

style.media = 'print';
style.appendChild(document.createTextNode(css));

head.appendChild(style);
window.print();
head.removeChild(style);
Related