How can i print a pdf in google chrome? - javascript

I have a pdf associated with a button . When i click the button i want to get the pdf printed. This is how my button is coded :
<input type="submit" class="btn-red" value="Print"
name="Submit" id="printbtn"
onclick="printPDF('http://www.irs.gov/pub/irs-pdf/fw4.pdf')" />
Now my print functionality works like this :
function printPDF(pdfUrl)
{
if ((navigator.appName == 'Microsoft Internet Explorer') )
window.print(pdfUrl,"_self");
else
{
var w = window.open(pdfUrl,"_self");
w.print();
w.close();
}
}
The problem is , it's working fine in IE and Fire fox , but does not work in chrome. In ie and Firefox, it opens up the xps printer option, but in chrome , it just opens up a new print window, with the print preview of the div and not the pdf . But i want the xps option to be opened up here.
EDIT : In chrome when i try to print , only the html element comes as preview and not the pdf. I am using chrome version : 20.0.1132.57
How can i get around this peculiarity ? kindly help .

This worked for me and didn't require a host HTML file. The key was to wait for onload:
For a link like this:
<a class="print-pdf-link" href="/your/pdf.pdf">Print PDF</a>
I used javascript:
$('a.print-pdf-link').click(function () {
var w = window.open($(this).attr('href'));
w.onload = function () {
w.print();
};
return false;
});

I had to do the same thing and I used a different approach, one that for me worked in both Chrome and Firefox.
My solution involved a print.html helper file, that received the PDF file's url as a GET type parameter, then loaded the pdf inside an iframe. Then it kept checking to see if the pdf had completely loaded (binding the check to the onload event did not work) and on completion it triggered the print method.
Here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
<title>Print Page</title>
<meta name="title" content="Print" />
<script>
(function (window, document, undefined) {
var printy = {
urlGET: function (param) {
var params = document.URL.split('?');
if(params.length > 1) {
params = params[1].split('&');
for (var i = 0, len = params.length; i < len; i++) {
if (params[i].split('=')[0] === param) {
return params[i].split('=')[1];
}
}
}
return null;
},
init: function () {
var self = this;
window.onload = function () {
var src = self.urlGET('path');
//creating an iframe element
var ifr = document.createElement('iframe');
document.body.appendChild(ifr);
// making the iframe fill the viewport
ifr.width = '100%';
ifr.height = window.innerHeight;
// continuously checking to see if the pdf file has been loaded
self.interval = setInterval(function () {
if (ifr.contentDocument.readyState === 'complete') {
clearInterval(self.interval);
// doing the actual printing
ifr.contentWindow.print();
}
}, 100);
ifr.src = src;
}
}
}
printy.init();
})(window, document, undefined);
</script>
</head>
<body>
</body>
</html>
This solution is not tested on IE though. We use Macs at work so it was not an option.
In order to do the printing, I use it by calling an URL like this: http://example.com/print.html?path=docs/myfile.pdf

Related

A simple example using html, javascript and jQuery

I'm starting with javascript, websockets and jQuery developing a simple example. In the html page I only have a button, that, when pressed, has to send its state (ON/OFF for instance). In index html, I have the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"></meta>
<title>First App</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/APP.js"></script>
</head>
<body>
<div id='hello_message'>
Connecting...
</div>
<button id='state'>Turn on</button>
<div id='off'>OFF</div>
<div id='on'>ON</div>
</body>
</html>
My intention is to open a websocket between the client and the server when the page is loaded, and keep it open for any information to be sent between both of them. To this end, I have the following file containing the js code (APP.js):
window.onload = APPStart;
// Page onload event handler
function APPStart() {
state = false;
if ("WebSocket" in window)
{
var ws = new WebSocket("ws://10.30.0.142:8020");
ws.onopen = function()
{
alert ("Connected");
$('#hello_message').text("Connected");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
};
ws.onclose = function()
{
alert("Connection is closed...");
};
window.onbeforeunload = function(event) {
socket.close();
};
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}}
Now, every time someone clicks on button, I would like to execute the following code:
// program checks if led_state button was clicked
$('#state').click(function() {
alert ("click");
// changes local led state
if (led_state == true){
$('#on').hide();
$('#off').show();
state = false;
ws.send("ON");
}
else{
$('#off').hide();
$('#on').show();
state = true;
ws.send("OFF");
}
});
I've tried to put this part of the code inside the function APPStart, but it doesn't work. I also suspect that jQuery is not working either since messages are not updated. Any suggestion to make it work?
Thanks for the comments. The code works, the problem was in the cache of the browser. Once I noticed it, I cleaned the cache and everything started to work. Silly me.

How to modify so that links with specific class value trigger popup function with JavaScript/HTML?

