Search

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

import { Directive } from '@angular/core';

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



add Component

generate_pdf.ts


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

<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