1

I am trying to create a printable document using CSS in my angular project. For my print document that runs into multiple pages I need automatically to avoid printing the date and title in the header. At the same time I want to make sure that the document is printed with some margins. To achieve this I am using the approach suggested in this answer on SO. However I am not able to get the styling to apply.

My CSS Code looks like this

@media print {
  @page { 
    size: auto;
    margin: 0; 
  }
  body { 
    margin: 2cm !important;
  }
}

I have tried pasting this code in both the app.component.scss file as well as the styles.scss file. Both approaches don't seem to work. Any suggestions?

Anurag
  • 84
  • 3
  • 17

1 Answers1

0

You need to put the following css in your styles.css file

@media print {
  @page { 
    size: auto;
    margin: 0mm; // added mm
  }
  body { 
    margin: 2cm;
  }
}

And if you need component specific styling, you can add that to your component's css file as well:

@media print {
  section {
    color: orange;
  }
}

Here is a Stackblitz example. You can also try to print this page (https://angular-j4ab2g.stackblitz.io), and you will see that the date from the header is gone, and my custom section has orange text.

EDIT

I think the best option to remove the footer and header is to un-check the box in the print settings enter image description here

Then you do not need to add the 0mm margin to the @page selector and the 2cm margin on the body selector.

John
  • 10,165
  • 5
  • 55
  • 71
  • Thanks - I tried this -however the top margin seems to apply only on the first page and I am getting no margin on the second page. Please see screenshot at https://imgur.com/a/sOcJ870 – Anurag Aug 27 '19 at 07:27
  • I updated my answer, you should also probably use `page-break-*`-selectors as well. Have a look at this article by Rachel Andrew: https://www.smashingmagazine.com/2018/05/print-stylesheets-in-2018/ – John Aug 27 '19 at 09:13
  • Thanks @John - was aware of the option to hide headers and footers, unfortunately the requirement is for the margins to be hidden by default.... without user action. I also checked out the `page-break-*` properties. while these seem to be helpful in introducing a `break` after an element or class, in my case the break is introduced because of the page height and not because of an element or class, also what is not clear to me is how `page-break-*` can be used to enforce a `margin` after the break? – Anurag Aug 27 '19 at 14:08
  • I do not think it is possible to hide the footer and header (without using the 0mm margin option on @Page). So if you need margin on all other pages, my best guess is to use page-break rules on certain elements, and add a margin to those as well (for print). Maybe you can add a
    in your html, and add `page-break-before:always`.
    – John Aug 29 '19 at 11:30