-
Notifications
You must be signed in to change notification settings - Fork 3.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Custom printing API #4911
Comments
How about something 'simple', like a print function on the nw Window:
Would also need a function to return a list of all available printers. |
We are working on a project where printing is pretty important and it would be awesome to use an API like this. Here is a list of feature requests:
Thanks You! |
@rogerwang Just saw electron supports win.printToPDF(options, callback). |
@AndryBray it will be included. Thanks to all the suggestions. |
Support nw.Window.print(options), where options could have: 'pdf_path' - output filename if printing to pdf 'printer' - name of the printer 'headerFooterEnabled' - whether to turn on header and footer nw.Window.getPrinters(GetPrintersCallback callback) where callback is a function to receive an array of printer information.
Support nw.Window.print(options), where options could have: 'pdf_path' - output filename if printing to pdf 'printer' - name of the printer 'headerFooterEnabled' - whether to turn on header and footer nw.Window.getPrinters(GetPrintersCallback callback) where callback is a function to receive an array of printer information.
NW v0.14.6 LTS released with custom printing API http://nwjs.io/blog/v0.14.6/ |
This was fast! Thanks You very much! I tested it and there is two things i can't get to work: win.getPrinters returned this printer in one of its array->objects: It prints without print dialog but to the printer I last set in the print dialog before not to the printer option value path. Windows 10, v0.14.6, the printer is a network printer, can print to it in chrome print dialog |
@kailniris I made a fix and verify it working: http://dl.nwjs.io/live-build/06-02-2016/nw14-d775bb5-1a287bf-2a9e6e1-5a26102/v0.14.7/ Would you try it again and see if there are other issues? Thanks. |
Hello, win.print({'printer': 'SHARP AR-5620N'}); works fine as intended win.print({'printer': 'SHARP AR-5620N2'}); uses default printer set in chrome print dialog cuz this printer does not exists, works as intended win.print({'printer': '\OFFICE-5\HP LaserJet P2035'}); does NOT work but i can use it in print dialog win.print({'pdf_path': 'C:\asd.pdf'}) does NOT work, does not print to default printer and does not create the pdf in this location, nor any headerFooterEnabled: works fine landscape: works fine shouldPrintBackgrounds: works fine mediaSize: works fine Windows 10, v0.14.7 |
I tried it with something like E:/1.pdf and it works. Could you please On Thu, Jun 2, 2016, 3:08 PM kailniris [email protected] wrote:
|
Confirmed it works with win.print({'pdf_path': 'C:/Dev/test.pdf'}) Could the \ slashes the problem with the "\OFFICE-5\HP LaserJet P2035" printer name? Another thing i found out if i use the win.print() function the regular print (dialoged one) print to pdf will not work till nw restart. |
Im trying to print PDF directly to a printer: And the only option thats printing is the win.print({}) ( function printDialog() ), others just show the printing Layout just like in chrome, and it gets hidden automaticly and no job to the printer gets sent. Im running: nwjs-sdk-v0.14.7-win-x64.zip
|
It seems to remember the last |
@rogerwang, @Gimmeaphatbeat, @jasminmif, @kailniris Custom "Silent" printing -- win.print({options}) seems to be developing nicely. But "normal" (HTML5 print dialog window) printing has been lost..... at least on Windows-32.... hasn't it? |
@notsospecial1 |
" Window.print() is not a function " |
@notsospecial1 |
Great !! It works and I can go back and forth between dialoged- and silent- printing. Now I need to figure out exactly why it works (I've never been a fan of naming everything the same in requires, function definitions, etc -- for just this reason). I assume this has also solved your issue posed above, "Another thing i found out if i use the win.print() function the regular print (dialoged one) print to pdf will not work till nw restart". Thanks again |
@notsospecial1 |
Works fine for me ( Win 10 on old 32-bit Win XP => Win 7 => Win 10 Sony Vaio). |
Here is my quick-and-dirty index.html file....
Actually, dirty it may be, but hardly quick --- it took me 15 minutes to get the code showing.... |
@notsospecial1 |
The Save To PDF using normal print not working til app restart can be "solved" by running: |
"Storing the printer settings before the custom printing api call and restoring them after would probably solve this." I have been trying to figure this out.... I presume the "printer" whose "settings" would be stored and restored would be the one utilized for silent printing. But I have no clue as to the storing/restoring code (win 10 -ia32). Are we talking the "preferences" or "properties" as shown in the devices and printers settings? And how is it done programmatically? (i.e. in javascript)? Any clues would be welcome, and thank you for the "pseudo-workaround" solution. |
To all: I just fixed the "print to pdf" issue in normal print dialog. It will be available in the next nightly build. @fanchou using 'pdf_path' is supposed to specify the output pdf path when you print the current page... |
@gerdus This is a bit misleading, the only reason why win.print({'pdf_path': ''}) prompts a dialog cuz the last used option in print dialog was savetopdf. If you set a printer in the chrome print dialog then you call win.print({'pdf_path': ''}) then the doc will be printed to the printer you lastly set. |
@rogerwang: When printing silently (e.g., to PDF or directly to some printer), the Chromium print dialog pops up for a short while and then disappears once the job is spooled. This is the case for Windows, at least. Silent mode should really be silent without any additional modals spawning. Would it be possible to implement an additional boolean flag like Currently, a workaround is to spawn another hidden NW.js window and print from there, but that's a little ugly. Behavior:Source:<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Print Test</title>
<style>@media print {button {display: none}}</style>
<script>
function printToPdf()
{
nw.Window.get().print({pdf_path:'c:/foo.pdf', headerFooterEnabled:false});
}
</script>
</head>
<body>
<pre>Lorem ipsum dolor sit amet, consectetur adipisicing.</pre>
<button onclick="printToPdf()">Print to PDF</button>
</body>
</html> |
@rdtsc Does it prints, cause when i use the same code, it does not. Correct me if im wrong but
|
Hi, the new printing feature is very nice . We are using it in our application. We developed an application for our delivery partners so they can receive orders from our website which will be automatically printed. Works fine. We can't push multiple printjobs at once because we first create a local PDF file received from our API but we have settle this using a custom function which check every five seconds for new printjobs and execute one printjob at a time (some kind of print queue). In our application the client can choose a normal A4 printer and a POS printer. We noticed that when a printjob is executed, the default printer on Windows has been changed. Is this a bug in Chromium? When we execute the print function, we defined the printer name. Is there a way to get the default printer and set the default printer again after the printjob has been executed? See my issue #5300 |
we're trying to use the print API to hide chrome's headers/footers, but now the print preview pops up briefly and disappears anybody else seeing this? to be clear, we're trying to customize the print settings but are not looking for silent printing (my understanding is that is provided independently by kiosk-printing flag) nw 0.19.1; also tried 0.16.4 |
maybe result of |
after running in circles for quite a while (there are so many threads about printing that all reference each other, it's almost kafkaesque), two questions:
thanks a lot for any help!!! in html file: in javascript: |
@KarlKrach: AFAIK, the scriptable printing API only works with You can see some basic sample code in my earlier comment. As mentioned in my comment, I use a hidden window to work around the brief print dialog popup issue. I've got a Windows app in production that uses something similar to this technique without user complaints: package.json: {
"name": "nwjs-print-demo",
"main": "index.html"
} index.html: <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NW.js Silent Printing Demo</title>
</head>
<body>
<textarea id="payload" placeholder="HTML"></textarea>
<button id="print">Print</button>
<script>
document.addEventListener('DOMContentLoaded', () => {
const $ = document.querySelector.bind(document);
const textarea = $('#payload');
$('#print').onclick = () => {
const data = textarea.value.trim() ||
'<img src="https://nwjs.io/img/logo.png">';
const payload = `data:text/html,${encodeURI(data)}`;
nw.Window.open(payload, {show: false}, (win) => {
win.on('loaded', () => {
const filename = 'result.pdf';
win.print({
pdf_path: filename,
headerFooterEnabled: false
});
win.close();
nw.Shell.openItem(filename);
});
});
};
});
</script>
</body>
</html> IIRC, I use For what it's worth, if you need more advanced control over your PDFs, I'd recommend taking a look at wkhtmltopdf provided that it fits your redistributable size allowance, if any. |
... it did take me some time to understand the magic happening in your code - but since i did, it works really well. again: thank you so much!! one question left: when printing, the screen briefly freezes for like a second or so - which will not be much of an issue in most of the cases but since i have a continous animation going on, it does look quite irritating. i tried circumventing this by introducing a setTimeout which, according to this link https://javascriptweblog.wordpress.com/2010/06/28/understanding-javascript-timers/ should defer execution to a low priority queue - but that did not do the trick. apart, just in case someone else should have the same questions as me:
|
May 31, 2016
Is there a way to run a callback for when a print finishes. If so it isn't documented: Would it be possible to add this feature, or, if it already exists, have the documentation updated to reflect that. |
@TheJaredWilcurt |
Yeah, it is synchronous so there is no callback... |
Hi guys, Even if I set 'show' to false in the open window options, when I call 'print' to a specific or default printer, the window shows up for a few seconds. I couldn't find a way to keep this window hidden, is there a fix for it or something? Behavior: Source: package.json index.html
I'm using NW.js v0.20.3 SDK on macOS 10.12.3, btw. Thanks! |
hi, |
@KarlKrach - since printing is synchronous, it will lock the main UI thread. Moving your print routine to a web worker may resolve your issue. |
@KarlKrach Open a new window in a new render process (new_instance). You can safely print from there it wont freeze other windows in different threads. |
hi! this was quick, thank you so much for helping me!!! from my main script i just open up the new window with the "toprinter"-string is a complete html-site including: now, that does work and fixes the lag but:
or do i get the whole concept wrong? |
@KarlKrach: it's been a while, but it might be that the Node context is not made available to the standalone data URI instance because of the lack of the Since #4418 is still open, you may want to try spawning an HTML file with package.json{
"name": "nwjs-print-test",
"main": "index.html"
} index.html<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>NW.js Print Test</title>
<script>
function getRandomString() {
return Math.random().toString(32).slice(2);
}
function printAsync(html, printOpts, callback) {
this.id = ++this.id || 1;
const channel =
new BroadcastChannel(`${nw.App.manifest.name}-print-job-${this.id}`);
channel.onmessage = (event) => {
switch(event.data) {
case 'ready': {
channel.postMessage(html);
} break;
case 'done': {
channel.close();
callback();
} break;
}
};
printOpts = encodeURIComponent(JSON.stringify(printOpts));
nw.Window.open(`print.html?id=${this.id}&opt=${printOpts}`, {
show: true,
new_instance: true
});
}
document.addEventListener('DOMContentLoaded', () => {
const printBtn = document.querySelector('#print');
printBtn.onclick = () => {
printBtn.disabled = true;
printBtn.innerText = 'Printing in progress...';
printAsync(getRandomString().repeat(10000), {
pdf_path: `./tmp/${getRandomString()}.pdf`,
headerFooterEnabled: false
}, () => {
printBtn.disabled = false;
printBtn.innerText = 'Print';
});
};
const counter = document.querySelector('#counter');
setInterval(() => counter.innerText = (+counter.innerText + 1), 50);
});
</script>
</head>
<body>
<p>App UI is responsive: <span id="counter">0</span></p>
<button id="print">Print</button>
</body>
</html> print.html<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Printing...</title>
<script>
document.addEventListener('DOMContentLoaded', () => {
const url = require('url'),
qs = require('querystring'),
win = nw.Window.get();
const {id, opt} = qs.parse(url.parse(window.location.href).query);
const channel =
new BroadcastChannel(`${nw.App.manifest.name}-print-job-${id}`);
channel.onmessage = (event) => {
document.body.innerHTML = event.data;
setTimeout(() => {
win.print(JSON.parse(opt));
setTimeout(() => {
channel.postMessage('done');
channel.close();
win.close();
}, 1000);
}, 1000);
};
channel.postMessage('ready');
});
</script>
</head>
<body style="word-wrap: break-word">
</body>
</html> |
hi rdtsc, |
again, hi rdtsc. ps.: if i can get you a crate of beer for this, let me know!!! |
So this issue is resolved now? |
Hi, I'm trying to print a jpg file and i get some troubles... let filename = 47_abeille.jpg;
let filePath = global.__dirname + '/_content/ressources/reperes/' + filename;
nw.Window.open('file://' + filePath, {
show: true,
new_instance: false,
width: 800,
height: 600
}, function (win) {
win.on('loaded', function () {
try {
win.print({
autoprint: false,
landscape: true,
headerFooterEnabled: true,
headerString: filename,
footerString: ''
});
win.close();
} catch (exception) {
console.log('print exception', exception);
}
});
}); Have you any advice about this issue? |
It works fine for me on Mac with nwjs-sdk-v0.26.6.
|
I just tried with nwjs-sdk-v0.26.6 and get the same issue... |
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. |
As proposed in #1263 (comment)
The text was updated successfully, but these errors were encountered: