Google Chrome (v.51) not applying print media css - html

I know there's a lot of questions about this, but I tried everything and nothing seems to work. I followed these links:
Splitting HTML page so Printer splits it into separate pages
Chrome: Print preview differs from simulate CSS media print
Print media queries being ignored in Chrome?
Google Chrome Printing Page Breaks
and much more.
I tried pretty much every single suggestion in all of them.
Here's what I've got so far :
html
<link href="path/styles/print.css" rel="stylesheet" media="print">
<div class="page-break">
//some stuff
</div>
css
#media all {
.page-break { display: none; }
}
#media print {
.page-break { display: block; page-break-before: always;}
}
In IE and FF, I can't see preview of the page I'll print, but when I do print, it works just fine. In chrome, I can see preview, but it's never right... next I'm trying to save it as pdf, but it still doesn't apply print css.
*Saving as pdf as nothing to do with trying to make it works... it's just to save paper
Now, before you post an answer, please be aware of the following :
I tried this:
!important; hack
Deleting css page and put css directly in html page
Delete media all
Delete media all and changing display block to none
Tried page-break-inside: avoid;
*{transition:none !important;}
.page-break { ... transition: none !important;}
put it in main style sheet
float: none !important;
position: relative; position: static;
display: block; display: inline;
box-sizing: content-box;
-webkit-region-break-inside: avoid;
I didn't try with other version of Chrome. I tried on v.50, after multiple attempt fail, I updated to v.51. Some said it works on v.38 or something like that... I won't downgrade to that version.
Edit: I forgot to mention that my html code is in a jsp page. So the <div class="page-break"> is in a for-loop. Every loop has to be on individual page.
Edit 2: I created a jsfiddle. I pasted the source code I have and it works perfectly. So I removed the css stylesheet that are links in my page. But even by doing that, it won't work. So if it's override somewhere, it's not there.
The page is a JSP page, does it have anything to do about it? If not I'm clueless, because in the same project, on the page I want to print, I added a button that redirect to a page.html and I created 3 divs with the same class name and it works just fine.

So! I'm here to answer my own question, in case someone just can't make it work just like me.
I tried to give a new approach to my problem, since I can't print single div per page and I don't know why, I must find another way. But it's not that I didn't know how it works... I created a JSFiddle and it worked. In my own project, I created a html page and it worked. But since I was in JSP, maybe it was messing with my code somewhere.. I have no idea.
So here's what I've done.
function getStuffToPrint(data){
var html = "", index, len;
for (index = 0, len = data.length; index < len; ++index) {
html += "<div class=\"custom-page-break\">" + data[index].innerHTML + "</div>";
}
var mywindow = window.open();
mywindow.document.write('<html><head>');
mywindow.document.write('<link href="my/path/to/styles/print.css" rel="stylesheet" type="text/css"/>');
mywindow.document.write('</head><body >');
mywindow.document.write(html);
mywindow.document.write('</body></html>');
mywindow.document.close();
mywindow.focus();
mywindow.print();
mywindow.close();
return true;
}
In my case, data was an objectHTMLCollection : document.getElementsByClassName("custom-page-break")
It's a bit ratchet, I had to write the div with the class name again...
Here's my css, it may work without display: block and page-break-inside, I didn't even try.
#media print {
.custom-page-break {
display: block !important;
page-break-before: always !important;
page-break-inside: avoid !important;
}
}
Hope it'll save hours for some people.

Have you tried to put the print.css in your main style css document ? I had a similar case and it solved my problem.
You dont have to make a pdf file every time to see if the #media print worked, you can see the page emulated like print in your Google developpement tool on Chrome:
To see that option, do : F12 -> show console -> rendering ( it's a tab of the console ) -> check "Emulate media Print".

Related

break-inside: avoid doesn't work for basic example

I'm using Chrome v99 and a pretty basic usage of break-inside: avoid - but it does nothing.
Moderator: This is not a duplicate of this post and the 1 answer there isn't helpful.
My objective is to disallow the contents of all these divs from splitting at page breaks:
<div class="opt">
Here is my inline css:
<style media="screen" type="text/css">
#media print {
div.opt, table {
break-inside: avoid !important;
}
}
</style>
The full html is a bit lengthy but you can view the entirety here.
Simply press CTRL+P and observe that it page-breaks in the middle of divs with a class of opt - but it shouldn't because I'm using break-inside: avoid.
The example I linked to is very short and contrived, but my real scenario has many more sections and is dynamic, pulling from a database. So there's no way to know where the page is going to break relative to the divs. I just want the contents within those divs with that class to always stay together on the same page and never split across a page break. No div contents ever exceed a page, they are even shorter than my example.
Help, what am I doing wrong?
You have media=screen in the style tag...
Your print styles will only load when you're using a screen and not a printer
<style media="print" type="text/css">
div.opt, table {
break-inside: avoid !important;
}
</style>
When you fix it though it still seems to wrap onto multiple pages uglier but at least now you can play around with what print styles work

