Print a document with JavaScript - javascript

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("?", "");

Related

Window.print not working for print graph

I have one page where I use java script and css to show graph.When I try to print graph using div content and opening new window it does not work.
Below is screenshot of graph page and print window
I have tried to put css before printing and also added bootstrap js but stil not work.
Below is code that I copy form stackoverflow and modify as I require.Thanks.
function printDiv() {
debugger;
var printContents = $('body').clone().find('script').remove().end().html();
// get all <links> and remove all the <script>'s from the header that could run on the new window
var allLinks = $('head').clone().find('script').remove().end().html();
var js = "";
js += "#Html.Raw(string.Format("<script src='/SkillsAssessmentModule/Scripts/bootbox.min.js'/>"))";
// open a new window
var popupWin = window.open('', '_blank');
// ready for writing
popupWin.document.open();
// -webkit-print-color-adjust to keep colors for the printing version
var keepColors = '<style>body {-webkit-print-color-adjust: exact !important; }</style>';
// writing
// onload="window.print()" to print straigthaway
popupWin.document.write('<html><head>' + keepColors + allLinks + '</head><body>' + document.getElementById("lProgress").innerHTML + js + '</body></html>');
popupWin.print();
// close for writing
popupWin.document.close();
setTimeout(function () { popupWin.close(); }, 1);
}
</script>
}

How to remove the iFrame DOM node that is used for printing

I'm creating a iFrame DOM dynamically only for printing. Here's my code doing the creation and show printing window.
var url, data, _iFrame, nonce, iframeId;
data = new Blob([buffer], {
type: 'application/pdf'
});
url = window.URL.createObjectURL(data);
_iFrame = document.createElement('iframe');
nonce = (new Date()).getTime();
var iframeId = "printPDF" + nonce;
_iFrame.id = iframeId
_iFrame.setAttribute('style', 'visibility:hidden;');
_iFrame.setAttribute('src', url);
document.body.appendChild(_iFrame);
$('#' + iframeId)[0].focus();
$('#' + iframeId)[0].contentWindow.print();
But the thing is, I need to remove the iFrame after the printing is done (either print or cancel). How can I get the event in javascript?
I guess something like this will do the work for you:
$('#' + iframeId)[0].contentWindow.print();
setTimeout(function () { $('#' + iframeId)[0].contentWindow.close(); }, 100);
I actually resolved this on my own.
The first thing is not to hide the iframe. Instead, make it 0 size. style='height: 0;width: 0;'.
Then, bind the focus event of the iframe and remove the iframe when it's focused again after the print dialog gets dismissed.
Well, I tried the focus event, and I failed to get into it because the iframe was hidden.

Chrome print blank page

I have an old javascript code to print images, if a user clicks on the thumbnail. It used to work just fine, but lately (only in Chrome!) there is a blank page in preview.
Here is a demonstration in JsBin: http://jsbin.com/yehefuwaso/7
Click the printer icon. Now try it in Firefox; it will work as expected.
Chrome: 41.0.2272.89 m
Firefox: 30.0, 36.0.1
function newWindow(src){
win = window.open("","","width=600,height=600");
var doc = win.document;
// init head
var head = doc.getElementsByTagName("head")[0];
// create title
var title = doc.createElement("title");
title.text = "Child Window";
head.appendChild(title);
// create script
var code = "function printFunction() { window.focus(); window.print(); }";
var script = doc.createElement("script");
script.text = code;
script.type = "text/javascript";
head.appendChild(script);
// init body
var body = doc.body;
//image
doc.write('<img src="'+src+'" width="300">');
//chrome
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
win.printFunction();
} else {
win.document.close();
win.focus();
win.print();
win.close();
}
}
It looks like it's attempting to print before the <img> has loaded, move the call to print inside an event handler for the load event of window by opening the link as a data URI or Blob, for example
var code = '\
<html>\
<head>\
<title></title>\
<script>\
function printFunction() {\
window.focus();\
window.print();\
window.close();\
}\
window.addEventListener(\'load\', printFunction);\
</script>\
</head>\
<body><img src="'+src+'" width="300"></body>\
</html>';
window.open('data:text/html,' + code, '_blank', 'width=600,height=600');
Don't forget you may need to HTML encode the tags in code
You could probably just listen for load on the <img> instead, but if you ever do anything more complicated than tring to print a single image you may find it breaks again in future
doc.write('<img onload="printFunction();" src="'+src+'" width="300">');
Where printFunction is the print function for all browsers
I encountered the same problem in Chrome. You can try these approaches, the first one worked for me. setTimeout didn't work for me (had to edit this later).
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
w = window.open();
w.document.write(printContents);
w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');
w.document.close(); // necessary for IE >= 10
w.focus(); // necessary for IE >= 10
return true;
}
setTimeout:
<div id="printableArea">
<h1>Print me</h1>
</div>
<input type="button" onclick="printDiv('printableArea')" value="print a div!" />
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
w = window.open();
w.document.write(printContents);
w.document.close(); // necessary for IE >= 10
w.focus(); // necessary for IE >= 10
setTimeout(function () { // necessary for Chrome
w.print();
w.close();
}, 0);
return true;
}
You need to wait for the image to finish loading:
var img = new Image();
img.src = src;
img.style.width = '300px';
img.onload = function(){
doc.write(img);
};

access a element within hidden div element using javascript

I am having an iframe inside a div element which is hidden/display none, I want to get the href attribute of a tag using javascript my code is
HTML
<div id="questions" style="display: none;">
<iframe id="article_frame" width="100%" height="100%">
Click here
</iframe>
</div>
JS
window.onload = function() {
alert("Hello " + window.document.getElementById("article_frame"));
}
But I am getting alert as "Hello null" any solution
Thanks
Thanks All,
I have got the answer with javascript it just simple code
var anchor = document.getElementById('en_article_link').firstChild;
var newLink = anchor.getAttribute("href")+"sid="+sidvalue;
anchor.setAttribute("href", newLink);
Ok i feel this may be a slight overkill but it will get you what you require (the href value of the anchor tag inside the iframe) :
window.onload = function() {
var frame = window.document.getElementById("article_frame");
var myString = frame.childNodes[0].textContent
, parser = new DOMParser()
, doc = parser.parseFromString(myString, "text/xml");
var hrefValue = doc.firstChild.getAttribute('href');
alert("Hello " + hrefValue);
}
I guess it depends on your requirements but another way would be to create a string and then using functions: substring and indexof you could get your value. Here is how you would get the string:
window.onload = function() {
var frame = window.document.getElementById("article_frame");
var elementString = frame.childNodes[0].textContent;
//then perform your functions on the string here
}
Note that you can only access the contents of an iframe that contains a page on the same domain due to the Same-Origin Policy (Wikipedia).
I recommend using jQuery for this. The tricks here are:
Wait for the iframe to finish loading $("#article_frame").ready()
Access the iframe's document $("#article_frame").contents()
From there you're just handling the task at hand:
$("#article_frame").ready(function() {
alert("Hello " + $("#article_frame").contents().find("#en_link").href);
});

Changing JS code from clicking image to clicking link

I found the following JS online, which functions like:
If an image is clicked, open the image in new window and prompt for print. Once printed the window closes. I need this script modified to click a print link it prints an image then closes the new image window. So I want to change from clicking the image itself to clicking a link that says print image.
Here is the code:
<script type="text/javascript">
/* <![CDATA[ */
function makepage(src)
{
// We break the closing script tag in half to prevent
// the HTML parser from seeing it as a part of
// the *main* page.
return "<html>\n" +
"<head>\n" +
"<title>Temporary Printing Window</title>\n" +
"<script>\n" +
"function step1() {\n" +
" setTimeout('step2()', 10);\n" +
"}\n" +
"function step2() {\n" +
" window.print();\n" +
" window.close();\n" +
"}\n" +
"</scr" + "ipt>\n" +
"</head>\n" +
"<body onLoad='step1()'>\n" +
"<img src='" + src + "'/>\n" +
"</body>\n" +
"</html>\n";
}
function printme(evt)
{
if (!evt) {
// Old IE
evt = window.event;
}
var image = evt.target;
if (!image) {
// Old IE
image = window.event.srcElement;
}
src = image.src;
link = "about:blank";
var pw = window.open(link, "_new");
pw.document.open();
pw.document.write(makepage(src));
pw.document.close();
}
/* ]]> */
</script>
<img src="fortune.jpg" onclick="printme(event)" />
I do not know any JS so I apologize. I only do php/mysql.
Best Regards!
Jim.
<img src="someurl.jpg" id="imgid' />
Print the image
function printme(id)
{
var src = document.getElementById(id).src;
var link = "about:blank";
var pw = window.open(link, "_new");
pw.document.open();
pw.document.write(makepage(src));
pw.document.close();
}
In the old method, the printme function knows what image should be printed: the same image that was clicked; when you change the trigger, you need to tell the function explicitly what image you want to print. That is why we are adding an id to the image and pass it to printme function. But if you only have one image on the page, or if a spacial relation exists (like the link always being the immediate next node after the image), then we can do it differently and need no id.
I don't know what your link looks like, but assuming it's just a plain anchor:
Change from:
<img src="fortune.jpg" onclick="printme(event)" />
To:
<img id="printableImage" src="fortune.jpg" onclick="printme(event)" />
<a href="javascript:void(0);" onclick="printme('printableImage')" />
Then alter the printme() function to retrieve the image src from the passed in image element id (jQuery makes this easy):
function printme(printableImageId)
{
var src = $('#' + printableImageId).attr('src');
// the rest of the logic...
}
You'll need to modify the printMe function a bit, doing this should fix it:
function printme(evt)
{
if (!evt) {
// Old IE
evt = window.event;
}
var anchor = evt.target;
if (!anchor) {
// Old IE
anchor = window.event.srcElement;
}
src = anchor.href;
link = "about:blank";
var pw = window.open(link, "_new");
pw.document.open();
pw.document.write(makepage(src));
pw.document.close();
return false;
}
And then on your actual anchor you would do the following:
Print

Categories