Generating PDF in Electron App


| 0 Comments

angular2 electron typescript

this is how to generate pdf file in Electron (angular2).



add webview directive

webview.ts

1
2
3
4
5
6
import { Directive } from '@angular/core';

@Directive({ selector: 'webview' })
export class WebviewDirective {
	
}



add Component

generate_pdf.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { Component } from '@angular/core';
import { remote } from 'electron';
import { writeFileSync } from 'fs';

@Component({
	selector: 'genPDF',
	templateUrl: 'gen_pdf.html'
})
export class GeneratePDFComponent {
	app = remote.app;
	webview: any;

	constructor() { }

	generate_pdf_file() {
		
		// get webview
		this.webview = document.getElementById('webview');
		
		// app path
		var _path = this.app.getPath('userData');
		
		// load your file into webview
		this.webview.loadURL(_file_path);
		
		// when content loaded
		this.webview.addEventListener('dom-ready', function handler() {
			
			// insert custom css here 
			_t.webview.insertCSS("@page{  background-color: transparent !important; -webkit-print-color-adjust: exact !important; size: 64px 64px; margin: 0 0 0 0; margin: 2px -10px -20px -10px; } svg{ width: 100%; height: 100%; }");
			
			// print to pdf
			_t.webview.printToPDF({
				// to enable transparent or any color
				printBackground: true
			}, function (error, data) {
				
				// write the binary data to file
				writeFileSync(_path + '/test.pdf', data);
			});
		});
	}
}


add view

gen_pdf.html

1
2
3
<webview id="webview" src="#" style="visibility:hidden;"></webview>

<button (click)="generate_pdf_file()">Generate PDF</button>



make sure to add directive to module in declarations