我会回答,因为我尝试了这个解决方案并且它有效,但很难让它发挥作用,但后来我尝试了另一种方法。
我推荐使用 ngx-electron,效果很好!!不涉及任何问题,并且可以快速构建。
首先你必须像往常一样创建你的 main.js。构建您的方法,然后在您的组件中使用 ngx electron。我举了一个让我疯狂了很长时间的例子,但没有有效的例子
app.module.ts 中的第一个
import { NgxElectronModule } from 'ngx-electron';
imports: [NgxElectronModule,
FormsModule ,
HttpClientModule ,
BrowserModule,
]
然后在你的模块中
在我的情况下,我需要实现无声打印
export class PrincipalComponent implements OnInit {
@ViewChild('myDiv', {static: false}) myDiv: ElementRef; // reference of view i want to print
constructor(
private authenticationService: AuthenticationService,
private _electronService: ElectronService) {}
generarPdf(){
this.documento ='';
this.imprimir = true;
this.horario = formatDate(new Date(), 'dd/MM/yyyy hh:mm', 'en');
this._electronService.ipcRenderer.send('print-to-pdf', this.myDiv.nativeElement.innerHTML);
this._electronService.ipcRenderer.on('wrote-pdf', function(event, path){
this.documento ='';
console.log('respueta recibida '+ path);
});
setTimeout(() =>
{
this.imprimir = false;
},
3000);
}
在 main.js 中
ipc.on('print-to-pdf',function(event, data){
console.log('ingreso a imprimiendo');
win.webContents.printToPDF(pdfSettings()).then(data => {
const pdfPath = path.join(os.tmpdir(),'./generated_pdf.pdf' );
win.webContents.print({silent: true}, (success, errorType) => {
if (!success){
console.log(errorType)
} else{
console.log('print success');
}
})
fs.writeFile(pdfPath, data, (error) => {
if (error) throw error
console.log(`Wrote PDF successfully to ${pdfPath}`)
})
}).catch(error => {
console.log(`Failed to write PDF to ${pdfPath}: `, error)
})
function pdfSettings() {
var option = {
landscape: false,
marginsType: 0,
printBackground: false,
printSelectionOnly: false,
};
return option;
}