Page break in DataList (asp.net) in Google Chrome

I have created a Page with the Datalist control in it, which generates "ID cards".
You can see the working example here.
The problem is that I want to break the page after every 4th row of Datalist.
So to execute this, I am using this jQuery code:
<script type="text/javascript">
$(document).ready(function () {
$("#GridView1 tr:nth-child(4n+0)").addClass("breakpage");
})
</script>
And the CSS class:
<style type="text/css">
.breakpage {
page-break-after: always;
}
</style>
So if you open the page and check with the inspect element, you can see that the jQuery is working, and it does add the class on every 4th row.
But still, when I try to take a print, the page break is not working in Google Chrome (working fine in firefox).
Could someone please explain what is wrong with the code?
Thank you.
How to achieve page break in HTML table for Google Chrome? can you see if this page helps? It might have something to do with a tr being display: table-row instead of display: block
Apparently Chrome only applies the page break to block level elements.
Edit: I've just tested that setting the following fixes it:
#GridView1 > tbody > tr {
display: block;
}
If I shrunk the margins of the pages the pagebreak didn't fall on the next page, but playing around with the sizes of your cards would fix this too so you don't have a fully empty page
Try it in CSS with this:
#GridView1 tr:nth-of-type(4n) {
page-break-after:always;
}

CSS styling lost when printing

