我正在尝试将Material-UI样式与react- to -print一起用于打印组件,但我有一个特定的组件,它应该具有特定的页面大小。为此,我想这样做:
const styles = (theme: Theme) => ({
container: {
display: "none",
'@media print': {
display: "block"
},
'@page': {
size: "auto"
}
}});但是当我使用@page规则时,我得到这个错误:无法读取null的属性'addRule‘。如果我删除@page,就不会有问题。这个问题有没有简单的解决办法?
对于任何参考,这是我的完整组件:
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);我刚开始使用Material-UI样式,但我真的需要在我的可打印组件中使用本地样式。如果你想一些更简单的解决方案,我对新的想法持开放态度。
发布于 2020-12-03 20:06:51
JSS没有提供@Page解决方案,所以你需要动态创建样式并追加到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);https://stackoverflow.com/questions/61177165
复制相似问题