Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a PDF file with Electron JS

I am trying to create an Electron JS app that has the purpose to print letter size PDFs.

This is my snippet of code for printing:

win = new BrowserWindow({   width: 378,    height: 566,    show: true,    webPreferences: {     webSecurity: false,     plugins: true   } });  // load PDF win.loadURL('file://' + __dirname + '/header1_X_BTR.pdf');  // if pdf is loaded start printing win.webContents.on('did-finish-load', () => {   win.webContents.print({silent: true, printBackground:true}); }); 

My issues are: if I have print({silent:true}) my printer prints an empty page. If I have print({silent:false}), the printer prints in the same way as the screenshot, with headers, controls, etc.

enter image description here

I need a silent print of the PDF content, and I can't manage to do it for days. Did anyone experience the same thing with Electron?

like image 526
Grig Dodon Avatar asked Apr 04 '18 12:04

Grig Dodon


People also ask

How do you create an electron PDF?

Generate PDF in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module. Approach 1: Convert the contents of the current active BrowserWindow Instance and save it as a PDF file. index.


1 Answers

If you have already have the pdf file or you save the pdf before printing "I assuming it is", then you can grab the file location then you can use externals process to do the printing using child_process.

You can use lp command or PDFtoPrinter for windows

const ch = require('os');  switch (process.platform) {     case 'darwin':     case 'linux':         ch.exec(             'lp ' + pdf.filename, (e) => {                 if (e) {                     throw e;                 }             });         break;     case 'win32':         ch.exec(             'ptp ' + pdf.filename, {                 windowsHide: true             }, (e) => {                 if (e) {                     throw e;                 }             });         break;     default:         throw new Error(             'Platform not supported.'         ); } 

I hope it helps.

Edit: You can also use SumatraPDF for windows https://github.com/sumatrapdfreader/sumatrapdf

like image 135
zer09 Avatar answered Sep 24 '22 17:09

zer09