21

I have an HTML file that uses one CSS file. Inside this file at the very bottom, I use this for styles that need to be applied ONLY to the printer version of the page:

@media print{
   ....print styles here...
}

When I call wkhtmltopdf --print-media-type input.html output.pdf, it renders the pdf with styles that are only in the @media print enclosure and ignores the rest of the styles - which DO NOT have @media type specified.

Is this normal, or what am I doing wrong here? Do I need to specify all styles for print inside @media print?

CarenRose
  • 1,266
  • 1
  • 12
  • 24
Hill
  • 419
  • 1
  • 7
  • 12

2 Answers2

19

wkhtmltopdf has an argument --print-media-type you can pass. Here is a C# code example using NReco (for illustrative purposes only), but the parameter should work in exactly the same way:

        var converter = new NReco.PdfGenerator.HtmlToPdfConverter();
        converter.CustomWkHtmlArgs = "--print-media-type";
        var pdfBytes = converter.GeneratePdf(html);
        return pdfBytes;

This works fine for me in C# using NReco to use print media css, and it takes into account any CSS that is not inside a @media block too, such as the font-size of a h3. Try changing the size of the text or something similar and see if the change is reflected.

Doc
  • 343
  • 3
  • 13
Peter Morris
  • 20,174
  • 9
  • 81
  • 146
  • 1
    You are using `NReco.PdfGenerator`; he is using [`wkhtmltopdf`](http://wkhtmltopdf.org/) (and probably not C#), so, you are not answering his question in any meaningful way :( – Doc Mar 28 '16 at 15:18
  • 4
    The converter.CustomWkHtmlArgs are the same. My answer is simply telling him the arguments to use for WkHtml, I will make this more clear in the answer. – Peter Morris Mar 30 '16 at 09:13
  • 2
    For Rotativa (which uses wkhtmltopdf), this is how to do it: `return new ViewAsPdf("Receipt", receiptModel) { FileName = "Receipt.pdf", CustomSwitches = "--print-media-type" };` – Rosdi Kasim Sep 09 '16 at 05:56
18

By default, any CSS rules you define without using media queries applies to all media types.

Therefore, wkhtmltopdf --print-media-type will explicitly use @media print AND any other generic rules.

If you want rules that wkhtmltopdf --print-media-type will not use, you must specifically define the media query as anything other than print, for example:

@media screen {
  /* will not be used */
  ...
}

@media print {
  /* will be used */
  ...
}

/* any rules outside specific media queries will also be used */
div.foo {
  ...
}

Alternatively, including the CSS file in your HTML with media="screen" attribute will not be used with wkhtmltopdf --print-media-type:

<!-- will not be used -->
<link rel='stylesheet' href='foo.css' type='text/css' media='screen'>
janechii
  • 1,055
  • 1
  • 11
  • 26