React,打印机友好的可打印区域进行打印 (Ctrl+P)

Ami*_*avi 3 html css printing reactjs semantic-ui-react

在我的 React 应用程序中(使用SemanticUI),我在一个视图中呈现了多个组件,但是当用户想要打印页面时(例如通过在浏览器上按 Ctrl+P),我只希望可以打印一个部分

例如,如果这是用户看到的屏幕截图,则触发浏览器打印时,应在打印概览上显示绿色区域。

到目前为止,我在 SCSS 文件中

@media print{    
  .no-print, .no-print *{ display: none !important; }
}
Run Code Online (Sandbox Code Playgroud)

添加不需要的组件会使它们消失,但打印区域中有空白区域并且绿色部分没有填充页面,如果这个绿色部分是可滚动的并且应该适合几页我只看到一页(一张 A4 纸包含什么我在屏幕上看到)

@media print {
  .print-content {
    display: block;
    width: 100%;
    height: 100%;
    page-break-after: always;
    overflow: visible;
  }
}
Run Code Online (Sandbox Code Playgroud)

还没有得到相同的可打印视图

在此处输入图片说明 这是此屏幕截图的代码

import React from 'react'
import { Grid, Image } from 'semantic-ui-react'

const GridExampleCelled = () => (
  <Grid celled>
    {/*another Grid.Row*/}

    <Grid.Row>
      <Grid.Column width={3}>
        <Image src='/images/wireframe/image.png' />
      </Grid.Column>
      <Grid.Column width={10}> /* This should be the component to print */
        <p> EveryThing Wrapped in this Grid should be printed </p>
      </Grid.Column>
      <Grid.Column width={3}> 
        <Image src='/images/wireframe/image.png' />
      </Grid.Column>
    </Grid.Row>
  </Grid>
)

export default GridExampleCelled
Run Code Online (Sandbox Code Playgroud)

小智 8

不要将此视为涵盖所有用例的最终解决方案。但是你可以试试这个片段的想法,看看它是否足以解决你的问题。我在最近的项目中执行了类似的任务,这种方法可以根据需要发挥作用。

@media print {
  @page {
    size: landscape;
  }
  body * {
    visibility: hidden;
  }
  .section-to-print, .section-to-print * {
    visibility: visible;
  }
  .section-to-print {
    position: absolute;
    left: 0;
    top: 0;
  }
}
Run Code Online (Sandbox Code Playgroud)

它将隐藏页面上的所有内容。然后将.section-to-print类添加到要打印的区域。除非您有一些覆盖 css 的内容,否则它应该按照您希望的方式工作。

重要的一点是,如果您在全局范围内使用此 CSS,它将隐藏所有没有的内容,.section-to-print并且打印页面将为空白。因此,仅在需要时才将其注入样式表可能是明智之举。

如果这有帮助,请告诉我。