I’ve got a piece of JavaScript code that prints the content located inside a specific div( #printthis ). It works great on PC; however, when I try to use it on an ipad, the page is blank except for the “footer” that contains the page name, date, time, and how many pages. The footer is set via the print driver/iPad.
Any way to modify this code to work on both PC and ipad? I haven’t tested on any other devices yet. These are just the devices I use regularly.
<script type="text/javascript">
function printdata(title) {
var thistitle = title;
var contents = $("#printthis").html();
var frame1 = $('<iframe />');
frame1[0].name = "frame1";
frame1.css({ "position": "absolute", "top": "-1000000px" });
$("body").append(frame1);
var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
frameDoc.document.open();
//Create a new HTML document.
frameDoc.document.write('<html><head><title><?php if(isset($title)) { echo strtoupper($title) .' '; } ?>LIST PRICE</title>');
frameDoc.document.write('</head><body>');
//Append the external CSS file.
frameDoc.document.write('<link href="style.css" rel="stylesheet" type="text/css" />');
//Append the DIV contents.
frameDoc.document.write(contents);
frameDoc.document.write('</body></html>');
frameDoc.document.close();
setTimeout(function () {
window.frames["frame1"].focus();
window.frames["frame1"].print();
frame1.remove();
}, 500);
}
</script>
I call this function via <a onclick="printdata()" href="javascript:void(0)">Print</a>
Related
I use this code for modal windows with html content - printing
I am having issues with click and responding to events, I have had no response when i click, and sometimes i have to click frequently and refreshing oage then i might get respond.
<span class="print_m" id="closeme"><i class="fa fa-print" aria-hidden="true"></i></span>
jQuery("#closeme").click(function () {
var contents = jQuery("#printContent").html();
var frame1 = jQuery('<iframe />');
frame1[0].name = "frame1";
frame1.css({ "position": "absolute", "top": "-1000000px" });
jQuery("body").append(frame1);
var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
frameDoc.document.open();
//Create a new HTML document.
frameDoc.document.write('<html><head><title>document class2</title>');
frameDoc.document.write('</head><body>');
//Append the external CSS file.
frameDoc.document.write('<link href="../wp-content/themes/MCC/style.css" rel="stylesheet" type="text/css" />');
//Append the DIV contents.
frameDoc.document.write(contents);
frameDoc.document.write('</body></html>');
frameDoc.document.close();
setTimeout(function () {
window.frames["frame1"].focus();
window.frames["frame1"].print();
frame1.remove();
}, 50);
});
I have a string which comes from api response. Now i want to integrate this script and style tag in my application and execute script.
const styleScriptText = '<style type="text/css">#checkoutmodal .checkoutmodal-box{background:#FFF !important}</style><script src="https://someurl/lib/jquery.min.js" type="text/javascript"></script><script type="text/javascript">$(document).ready(function() { console.log("test")});</script>'
I tried to load it using iframe and i could achieve expected result
const iframe = document.createElement('iframe');
const html = `<body>${styleScriptText}</body>`;
iframe.srcdoc = html;
iframe.style.width = "47%";
iframe.style.left = "25%";
iframe.style.height = "100vh";
iframe.style.position = "relative";
document.getElementById("parentId").appendChild(iframe);
But i don't want to use iframe as it has future constraints i have to redirect to bank page and when it comes back whole application is iframed which i don't want
Next i tried it using document.write as below
const html = `<html>
<head>
</head>
<body>
${styleScriptText}
</body>
</html>`;
document.open("text/html", "replace");
document.write(html);
document.close();
But problem with above approach is i am getting below error
A parser-blocking, cross site (i.e. different eTLD+1) script, https:externalscript.js, is invoked via document.write
If i take any other approch $(document).ready function in script doesnot execute.
Tried almost everything but not able to figure out how can i load and run script coming from api response.
Goal here is i need to take a script coming as string and load it in html and execute every script files
this should work, use it at your own risk:
const styleScriptText =
'<style type="text/css">body {background: #000}</style><script type="text/javascript">alert("OK")</' + 'script' + '>';
const insertStyleScriptText = () => {
const div = document.createElement('div');
div.innerHTML = styleScriptText;
div.childNodes.forEach(child => {
document.head.appendChild(child.cloneNode(true));
if (child.tagName === 'SCRIPT')
eval(child.textContent);
});
};
<button onclick="insertStyleScriptText()">insert StyleScriptText</button>
this is my jquery code:
jQuery('.print_btn').hide();
var contents = document.getElementById("print_page").innerHTML;
var frame1 = document.createElement('iframe');
frame1.name = "frame1";
frame1.style.position = "absolute";
frame1.style.top = "-1000000px";
document.body.appendChild(frame1);
var frameDoc = (frame1.contentWindow) ? frame1.contentWindow : (frame1.contentDocument.document) ? frame1.contentDocument.document : frame1.contentDocument;
frameDoc.document.open();
frameDoc.document.write('<html><head><title></title>');
frameDoc.document.write('</head><body>');
frameDoc.document.write(contents);
frameDoc.document.write('</body></html>');
frameDoc.document.close();
setTimeout(function () {
frameDoc.focus();
frameDoc.print();
document.body.removeChild(frame1);
}, 500);
jQuery('.print_btn').show();
return false;
I search on google but i did not find any solution so i am posting this question.
I have a pop which is having image and a print button , i want to print the image on click on print button.
This working fine on web browser means on desktop, But it is printing whole page and pop-up image , and on i pad it is printing nothing .
Why this is happening i don't know please help me out.
Unfortunately .print() isn't supported on Android devices. You could however use Googles cloud print API: https://developers.google.com/cloud-print/docs/gadget
I want to open a print dialog for a file(docx,pdf,...) via a SharePoint Workflow. There I call a URL with GET and pass the URL of the file after the ? like this:
http://www.sharepoint_intranet.com/print.html?link-to-file.pdf
EDIT: I also tried:
<script type="text/javascript">
//Get the URL of the file
var urlOfFile = window.location.search.replace("?", "");
document.write("<iframe id=" + "printDocument" + " src=" + "'" + urlOfFile + "'" + " width=" + "600" + " height=" + "400" + "></iframe>");
window.frames['printDocument'].focus();
window.frames['printDocument'].print();
</script>
The Print Dialog is opening and in the print options there is the Point "Only selected Frame" selected but when I press the print button nothing will happen.
Thanks for any help!
you can put in the body of the html
<body onLoad="window.print();">
so the page is opened already prints the document.
The issue is that the new url doesn't start loading until the current script block has finished executing. Therefore when you call w.print(), the new window is currently blank.
Try:
<script type="text/javascript">
//Get the URL of the file
var urlOfFile = window.location.search.replace("?", "");
//print
var w = window.open(urlOfFile);
w.onload = function() {
w.print();
}
</script>
EDIT: I didn't read the question properly! The above technique only works for html. The way to solve this is to use an iframe and if we are using an iframe we might as well dispense with the popups entirely. The following code creates an iframe with a source set to the desired document, attaches the iframe to the page (but keeps it invisible), prints the contents of the iframe and finally removes the iframe once we've finished with it. Only tested in Chrome but I'm fairly confident that it'll work in other browsers.
<script type="text/javascript">
//Get the URL of the file
var urlOfFile = window.location.search.replace("?", "");
//print
var iframe = document.createElement('iframe');
iframe.src = urlOfFile;
iframe.style.display = "none";
var iFrameLoaded = function() {
iframe.contentWindow.print();
iframe.parentNode.removeChild(iframe);
};
if (iframe.attachEvent) iframe.attachEvent('onload', iFrameLoaded); // for IE
else if(iframe.addEventListener) iframe.addEventListener('load', iFrameLoaded, false); // for most other browsers
else iframe.onload = iFrameLoaded; // just in case there's a browser not covered by the first two
window.onload = function() {
document.body.appendChild(iframe);
};
</script>
where we can give the path of the file like("abc.doc"/"abc.xls")
var urlOfFile = window.location.search.replace("?", "");
I have recently made the switch from HTML to XHTML... don't get me started on the "why" - let's just say it wasn't an option. Anyhoo...
This function worked fine in IE and FF when I was HTML, but now with XHTML I get the following error in FF:
heightElement is undefined
now here is the statement where I define heightElement
function revBars(isEFBOutput, isIXPPreview) {
if (!isIXPPreview) isIXPPreview = false;
var heightElement =
$('<div id="resizeDetectingElement" style="position:absolute; left:-9999999px height:1em;"> </div>')
.prependTo('body')
.get(0);
heightElement.currentHeight = heightElement.offsetHeight; // FireBug says the error is here.
insert();
window.onresize = refresh;
setInterval(
function() {
if (heightElement.currentHeight != heightElement.offsetHeight) {
heightElement.currentHeight = heightElement.offsetHeight; refresh();
}
}, 500);
function insert() {
var px = "px";
var color = (document.styleSheets[0].href.match("ftidStyleDay")) ? "black" : "white";
$revMarks = $('.RevMark').removeClass('RevMark').addClass('UnMarked');
if (!$revMarks.length) $revMarks = $('.UnMarked');
$revMarks.each(function() {
$('<div class="RevBar" />').css({
'background-color': color,
'width': '2px', 'position': 'absolute',
'left': (isEFBOutput && !isIXPPreview ? '.25em' : '-.75em'),
'height': this.offsetHeight,
'top': offset(this) + px
}).prependTo('body');
});
}
function refresh() { $('.RevBar').remove(); insert(); }
function offset(obj) {
var top = 0;
if (obj.offsetParent) {
do {
top += obj.offsetTop;
} while (obj = obj.offsetParent);
}
if (document.all && (!isEFBOutput || (isEFBOutput && isIXPPreview))) top -= 15;
return top;
}
}
any ideas why this is throwing an error in XHTML in FF? It still works in IE.
EDIT: Again, this code worked perfectly in FF and IE until I switched to XHTML. Firefox still creates a DOM for XHTML, right?
I rewrote some of your example, as you have errors and is incomplete with function calls that are not in the example:
$(document).ready( function(){
function revBars(isEFBOutput, isIXPPreview){
var test = "<div id=\"someElement\">whatever</div>";
$('body').prepend(test).get(0);
var heightElement = $('#someElement');
console.log( heightElement);
}
revBars();
});
At this point the heigthElement exists and the div is added to DOM.
Please provide correct problems in order to get them solved.
UPDATES
//var heightElement = $('<div id="resizeDetectingElement">whatever</div>').prependTo('body').get(0);
// this statement doesn't work
var heightElement = $('body').prepend('<div id="resizeDetectingElement">whatever</div>');
// this does
console.log(heightElement);
This is basically the same as first example.
The request that you made is to add a div before the element body and then get the first element of the body. The prependTo already returns the matched items so the get was irelevant. And you are attaching an element before the body so is normal that your variable will be empty.
Try my code and remove the downvote as not to many people had this kind of patience with your supercode.
UPDATE 2
This is an usage example for prepend() and prependTo().
<html>
<head>
<script type="text/javascript" src="../lib/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready( function(){
$("#test_A").prepend('<div id=\'test_B\'>B</div>');
$("#test_C").prependTo( $('#test_A'));
var x = $('<div id="resizeDetectingElement">D</div>').prependTo('body').get(0);
console.log( x ); // returns the div
$(x).append('some text'); //works
});
</script>
</head>
<body>
<div id='test_A'>A</div>
<div id='test_C'>C</div>
</body>
</html>
I hope this will help to make your code work. USE $(heightElement) not just heightElement which is the div not the jQuery object.