繁体   English   中英

如何使用样式组件来设置组件的打印样式?

[英]how to use styled components to style the printing of a component?

我试图在使用样式组件打印组件时控制大小/方向。 我的问题是:如何使用 @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;
  }
`;

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

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

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

例子:

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>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM