function CallPrint() {
var prtContent = document.getElementById('<%= pnlDelete.ClientID %>');
var winPrint = window.open('', '', 'left=0,top=0,width=800,height=600,toolbar=0,scrollbars=0,status=0');
winPrint.document.write("<h3>Summary</h3><br />" + prtContent.innerHTML);
winPrint.document.close();
winPrint.focus();
winPrint.print();
winPrint.close();
}
I have a need where I have to print contents of a div. I am using above code to do so. It is working fine in IE but does nothing in Firefox. Am I missing something here that needs to be done in Firefox?
Instead of opening a new window without any URL, I opened this page in the window and accessed the contents of the pnlSummary from the opened window via window.opener object –
function CallPrint() {
var winPrint = window.open('Print.aspx', '', 'left=0,top=0,width=800,height=600,toolbar=0,scrollbars=0,status=0');
}
On Print.aspx page I used this function –
function Print() {
var prtContent = "<h3>Summary</h3>" + window.opener.document.getElementById('ctl00_cphContent_pnlSummary').innerHTML;
document.getElementById("printDiv").innerHTML = prtContent;
window.print();
window.opener.focus();
window.close(); }
and called it on body onload.
<body onload="Print();">
<form id="form1" runat="server">
<div id="printDiv">
</div>
</form>
</body>
This is working fine in both IE and Firefox.
Use setTimeout() function for loading the page. The example is given bellow link.
http://oraclehappy2help.blogspot.in/2012/09/child-window-printing-problem-solution.html
Uhm... your code seems to work fine for me, on Firefox 3.5 (Windows).
It's possible that are something wrong on your pnlDelete.ClientID?
Your javascript code is rendered well on the page?
Anyway I suggest you to use jQuery + a print plugin like this.
Check to ensure your panel has something. My guess is prtContent is undefined
Try this:
function CallPrint() {
var prtContent = document.getElementById('<%= pnlDelete.ClientID %>');
if (prtContent) {
var winPrint = window.open('', '', 'left=0,top=0,width=800,height=600,toolbar=0,scrollbars=0,status=0');
winPrint.document.write("<h3>Summary</h3><br />" + prtContent.innerHTML);
winPrint.document.close();
winPrint.focus();
winPrint.print();
winPrint.close();
}
else {
alert('No summary available for printing');
}
}
you can use JS Printer Setup https://addons.mozilla.org/en-us/firefox/addon/js-print-setup/"
which is Fire fox Depended addon most usefulladdon In web-app Kisok in Firefox to select printer
attached some example for attached printer and local printer it may help you to build without print dialog.
function EB_Print(printType) {
try{
var printerType = printType; // type of the Print Code : network
// Default Printer Configuring
var Default_printer = "Canon MG2500 series";
/** local Printer configuring via Network
** Config teh Local server use \\\\ to get \\
**/
var Organizer_Printer = "\\\\network\\Canon LBP2900";
jsPrintSetup.setPrinter(Default_printer);
jsPrintSetup.setSilentPrint(true);// withoud dialog
/** alert(jsPrintSetup.getPrintersList()); // Debugger for the attached Printers list
alert(jsPrintSetup.getPrinter()); // get the set printer Option
**/
// id network is selected It will print the page in network
if(printerType == 'network'){
jsPrintSetup.setPrinter(Organizer_Printer);
}
jsPrintSetup.print(); // Print the page
}catch (e) {
// TODO: handle exception
}
}
you could try a jquery plugin...
http://plugins.jquery.com/project/PrintArea
Related
I want to print the page on load in both Windows and Andriod using any browser including google chrome.
I have tried to print on crome in Andriod phone using window.print() but it was giving error,
<script type="text/javascript">
setTimeout(function () {
if (typeof(window.print) != 'undefined') {
window.print();
window.close();
}
}, 1500);
</script>
So I tried some help from google cloud print and what I found is that, it's been deprecated since 31th Dec 2020.
Here is my code for that,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
setTimeout(function () {
if (isAndroid) {
// https://developers.google.com/cloud-print/docs/gadget
var gadget = new cloudprint.Gadget();
gadget.setPrintDocument("url", $('title').html(), window.location.href, "utf-8");
gadget.openPrintDialog();
} else {
if (typeof(window.print) != 'undefined') {
window.print();
window.close();
}
}
}, 1500);
</script>
Can anyone help me in this.
I want to print the URL on load in both Windows and in Andriod.
I implemented as follow:
Added iframe element to page
<iframe id="print-frame" class="print-frame" title="Print" src="https://www.w3schools.com" onload="print"></iframe>
print-frame {display: none}
function print() {
var frame = document.getElementById('print-frame');
if (!frame) return;
var frameWindow = frame.contentWindow;
if (!frameWindow) return;
frameWindow.print();
}
iframe is hidden but onload it opens print dialog. On windows it's enough for printing.
for android I use PaperCut https://www.papercut.com/products/free-software/mobility-print/
Install server part on PC where printers are connected, share printers in admin web UI.
On Android install MobilityPrint app, turn on Print service 'Mobility Print'
then in Chrome browser select Share->Print and select any MobilityPrint service printer
I am trying to copy 'window.location.href' e.g. the URL of the current page to clipboard from my extension.
My issue is that when I copy the URL to clipboard, it is the extensions URL that is copied and not the page I am visiting.
Extensionbar:
<!DOCTYPE HTML>
<html>
<head>
<button onclick="copyFunction();">Copy</button>
<script type="text/javascript">
function copyFunction() {
var inputDump = document.createElement('input'),
hrefText = window.location.href;
document.body.appendChild(inputDump);
inputDump.value = hrefText;
inputDump.select();
document.execCommand('copy');
document.body.removeChild(inputDump);
}
</script>
</head>
</html>
From my understanding the solution should be this, but I fear I am too clueless how to proceed: https://developer.apple.com/documentation/safariservices/safari_app_extensions/passing_messages_between_safari_app_extensions_and_injected_scripts
This is how I (tried to) proceed, by creating a global.html page and an injected script.
Global page:
<!DOCTYPE HTML>
<script>
safari.application.addEventListener("command", copyFunction, false);
function copyFunctionEvent(event) {
if (event.command == "CopyToClipboard") {
safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("CopyToClipboard", "all");
}
}
</script>
Injected script:
function myextension_openAll(event){
if (event.name == 'CopyToClipboard'){
function copyFunction() {
var inputDump = document.createElement('input'),
hrefText = window.location.href;
document.body.appendChild(inputDump);
inputDump.value = hrefText;
inputDump.select();
document.execCommand('copy');
document.body.removeChild(inputDump);
}
}
safari.self.addEventListener("message", myextension_openAll, true);
Actual:
safari-extension://com.myextension-0000000000/abc123/extensionbar.html
Expected:
http://www.google.com (e.g. if current tab)
From your code above (Extensionbar html), you seem to write legacy Safari extension (.safariextz), and it has been deprecated. See What’s New in Safari and WebKit" session on WWDC18
I recommend you rewrite your code into Safari App Extension by following process, which can be written in Swift. I'm not sure why wrong URL is copied to clipboard in your code, but rewriting your code would solve the problem as a result.
Creating App Extension project
Create App Extension by following [File] -> [New] -> [Project...] then choose [Safari Extension App] on Xcode. Project template contains example of menubar implementation.
Copying location.href by clicking menu bar button
Following code would add functionality to copy location.href when you click menu bar button.
Just paste this into SafariExtensionHandler.swift.
class SafariExtensionHandler: SFSafariExtensionHandler {
override func messageReceived(withName messageName: String, from page: SFSafariPage, userInfo: [String : Any]?) {
// WHen injected script calls safari.extension.dispatchMessage, the message will come here
guard let href = userInfo?["href"] as? String else { return }
// Save href to clipboard
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(href, forType: .string)
}
override func toolbarItemClicked(in window: SFSafariWindow) {
// Request injected script a message to send location.href
window.getActiveTab { currentTab in
currentTab!.getActivePage { currentPage in
currentPage!.dispatchMessageToScript(withName: "getHref", userInfo: nil)
}
}
}
}
And injected script (script.js) as follows.
safari.self.addEventListener("message", function(event) {
console.log("event received");
safari.extension.dispatchMessage("sendHref", { "href": location.href });
});
Working Example
Complete working code here, This may help your work. Good luck :)
https://github.com/horimislime/safari-extension-menubar-example
I am relatively new to JS so apologies for any basic errors I have made here.
I am attempting to insert some JS on our site that will detect if the user has Flash enabled & the site is able to launch a popup, if these fail the user will be directed to a support page to resolve these.
The code works without issue on Chrome and Firefox, the issue I am having is on IE the popup which launches as a test is not being closed by the script.
Am I missing something glaringly obvious?
function loadpopunder(){
var popupBlockerChecker = {
check: function(popup_window){
var _scope = this;
if (popup_window) {
if(/chrome/.test(navigator.userAgent.toLowerCase())){
setTimeout(function () {
_scope._is_popup_blocked(_scope, popup_window);
},250);
}else{
popup_window.onload = function () {
_scope._is_popup_blocked(_scope, popup_window);
};
}
}else{
_scope._displayError();
}
},
_is_popup_blocked: function(scope, popup_window){
if ((popup_window.outerHeight > 0)===true)
popup.close();
},
_displayError: function(){
popupFail=true;
}
};
var popup = window.open("http://www.google.com", '_blank', "width=10, height=10, left=1, top=1, scrollbars=no, resizable=no");
popupBlockerChecker.check(popup);
}
loadpopunder()
The thing I want to build is that by clicking a button I want to trigger the print of a PDF file, but without opening it.
+-----------+
| Print PDF |
+-----------+
^ Click *---------> printPdf(pdfUrl)
The way how I first tried it is to use an iframe:
var $iframe = null;
// This is supposed to fix the onload bug on IE, but it's not fired
window.printIframeOnLoad = function() {
if (!$iframe.attr("src")) { return; }
var PDF = $iframe.get(0);
PDF.focus();
try {
// This doesn't work on IE anyways
PDF.contentWindow.print();
// I think on IE we can do something like this:
// PDF.document.execCommand("print", false, null);
} catch (e) {
// If we can't print it, we just open it in the current window
window.location = url;
}
};
function printPdf(url) {
if ($iframe) {
$iframe.remove();
}
$iframe = $('<iframe>', {
class: "hide",
id: "idPdf",
// Supposed to be a fix for IE
onload: "window.printIframeOnLoad()",
src: url
});
$("body").prepend($iframe);
}
This works on Safari (desktop & iOS) and Chrome (can we generalize it maybe to webkit?).
On Firefox, PDF.contentWindow.print() ends with a permission denied error (even the pdf is loaded from the same domain).
On IE (11), the onload handler is just not working.
Now, my question is: is there another better way to print the pdf without visually opening it to the user?
The cross browser thing is critical here. We should support as many browsers as possible.
What's the best way to achieve this? Is my start a good one? How to complete it?
We are now in 2016 and I feel like this is still a pain to implement across the browsers.
UPDATE: This link details an elegant solution that involves editing the page properties for the first page and adding an action on Page Open. Works across all browsers (as browsers will execute the JavaScript placed in the actions section). Requires Adobe Acrobat Pro.
It seems 2016 brings no new advancements to the printing problem. Had a similar issue and to make the printing cross-browser I solved it using PDF.JS but had to make a one-liner addition to the source (they ask you to build upon it in anyways).
The idea:
Download the pre-built stable release from https://mozilla.github.io/pdf.js/getting_started/#download and add the "build" and "web" folders to the project.
The viewer.html file is what renders out PDFs with a rich interface and contains print functionality. I added a link in that file to my own JavaScript that simply triggers window.print() after a delay.
The link added to viewer:
<script src="viewer.js"></script>
<!-- this autoPrint.js was added below viewer.js -->
<script src="autoPrint.js"></script>
</head>
The autoPrint.js javascript:
(function () {
function printWhenReady() {
if (PDFViewerApplication.initialized) {
window.print();
}
else {
window.setTimeout(printWhenReady, 3000);
}
};
printWhenReady();
})();
I could then put calls to viewer.html?file= in the src of an iframe and hide it. Had to use visibility, not display styles because of Firefox:
<iframe src="web/viewer.html?file=abcde.pdf" style="visibility: hidden">
The result: the print dialog showed after a short delay with the PDF being hidden from the user.
Tested in Chrome, IE, Firefox.
After spending the past couple of hours trying to figure this one out and lots of searching here is what I have determined...
The HTML5 Web API spec for Printing indicates that one of the printing steps must fire beforeprint, a simple event (an event that is non-cancelable), to the window object of the Document being printed (as well as any nested browsing contexts, this relates to iframes) to allow for changes to the Document prior to printing. This step is internal to the browser and not something you'll be able to adjust. During this process, the browser's print dialog sometimes shows a preview of the file (Chrome does this)...so if your goal is to never display the file to the viewer you might be stuck.
The closest to achieving this I came was by creating an index.html file which has a button containing data-* attributes which provided context. Change the path/filename.ext in the data-print-resource-uri attribute to a local file of your own.
<!DOCTYPE html>
<html>
<head>
<title>Express</title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<h1>Express</h1>
<p>Welcome to Express</p>
<button name="printFile" id="printFile" data-print-resource-uri="/binary/paycheckStub.pdf" data-print-resource-type="application/pdf">Print File</button>
<iframe name="printf" id="printf" frameborder="0"></iframe>
<script src="/javascripts/print.js"></script>
</body>
</html>
Then in the print.js file, I tried a few things, but never quite got it working (leaving different things I had played with in the comments).
// Reference vars
var printButton = document.getElementById('printFile');
var printFrame = document.getElementById('printf');
// onClick handler
printButton.onclick = function(evt) {
console.log('evt: ', evt);
printBlob('printf', printButton.getAttribute('data-print-resource-uri'), printButton.getAttribute('data-print-resource-type'));
}
// Fetch the file from the server
function getFile( fileUri, fileType, callback ) {
var xhr = new XMLHttpRequest();
xhr.open('GET', fileUri);
xhr.responseType = 'blob';
xhr.onload = function(e) {
// Success
if( 200 === this.status ) {
// Store as a Blob
var blob = new Blob([this.response], {type: fileType});
// Hang a URL to it
blob = URL.createObjectURL(blob);
callback(blob);
} else {
console.log('Error Status: ', this.status);
}
};
xhr.send();
}
function printBlob(printFrame, fileUri, fileType) {
// Debugging
console.log('inside of printBlob');
console.log('file URI: ', fileUri);
console.log('file TYPE: ', fileType);
// Get the file
getFile( fileUri, fileType, function(data) {
loadAndPrint(printFrame, data, fileType);
});
}
function loadAndPrint(printFrame, file, type) {
// Debugging
console.log('printFrame: ', printFrame);
console.log('file: ', file);
window.frames[printFrame].src = file;
window.frames[printFrame].print();
/*
// Setup the print window content
var windowContent = '<!DOCTYPE html>';
windowContent += '<html>'
windowContent += '<head><title>Print canvas</title></head>';
windowContent += '<body>'
windowContent += '<embed src="' + file + '" type="' + type + '">';
windowContent += '</body>';
windowContent += '</html>';
// Setup the print window
var printWin = window.open('','','width=340,height=260');
printWin.document.open();
printWin.document.write(windowContent);
printWin.document.close();
printWin.focus();
printWin.print();
printWin.close();
*/
}
I think that if you can get it working properly using the Blob might work the best in the cross-browser method you wanted.
I found a few references about this topic which might be helpful:
How to send a pdf file directly to the printer using JavaScript?
https://www.w3.org/TR/html5/webappapis.html#printing
https://developer.mozilla.org/en-US/docs/Web/Guide/Printing#Print_an_external_page_without_opening_it
Printing a web page using just url and without opening new window?
I will post here the modified functions of the OP functional on IE 11
printPdf: function (url) {
$('#mainLoading').show();
let iframe = $('#idPdf');
if (iframe) {
iframe.remove();
}
iframe = $('<iframe>', {
style: "display:none",
id: "idPdf"
});
$("body").prepend(iframe);
$('#idPdf').on("load", function(){
utilities.printIframeOnLoad()
})
utilities.getAsyncBuffer(url, function(response){
let path = utilities.getPdfLocalPath(response);
$('#idPdf').attr('src', path);
})
},
printIframeOnLoad: function () {
let iframe = $('#idPdf');
if (!iframe.attr("src")) { return; }
var pdf = iframe.get(0);
pdf.focus();
$('#mainLoading').hide();
pdf.contentWindow.print();
},
getPdfLocalPath: function (data) {
var filename = "Application_" + utilities.uuidv4() + ".pdf";
var blob = new Blob([data], { type: 'application/pdf' });
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
return filename;
}
else {
let url = window.URL || window.webkitURL;
let href = url.createObjectURL(blob);
return href;
}
},
getAsyncBuffer: function (uriPath, callback) {
var req = new XMLHttpRequest();
req.open("GET", uriPath, true);
req.responseType = "blob";
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {
callback(req.response);
}
};
req.send();
}
I am using the below function in order to print a target Div using JS. This works fine in all browsers apart from chrome. The console throws the error: PrintElem is undefined.
function PrintElem(elem) {
Popup($(elem).html());
}
function Popup(data) {
var mywindow = window.open('', 'to_print', 'height=600,width=800');
var html = '<html><head><title></title>' +
'</head><body onload="window.focus(); window.print(); window.close()">' +
data +
'</body></html>';
mywindow.document.write(html);
mywindow.document.close();
return true;
}
I have tried calling the function onclient click with the following:
PrintElement('[id$=divExport]');
PrintElement('divExport');
PrintElement('#divExport');
PrintElement('#ctl00_body_ucJobDetails_divExport');
PrintElement('ctl00_body_ucJobDetails_divExport');
It works in Firefox and incredibly in IE 9 and 11!
Any advice would be greatly appreciated.
Your function name is PrintElem(). But you are calling it as PrintElement(). Apart from this I don't see any other problem..
And use this line.
PrintElem('#divExport');