简体   繁体   English

反应如何为不同的组件打印横向/纵向

[英]React how to print landscape / portrait for different components

Our React app has ~10 different routes and we'd like for them all to be printable.我们的 React 应用程序有大约 10 条不同的路线,我们希望它们都可以打印。 We're using the css print media query to clean styles up for print, and the frontend has a button that calls window.print() on click.我们使用 css 打印媒体查询来清理 styles 以进行打印,并且前端有一个按钮,单击时调用window.print()

Amongst the 10 routes, 7 of the pages look better with landscape whereas the other 3 are better as portrait .在这 10 条路线中,有 7 条页面看起来更适合landscape ,而另外 3 条页面更适合portrait Currently, @page is only set once, in the app's top-level App.scss file.目前,@page 仅在应用的顶级@page文件中设置App.scss

App.scss应用程序.scss

@page {
  size: portrait;
}

@media print and (orientation: portrait) {
  .table-cols {
      max-width: 50%;
  }

  .my-selects { display: none; }
  .my-print-button { display: none; }
  .my-footer { display: none; }
  ...
}

How (if at all) can the @page { size: portrait } be switched to landscape certain routes, depending on the route? @page { size: portrait }如何(如果有的话)切换到横向某些路线,具体取决于路线? Maybe a landscape class and a portrait class could be made, that each set their own @page value, and then the classes would be used on the elements the routes are returning?也许可以制作landscape class 和portrait class ,每个都设置自己的@page值,然后将类用于路由返回的元素?

function setPageSize(cssPageSize) {
    const style = document.createElement('style');
    style.innerHTML = `@page {size: ${cssPageSize}}`;
    style.id = 'page-orientation';
    document.head.appendChild(style);
}

function PrintIcon({ teamId, orientation = 'portrait' }) {
    // Set orientation of page being printed
    useEffect(() => {
        setPageSize(orientation);
        return () => {
            const child = document.getElementById('page-orientation');
            child.parentNode.removeChild(child);
        };
    }, [orientation]);

    return (
        <div className='print-button' onClick={() => window.print()}>
            Click to Print
        </div>
    );
}

export default PrintIcon;

the useEffect calls the setPageSize() function which manually adds the @page to the head, and its cleanup function removes the @page ... useEffect调用setPageSize()函数,该函数手动将@page添加到头部,其清理函数将删除@page ...

<div className="printLayoutContainer">
     <style type="text/css" media="print">
         {" @page { size: portrait; } "}
       </style>
</div>

You can use internal CSS to print landscape or portrait.您可以使用内部 CSS 打印横向或纵向。

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

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