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

Can*_*ice 5 css printing reactjs

我们的 React 应用程序有大约 10 个不同的路由,我们希望它们都可以打印。我们正在使用 css 打印媒体查询来清理打印样式,并且前端有一个调用window.print()单击的按钮。

在这 10 条路线中,有 7 页看起来更好,landscape而其他 3 条更好看portrait。目前,@page仅在应用程序的顶级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; }
  ...
}
Run Code Online (Sandbox Code Playgroud)

@page { size: portrait }根据路线,如何(如果有的话)可以切换到风景某些路线?也许可以创建一个landscape类和一个portrait类,每个类都设置自己的@page值,然后这些类将用于路由返回的元素?

Can*_*ice 3

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;
Run Code Online (Sandbox Code Playgroud)

调用手动将 添加到头部的函数,并且其清理函数useEffect删除...setPageSize()@page@page