Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material-UI @page rule?

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.

like image 806
AxelLeon Avatar asked Oct 17 '25 19:10

AxelLeon


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);
like image 91
jerry_p Avatar answered Oct 20 '25 07:10

jerry_p



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!