首页 > 解决方案 > 如何使用样式化的组件来设置组件的打印样式?

问题描述

我试图在使用样式组件打印组件时控制大小/方向。我的问题是:如何使用@page CSS at-rule 或其他方法来设置打印组件的样式,以及样式化的组件?

CSS @page 文档:

https://developer.mozilla.org/en-US/docs/Web/CSS/@page

我努力了:

const PrintSchedulesContainer = styled.div`
  display: none;
  @media print and (min-width: 480px) {
    padding: none;
    margin: none;
  }
`;

和:

const PrintSchedulesContainer = styled.div`
  display: none;
  @page {
    size: landscape;
  }
`;

标签: javascriptcssreactjsstyled-components

解决方案


您不能针对单个组件进行打印。
您需要隐藏其他元素才能使您的组件成为唯一打印的组件。

@page仅适用于更改打印规则。
@media print允许您定义其他类样式,就像@media screen 一样。

您可以在包装样式的组件中使用@media print,使其全屏显示,并固定为白色背景。

例子:

const PrintableBodyWrapper = styled.div`
  @media print {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: white;
    display: flex;
    justify-content: center;
    align-items: center;
  }
`;

function App() {
  return (
    <div className="App">
        <PrintableBodyWrapper>
          <div style={{ width: 100, height: 100, background: "grey" }}>
            I will be printed
          </div>
        </PrintableBodyWrapper>
    </div>
  );
}

要更改打印规则,您需要将 @page 添加到全局样式中并呈现全局样式组件。

import styled, { createGlobalStyle } from "styled-components";

const GlobalStyle = createGlobalStyle`
  @page {
    size: landscape;
    margin: 5cm;
`;

const PrintableBodyWrapper = styled.div`
  @media print {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: black;
    display: flex;
    justify-content: center;
    align-items: center;
  }
`;

function App() {
  return (
    <div className="App">
        <GlobalStyle />
        <PrintableBodyWrapper>
          <div style={{ width: 100, height: 100, background: "grey" }}>
            I will be printed
          </div>
        </PrintableBodyWrapper>
    </div>
  );
}

推荐阅读