Our React app has ~10 different routes and we'd like for them all to be printable. 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.
Amongst the 10 routes, 7 of the pages look better with landscape
whereas the other 3 are better as portrait
. Currently, @page
is only set once, in the app's top-level App.scss
file.
App.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? 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?
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
...
<div className="printLayoutContainer">
<style type="text/css" media="print">
{" @page { size: portrait; } "}
</style>
</div>
You can use internal CSS to print landscape or portrait.
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.