I have a page which contains charts etc for statistics which must be printable. I want to just use the standard browser print functionality in order to enable printing. I also have css which changes the button colours for selected buttons to make it clear which charts are being viewed. However, my issue is that when i attempt to print the page, this colouring is lost and reset to its default presentation.
I am aware of the capabilities of doing this in Chrome by using webkit-print-color-adjust settings in the CSS, however, the vast majority of users in my business use IE or Edge (as they are microsoft defaults) and therefore i need a solution which would work in them.
I have attempted using !important and #media print but to no effect as yet, unless i am using them wrong.
Here is the css currently:
#media print{
.btn-primary-chart:active,
.btn-primary-chart.active {
color: #ffffff;
background-color: green !important;
border-color: #285e8e;
}
}
Any help would be greatly appreciated :)
From the SO answer here, the reason why your CSS does not work is because of the default settings in the browser print settings.
With Chrome and Safari, you may want to add in
-webkit-print-color-adjust: exact;
to force print the background color.
There isn't any foolproof method to print backgrounds in Internet Explorer and Microsoft Edge yet. However, there's a few methods I've tried before and may work under some circumstances:
Method 1 (using sprite):
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#fffad‌​a', endColorstr='#fffada')";
Method 2:
CSS
.background:before {
content: '';
display: block;
position: absolute;
top: 0;
right: 0;
left: 0;
z-index: -1;
border-bottom: 1000px solid #eee;
}
HTML
<body class="background">
But if you want to print it yourself, you can enable 'Print Background Color':
To resolve this behavior, turn on the Print background colors and images option in Internet Explorer. To do this, follow these steps:
On the Tools menu, click Internet Options, and then click the Advanced tab.
In the Settings box, under Printing, click to select the Print background colors and images check box, and then click OK.
Also, a few similar StackOverFlow Posts
CSS #media print issues with background-color;
How can I force browsers to print background images in CSS?
Please try adding "!important" on the style (but not in the #media print).
I just met the problem that font color was missing in print view, and the final solution is replace
color: red !;
with
color: red !important;
in the style.
It seems that some styles will be ignored if "!important" is not used.
I found one solution that will even work in the EDGE browser. Here is the basic HTML:
<div style="position: relative;width:100%">
<div style="border-color:green;border-style:solid;
border-width:15px;width:70%;"></div>
<div style="position: absolute; top: 50%;
transform:translateY(-50%);left: 0px;">
Hello, world.
</div>
</div>
You can adjust the width or the parent and the child div's as necessary.
Worth mentioning here, since I had a similar problem, is that EDGE will render SVG properly while ignoring the HTML background-color.
So instead of using:
<div style="background-color:red; width:20px height:20px">...</div>
You can use something like this:
<svg style="width:20px;height:20px">
<rect width="100%" height="100%" style="fill:red">
</svg>
Actually it is possible to programmatically change the background printing setting for IE:
void CMeetingScheduleAssistantApp::SetPrintBackgroundSetting(CSettingsStore& regSettings, CString strPrintBackground, BOOL& rbResetDefault, BOOL& rbReset)
{
rbResetDefault = FALSE;
rbReset = FALSE;
// Attempt to read the registry key value
if(regSettings.Read(_T("Print_Background"), strPrintBackground))
{
// Update registry key value if we need to
if (strPrintBackground != _T("yes"))
{
regSettings.Write(_T("Print_Background"), _T("yes"));
// Remember, reset it back to original value afterwards
rbReset = true;
}
}
else
{
// User accepted default behavior, so create registry key value
regSettings.Write(_T("Print_Background"), _T("yes"));
// Remember, reset it back to default value afterwards
rbResetDefault = true;
}
}
void CAvailableBrothersReportPreview::OnButtonPrintPreview()
{
CSettingsStore regSettings(false, false);
if (regSettings.Open(_T("SOFTWARE\\MICROSOFT\\Internet Explorer\\Main")))
{
CString strPrintBackground;
BOOL bResetValue = FALSE, bResetResetDefault = FALSE;
// Try to revise the Print_Background setting
CMeetingScheduleAssistantApp::SetPrintBackgroundSetting(regSettings, strPrintBackground,
bResetResetDefault, bResetValue);
// Now show the print preview dialogue
if (m_pHtmlView != nullptr)
m_pHtmlView->DoPrintPreview();
// Reset the Print_Background setting if required
if (bResetValue)
regSettings.Write(_T("Print_Background"), strPrintBackground);
else if (bResetResetDefault)
regSettings.Write(_T("Print_Background"), _T("no"));
}
}

page-break-inside doesn't work with hidden table

I some CSS similar to this:
table#id {
display : none;
}
#media print {
table#id {
display : block;
}
.no-page-break {
page-break-inside: avoid !important;
}
}
Each td contains a div.no-page-break. The problem I'm having is that there are page breaks inside the tds unless the table is made visible before opening the print dialogue. If I emulate print media in the dev tools and print, it works fine. If I display the table before window.print() and hide it afterwards it also works, although I'd like to avoid this hack. Anyone have any ideas about why this is happening?

Wkhtmltopdf Characters in single line partially cut between pages