I need to "modify the popups.js and the popups.html files so that only links with a specific class value trigger the createPopup() function." How do I got about doing this? I'm a complete beginner learning javascipt and I have no idea what it's asking for and how to do this.
/*Modify popups.js and .html so that only links with a specific class value
trigger the createPopup() function*/
function createPopup(e) {
'use strict';
// Get the event object:
if (typeof e == 'undefined') var e = window.event;
// Get the event target:
var target = e.target || e.srcElement;
// Create the window:
var popup = window.open(target.href, 'PopUp', 'height=100,width=100,top=100,left=100,location=no,resizable=yes,scrollbars=yes');
// Give the window focus if it's open:
if ( (popup !== null) && !popup.closed) {
popup.focus();
return false; // Prevent the default behavior.
} else { // Allow the default behavior.
return true;
}
} // End of createPopup() function.
// Establish functionality on window load:
window.onload = function() {
'use strict';
// Add the click handler to each link:
for (var i = 0, count = document.links.length; i < count; i++) {
document.links[i].onclick = createPopup;
} // End of for loop.
}; // End of onload function.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Popup Windows</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<!-- Script 9.4 - popups.html -->
<p>B Link (Will open in a new window.)</p>
<p>A Link (Will open in a new window.)</p>
<script src="js/popups.js"></script>
</body>
</html>
document.links[i].onclick = createPopup;
That line should become something like:
var link = document.links[i]
if (link.classList.contains('link'))
document.links[i].onclick = createPopup;
Of course you need to update your HTML:
<a href="popupB.html" id="link" target="PopUp">
ID's should only appear once in the HTML (your <a> each have the same ID)
Change your id to class to fix that:
<a href="popupB.html" class="link" target="PopUp">
Full Code
/*Modify popups.js and .html so that only links with a specific class value
trigger the createPopup() function*/
function createPopup(e) {
'use strict';
// Get the event object:
if (typeof e == 'undefined') var e = window.event;
// Get the event target:
var target = e.target || e.srcElement;
// Create the window:
var popup = window.open(target.href, 'PopUp','height=100,width=100,top=100,left=100,location=no,resizable=yes,scrollbars=yes');
if (!popup)
console.log('Error:', "popup doesn't exist");
// Give the window focus if it's open:
if (popup && (popup !== null) && !popup.closed) {
popup.focus();
return false; // Prevent the default behavior.
} else { // Allow the default behavior.
return true;
}
} // End of createPopup() function.
// Establish functionality on window load:
window.onload = function() {
'use strict';
// Add the click handler to each link:
for (var i = 0, count = document.links.length; i < count; i++) {
var link = document.links[i];
if (link.classList.contains('link')){
link.onclick = createPopup;
}
} // End of for loop.
}; // End of onload function.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Popup Windows</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<!-- Script 9.4 - popups.html -->
<p>B Link (Will open in a new window.)</p>
<p>A Link (Will open in a new window.)</p>
<script src="js/popups.js"></script>
</body>
</html>
YOu can add a specific class to those link which will trigger pop up.
Change the HTML , remove the duplicate id & add a common class
<p>B Link (Will open in a new window.)</p>
<p>A Link (Will open in a new window.)</p>
Now you cna use document.querySelectorAll to get the elements with specific class. You can also you document.getElementsByClassName
var getLink = document.querySelectorAll('.pop')
Then use the loop to add event to it
for (var i = 0, count = getLink.length; i < count; i++) {
getLink[i].onclick = createPopup;
}
Not tested , but you can give a try. Hope this snippet will be useful
You can use className property of dom for checking the class name that need to trigger popup function
for (var i = 0, count = document.links.length; i < count; i++) {
if(document.links[i].className=="required_className")
document.links[i].onclick = createPopup;
}

Browser back button functionality issue [duplicate]

I am building a web application where I need to prevent back navigation in the browser history. After searching the threads in StackOverflow I found this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<title>Untitled Page</title>
<script type = "text/javascript" >
function changeHashOnLoad() {
window.location.href += "#";
setTimeout("changeHashAgain()", "50");
}
function changeHashAgain() {
window.location.href += "1";
}
var storedHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != storedHash) {
window.location.hash = storedHash;
}
}, 50);
</script>
</head>
<body onload="changeHashOnLoad(); ">
Try to hit the back button!
</body>
</html>
Reference Disable browser's back button
I did not change anything in the JavaScript. However, after using this in my code, I am observing another problem while the page is being visited. The webpage is getting auto-scrolled to the top prohibiting viewing the bottom part of the page alongwith disabling of some other features also.
The interesting part is that the page is not showing this symptom when I manually hit the refresh button. I am not getting what is causing this issue.
See, my basic requirement is to stop users visiting the previous page. If any other alternative is there, that would also be welcome.
Please help me to fix this. Thanks in advance.
I have modified code. Now its works in all modern browsers, IE8 and above
var storedHash = window.location.hash;
function changeHashOnLoad() {
window.location.href += "#";
setTimeout("changeHashAgain()", "50");
}
function changeHashAgain() {
window.location.href += "1";
}
function restoreHash() {
if (window.location.hash != storedHash) {
window.location.hash = storedHash;
}
}
if (window.addEventListener) {
window.addEventListener("hashchange", function () {
restoreHash();
}, false);
}
else if (window.attachEvent) {
window.attachEvent("onhashchange", function () {
restoreHash();
});
}
$(window).load(function () { changeHashOnLoad(); });
You are basically reloading the page every 50 ms through
window.location.href += "#";
window.location.href += "1";
Since the browser reloads when the location.href attribute changes.And you call that method again after that reload.
So the site starts to display at the top again every time.
You might generate the hash within a variable and use that for comparison i guess.

