简体   繁体   中英

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

I am trying to control the size/orientation when printing a component using styled-components. My question is: how can I use the @page CSS at-rule, or another method to style the printing component, with styled components?

CSS @page documentation:

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

I have tried:

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

And:

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

You can't target a single component to print.
You need to hide the other elements in order your component to be the only one printed.

@page works only for changing printing rules.
@media print let you define other class styles as well just like @media screen.

You can use @media print inside a wrapper styled component, making it fullscreen, fixed with a white background.

Example:

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

To change print rules you need to add the @page into a global style and render the global style component.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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