I have a javascript function to print a especific div called by a button.It works like i want but without styling.The problem is when i try to add the div style to the function,the print preview show a blank page in Chrome(Firefox works well).My function code is:
function printDiv(event) {
var DocumentContainer = document.getElementById("page-wrap");
var html = '<html><head>'+
'<link href="./css/style.css" rel="stylesheet" type="text/css"/>'+
'</head><body style="background:#ffffff;">'+
DocumentContainer.innerHTML+'</body></html>';
var WindowObject = window.open("", "PrintWindow",
"width=750,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes");
WindowObject.document.writeln(html);
WindowObject.document.close();
WindowObject.print();
WindowObject.close();
}
Anyone can help me?
Use the css media query
#media print
And apply styles you want in print
setTimeout(function() { objWin.print(); objWin.close(); }, 100);
Related
I’m printing selected parts of pages by putting them in an empty iframe. Everthing is fine except the CSS. Sometimes it’s there, sometimes not, so I guess the print function is loaded in moste cases before the css is complete. Unforntunately I’m obviously not able to solver the problem. The basic code:
var pStyles = new String ("<link href='/css/print.css' rel='stylesheet' type='text/css' id='cssprint' />");
var pWrapIn = new String ("<main><article><section>");
var pWrapOut = new String ("</section></article></main>");
function printFrame(fId) {
window.frames["printhelper"].document.body.innerHTML = pStyles + pWrapIn + document.getElementById(fId).innerHTML + pWrapOut;
console.log(window.frames["printhelper"].document.body.innerHTML);
window.frames["printhelper"].window.focus();
window.frames["printhelper"].window.print();
}
This works, but with the described CSS issue. To make sure the CSS is loaded, I ended up with the modified function, which is not working at all:
function printFrame(fId) {
window.frames["printhelper"].document.body.innerHTML = pStyles + pWrapIn + document.getElementById(fId).innerHTML + pWrapOut;
console.log(window.frames["printhelper"].document.body.innerHTML);
$(#cssprint).on('load', function() {
console.log ('CSS loaded');
window.frames["printhelper"].window.focus();
window.frames["printhelper"].window.print();
}, 0);
}
#cssprint seems to be loaded never, so console.log stays empty and no print is done. But what am I doing wrong? (The function printFrame is called by a simple onClick in the HTML markup.)
I would probably do something like this:
Add onload event handler to CSS link that calls a function that posts a message to the parent window (parent.postMessage(...)) or directly does so, then you do not need an extra script tag.
The outer window listens to the message of the iframe window and starts printing when receiving it.
You can also just skip the message posting if you do not need to synchronize anything with the parent window an just print directly in the onload event:
<link onload="window.print()" ...>
See MDN for more info on posting and receiving messages.
The complete working function (thanks to H. B.):
var pStyles = new String ("<link href='/css/print.css' rel='stylesheet' type='text/css' onload='window.focus(); window.print()' />");
var pWrapIn = new String ("<main><article><section>");
var pWrapOut = new String ("</section></article></main>");
function printFrame(fId) {
window.frames["printhelper"].document.body.innerHTML = pStyles + pWrapIn + document.getElementById(fId).innerHTML + pWrapOut;
}
I want to print a div element. I have a function that prints a div. But I want to print a div content with css.
function printDiv() {
var divContents = document.getElementById("mymodelid").innerHTML;
var a = window.open('', '', 'height=600, width=700');
a.document.write('<html>');
a.document.write(divContents);
a.document.write('</body></html>');
a.document.close();
a.print();
}
This code will help you to print a div. But if you want to print it with CSS, you must use #media rules in CSS.
function printDiv()
{
var divToPrint=document.getElementById('mymodelid');
var newWin=window.open('','Print-Window');
newWin.document.open();
newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');
newWin.document.close();
setTimeout(function(){newWin.close();},10);
}
Use #media print in CSS file like below:
#media print {
.mymodelid {background-color:#FF00FF;}
}
if it doesn't work, you should change your browser options and check the "Background graphics".
As sajadre said, I would also suggest to use createElement().
To change the font color, you could use the method fontColor() (be aware that it is deprecated):
function printDiv() {
const el = document.createElement('div');
el.innerHTML = 'Hello World';
var divContents = el.innerHTML.fontcolor("red");
var a = window.open('', '', 'height=600, width=700');
a.document.write('<html>');
a.document.write(divContents);
a.document.write('</body></html>');
a.document.close();
a.print();
}
I'm using Dreamweaver CS5.5 and Fancybox 1.3.4.
I've placed 4 images in a main div (2 in each row) and they fitted perfectly together (I don't want gaps as together the 4 images form one pic) till I applied fancybox to them.
Now there's a horizontal margin of about 20px between the 2 rows and I can't find where it's coming from. Any ideas? Do I need to paste the code here?
Be gentle – I'm primarily a print designer, so I'm learning dev as I go along. Thanks.
I have this in the head tag:
<script type="text/javascript" src="code.jquery.com/jquery-latest.min.js"></script>; <link href="jquery.fancybox-1.3.4/fancybox/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css"> <link href="jquery.fancybox-1.3.4/style.css" rel="stylesheet" type="text/css">
And this before the closing body tag:
<script type="text/javascript">
$(function($){
var addToAll = false;
var gallery = false;
var titlePosition = 'inside';
$(addToAll ? 'img' : 'img.fancybox').each(function(){
var $this = $(this);
var title = $this.attr('title');
var src = $this.attr('data-big') || $this.attr('src');
var a = $('').attr('href', src).attr('title', title);
$this.wrap(a);
});
if (gallery)
$('a.fancybox').attr('rel', 'fancyboxgallery');
$('a.fancybox').fancybox({
titlePosition: titlePosition
});
});
$.noConflict();
In the code you posted, you are not closing your javascript. This might be the problem. So after $.noConflict(); add
</script>
You could also override the CSS property by setting the margin and padding to the parent elements depending on the markup of the site.
Is there any way you could show us the HTML of that section?
I have a form with a print function. Inside the function I open a window, build the document, add the head with style sheets, add the form HTML and make the call to print the last part of the body. The problem is the initial print preview/print doesn't reflect the style. If I cancel the print and attempt to print manually, the style shows up.
I've tried quite a few ways of doing this with no luck. It seems like a timing issue. Any ideas?
Browser is Chrome. Below is the JS function. (This is injected with a faces context).
function printForm(windowTitle, path){
var printWindow = window.open();
var printDocument = printWindow.document;
var headHtml = "<link href='" + path + "/css/style.css' rel='stylesheet' type='text/css'/>";
printDocument.getElementsByTagName('head')[0].innerHTML = headHtml;
var printDiv = printDocument.createElement("DIV");
var formDiv = document.getElementById("formDiv");
printDiv.innerHTML = formDiv.innerHTML // Styling here is the issue
printDocument.body.appendChild(printDiv);
var scriptTag = printDocument.createElement("script");
var script = printDocument.createTextNode("print();");
scriptTag.appendChild(script);
printDocument.body.appendChild(scriptTag);
}
I think you need a setTimeout to delay printing for a second or two so the style can be applied. You'll need to tinker to find the right length.
Instead of trying to guessing with a timer, it might be more precise to use the load event on the <link ...> to know exactly when it has completed loading.
Below is a function I use which illustrates this technique. It uses an off-screen <iframe> to print a portion of a page. It's jQuery based, but the principles are the same in vanilla JS. Note the setting of the <link>'s onload function with an anonymous function which invokes print() on the <iframe>'s window object.
/*
* expects:
* <tag id="whatever">...goop...</tag>
* <input type="button" class="printit" data-target="whatever" value="Print">
*/
$(function() {
$( '.printit' ).click(function() {
var goop = $( '#' + this.dataset.target ).prop('outerHTML');
var ifr = $('<iframe>');
var bas = $('<base href="' + document.baseURI + '">');
var lnk = $('<link rel="stylesheet" href="/css/print.css">');
lnk.on('load', function() { /* CSS is ready! */
ifr[0].contentWindow.print();
});
ifr.css( { position: 'absolute', top: '-10000px' } )
.appendTo('body')
.contents().find('body').append(goop);
ifr.contents().find('head').append(bas).append(lnk);
return false;
});
});
This question is a little add for this Stackoverflow question Here I ended up with this code.
<script type="text/javascript">
//Simple wrapper to pass a jQuery object to your new window
function PrintElement(elem){
var data = '';
$(elem).each(function() {
data = data + $(this).html();
});
Popup(data);
}
//Creates a new window and populates it with your content
function Popup(data) {
//Create your new window
var w = window.open('', 'Print', 'height=400,width=600');
w.document.write('<html><head><title>Print</title>');
//Include your stylesheet (optional)
w.document.write('<link rel="stylesheet" href="add/css/layout.css" type="text/css" />');
w.document.write('<link rel="stylesheet" href="add/css/main.css" type="text/css" />');
w.document.write('</head><body>');
//Write your content
w.document.write(data);
w.document.write('</body></html>');
w.print();
w.close();
return true;
}
</script>
that when i tricker the
onclick="PrintElement('.PrintElement')">Print
I can print out some divs with the class="PrintElement" my question is now...
If i have some elements inside the DIV that i dont want to print out, how can i then add a class="NOprintelement" so the code know that the elements with this class, need to be excluded in the print event ?
Without knowing more details, you should probably try to hide DOM elements using css media queries. For example, if you have a div with class = 'hideWhenPrinting', your CSS could include:
#media print {
.hideWhenPrinting { display: none }
}
See this related question:
How do I hide an element when printing a web page?