How to send a web page from a textarea to iframe

So I have an iframe that's supposed to hold the rendered code from a textarea once a button is pressed, but I'm not sure how to do this in javascript or jquery. I'm aware of how to send a specific site with a URL to display inside a webpage, but for some reason when I try to render the textarea and send it to the iframe, it doesn't work.
this is my iframe:
<iframe id="outputIframe"></iframe>
this is the function I wrote to send contents from textarea editor (this works just fine with a but not with ):
function openIframe() {
var e = document.getElementById('outputIframe');
var editorHTML = editor.getValue();
e.document.innerHTML = editorHTML;
}
So the editor (codemirror) holds the HTML code which users write, and then it should output in the 'outputIframe' iframe element when users press a button. This is similar to the "Try it" sections of w3schools.
function openIframe() {
var editorHTML = editor.getValue();
var iframe = document.getElementById('outputIframe');
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(editorHTML);
iframe.contentWindow.document.close();
}
http://jsfiddle.net/tintucraju/2Lsr9ju9/
Using jquery you can type:
$("iframe").contents().find("body").html(yourHTML);
Important to say, this only works if iframe and your parent window are on the same domain, by security reasons.
This will do the trick - just keep in mind that different browsers will accept different maximum lengths of dataURL.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
function allByClass(className){return document.getElementsByClassName(className);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(elem, className){elem.classList.toggle(className);}
function toggleClassById(targetElemId, className){byId(targetElemId).classList.toggle(className)}
function hasClass(elem, className){return elem.classList.contains(className);}
function addClass(elem, className){return elem.classList.add(className);}
function removeClass(elem, className){return elem.classList.remove(className);}
function forEachNode(nodeList, func){for (var i=0, n=nodeList.length; i<n; i++) func(nodeList[i], i, nodeList); }
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
byId('displayBtn').addEventListener('click', onDisplayBtn, false);
}
function onDisplayBtn()
{
var rawInput = byId('htmlInput').value;
var base64Output = "data:text/html;base64," + btoa(rawInput);
byId('htmlOutput').src = base64Output;
}
</script>
<style>
</style>
</head>
<body>
<textarea id="htmlInput" style="width: 462px; height: 185px;"></textarea>
<hr>
<button id='displayBtn'>Display</button>
<br>
<iframe id='htmlOutput' style="width: 462px;"></iframe>
</body>
</html>

Browser Detection and Compatibility Checking with Java Script

I am trying to detect browser types and IE compatibility from user agent and redirect accordingly. It works only in IE but not in Firefox and Chrome. I am still looking around the solution and cannot figure out yet.
<html>
<head>
<title>Testing </title>
<script src="UserAgent.js" type="text/javascript"></script>
</head>
<body>
<div id="results">Output</div>
<script type="text/javascript">
if (UserAgent.firefox){
window.location.href("http://www.yahoo.com");
}
if (UserAgent.compatibilityMode) {
window.location.href("http://192.168.10.236/iecorrect.html");
} else {
window.location.href("http://www.apple.com");
}
</script>
</body>
</html>
UserAgent.js
if (typeof jQuery == 'undefined') {
document.write("\<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'>\<\/script>");
}
// Create new object
var UserAgent = {
init: function () {
// Get the user agent string
var ua = navigator.userAgent;
this.compatibilityMode = false;
this.firefox = ua.toLowerCase().indexOf("firefox") > -1;
this.chrome = ua.toLowerCase().indexOf("chrome") > -1
if (ua.indexOf("MSIE 7.0") > -1) {
this.compatibilityMode = true;
}
}
};
// Initialize the object
ieUserAgent.init();
Change your window.loacation.href calls to the below code:
if (UserAgent.compatibilityMode) {
window.location.href = "http://192.168.10.236/iecorrect.html";
} else {
window.location.href = "http://www.apple.com";
}
You wrote them like you would write jQuery :)
To check for IE and/or a specific version of IE you are better off using conditional statements.
http://www.quirksmode.org/css/condcom.html

Categories

Resources