I am working in a project using ruby on rails(3.1). My requirement is to produce pdf from the html content. So I use pdfkit gem.
In some pages, characters in single line partially cut between pages. When I convert html convert to pdf using pdfkit gem
version of wkhtmltopdf: wkhtmltopdf -- 0.11.0 rc1
operating system: Linux CentOS 5.5
In the image below showing character partially cut between pages.
Please suggest a solution.
Example 1
Example 2
I did have this problem with a table:
Then I added this to my CSS:
table, img, blockquote {page-break-inside: avoid;}
This fixed the problem:
I just ran across this and found something that resolved the issue for me. In my particular case, there were divs with display: inline-block; margin-bottom: -20px;. Once I changed them to block and reset the margin-bottom, the line splitting disappeared. YMMV.
According to some documentation I found (see Page Breaking), this is a known issue and suggests using CSS page breaks to insert page breaks (assuming you are using patched version of QT):
The current page breaking algorithm of WebKit leaves much to be
desired. Basically webkit will render everything into one long page,
and then cut it up into pages. This means that if you have two columns
of text where one is vertically shifted by half a line. Then webkit
will cut a line into to pieces display the top half on one page. And
the bottom half on another page. It will also break image in two and
so on. If you are using the patched version of QT you can use the CSS
page-break-inside property to remedy this somewhat. There is no easy
solution to this problem, until this is solved try organising your
HTML documents such that it contains many lines on which pages can be
cut cleanly.
See also: http://code.google.com/p/wkhtmltopdf/issues/detail?id=9,
http://code.google.com/p/wkhtmltopdf/issues/detail?id=33 and
http://code.google.com/p/wkhtmltopdf/issues/detail?id=57.
In my case, the issue was resolved by commenting out the following css:
html, body {
overflow-x: hidden;
}
In general, check if any tags have overflow set as hidden and remove it or set it to visible.
Btw, I am using wkhtmltopdf version 0.12.2.1 on Windows 8.
https://github.com/ArthurHub/HTML-Renderer/issues/38
**var head = "<head><style type=\"text/css\"> td, h1, h2, h3, p, b, div, i, span, label, ul, li, tr, table { page-break-inside: avoid; } </style></head>";**
PdfDocument pdf = PdfGenerator.GeneratePdf("html>" + head + "<body>" + m42Notes + "</body></html>", configurationOptions);
I scoured the internet for a couple of weeks, trying to overcome this issue. None of the solutions I found worked for me, but something else did.
I had a two column layout where the text was getting cut off mid-text. In the broken state, my basic structure looked like this:
#media print {
* {
page-break-inside: avoid;
page-break-after: avoid;
page-break-before: avoid;
}
}
.col-9{
display: inline-block;
width: 70%;
}
.col-9{
display: inline-block;
width: 25%;
}
<div class="col-9">
[a lot of text here, that would spill over multiple pages]
</div>
<div class="col-3">
[a short sidebar here]
</div>
I fixed it by changing it to:
#media print {
* {
page-break-inside: avoid;
page-break-after: avoid;
page-break-before: avoid;
}
}
.col-9{
display: block;
float: left;
width: 70%;
}
.col-9{
display: block;
float: left;
width: 25%;
}
.clear{
clear: both;
}
<div class="col-9">
[a lot of text here, that no longer split mid-line.]
</div>
<div class="col-3">
[a short sidebar here]
</div>
<div class="clear"></div>
For some reason, the tool could not handle the display: inline-block setup. It works with floats. I'm running version 0.12.4.
This is old but hopefully will help someone - I was having the issues too, tried everything - even resorting back to old versions mentioned (12.1) but to no avail. I kept tweaking css to play around, trying to throw in page-break avoids everywhere, not having much progress. Then I tweaked css that was on the root div of my html, and it fixed it. I made so many tweaks trying to get it to work so I can't be 100% sure, but I believe the issue was it set to 'display:table' with margin: 0 auto and a specific width on the main outer div. It started working and not cutting off either images or tables mid-row once I removed that. Then the page-break-inside: avoid was working after that as expected.
I believe ultimately the code is trying to guess as best as it can exactly how many pixels high each page is, and where exactly (down to the pixel) is your content. We have to make it easy for the library to detect this by removing as much odd css in there as possible, so it's as simple as possible to calculate down to the pixel where the content lies. That's my guess.
I solved problem adding margin-top and margin-bottom, like this:
$this->get('knp_snappy.pdf')->generateFromHtml($html, $pdfFilepath, [
'default-header' => false,
'header-line' => false,
'footer-line' => false,
'disable-javascript' => true,
'margin-top' => '3mm',
'margin-bottom' => '3mm',
'margin-right' => '5mm',
'margin-left' => '5mm',
'orientation' => 'Landscape',
], true);
The cut text problem is a known webkit problem and it seems developers found a solution inside wkhtmltopdf. Updating to 0.12.1 will fix the cut-text problem (if you don't want to waste time with compilations, you can just take the binary file from here: https://github.com/h4cc/wkhtmltopdf-amd64 ).
Have been putting up with this for months and finally found a fix for my situation. I'm using the github css stylesheet in the html file I'm converting, and code blocks that span multiple pages get the text cut if. Nothing is missing, it's just cut in half.
Bottom of a page:
Start of next page:
So in the github stylesheet overflow is set to auto for <pre> tags.
.markdown-body .highlight pre,
.markdown-body pre {
padding: 16px;
overflow: auto;
...
Switching the overflow property to hidden solved it for me!
.markdown-body .highlight pre,
.markdown-body pre {
padding: 16px;
overflow: hidden;
Think I tried all the other answers on this page, but this is solved for me. Hope it helps someone else out :)
I was able to find a workaround to this issue by installing wkhtmltox_0.12.6-1.bionic_amd64.deb (for Ubuntu) from https://github.com/wkhtmltopdf/packaging/releases/0.12.6-1
After updating this wkhtmltox package, the tables and text will not cut off at the end of the page anymore. This fix introduced a different issue for me, now the generated pdf has no styling. For example font-family, font-size or even text alignment are all gone, and are using some default setting.