Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React, printer friendly printable area to print (Ctrl+P)

In my React Application (using semanticUI), I have several components rendered in a view, but when users want to print the page (e.g. by pressing Ctrl+P on the browser) I want only one part to be printable

for instance, if this is a screenshot of what user sees, the green area should be shown on print overview when the browser print is triggered.

So far I have in the SCSS file

@media print{    
  .no-print, .no-print *{ display: none !important; }
}

which adding to unwanted components makes them disappear but yet got blank space in print area and the green part is not filling the page, also if this green part is scrollable and should fit into several pages I just see one page (one A4 paper containing what I see on screen)

having

@media print {
  .print-content {
    display: block;
    width: 100%;
    height: 100%;
    page-break-after: always;
    overflow: visible;
  }
}

did not work yet get the same printable view

enter image description here this is the code for this screenshot

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
like image 309
Amir-Mousavi Avatar asked Jan 27 '23 19:01

Amir-Mousavi


1 Answers

Don't take this as the ultimate solution that covers all your use cases. But you can try this snippet idea to see if it solves your problem enough. I had a similar task in my recent project and this approach worked as needed.

@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;
  }
}

It will hide all the content on the page. Then add .section-to-print class to the area you want to print. Unless you have some overwriting css on it, it should work the way you want it to.

Important point to mention, if you have this CSS in global scope, it will hide all the content which doesn't have the .section-to-print and the print page will be blank. So, it might be wise to inject it into the stylesheet only when needed.

Let me know if this helps.

like image 165
Sam Uherek Avatar answered Jan 31 '23 08:01

Sam Uherek