What is the best solution to print a React components?

我是研究僧i 提交于 2020-12-13 03:28:51

问题


I am trying to print a ReactJS component when the user clicks the print button. I tried using React-to-print, but having style issue when printing from different browsers like firefox and edge.

Here is the code sandbox I created

https://codesandbox.io/s/jolly-carson-zvrzu?file=/src/App.js

In this code sandbox, I am using React-to-print and the printing component receives an array of objects which is basically converted into multiple number of pages.

You will see the issue on firefox, after clicking print, the first page is having extra margin at the top and the second page is empty in the print preview.

Can someone help me with the alternative to @react-to-print or any other solution?


回答1:


This is most likely caused by different default stylesheets between browsers.

Issues like this are typically solved with a CSS Reset: https://meyerweb.com/eric/tools/css/reset/

This gives a blank slate of page styles in all browser that are the same. You then put your own styles on top of that.




回答2:


Try the following alternative modules: https://www.npmjs.com/package/react-easy-print

https://github.com/captray/react-print

https://github.com/tacomanator/react-detect-print




回答3:


I was able to fix it after the CSS changes. The Jerm's solution was helpful from this thread.

Here is the new CSS, which also helped in removing unnecessary logic for calculating last page margin


const DataWrapper = styled(TableCell)`
  && {  
    padding-top: 25px;
    height: 100vh;
    display: flex;
  }
`;


const TopAndBottomWrapper = styled(TableCell)`
  && {
    page-break-after: always;
  }
`;

I have created a new code sandbox.

What I actually did is I added break before and after each component in addition to height:100vh, which helped in fitting one component per page. Also display: flex to keep the component at the top as height:100vh was moving the component in the middle.



来源:https://stackoverflow.com/questions/61598973/what-is-the-best-solution-to-print-a-react-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!