PDF Make help us to generate the PDF, using JSON data. This blog uses Angular JS and PDF Make to generate the PDF.
Prerequisites
- <html lang='en'>
- <head>
- <meta charset='utf-8'>
- <title>my first pdfmake example</title>
-
- <script src="Scripts/pdfmake/pdfmake.js"></script>
- <script src="Scripts/pdfmake/vfs_fonts.js"></script>
- <script src="Scripts/angular.js"></script>
- <script src="Scripts/angular-ui-router.js"></script>
- </head>
We need to create a document definition to create a PDF.
- var docDefinition = { content: 'This is an sample PDF printed with pdfMake' }
Style Libraries
The reusable style can be used, across the PDF document, using styles property.
- styles: {
- 'lineSpacing': {
- margin: [0, 0, 0, 6]
- },
- 'doublelineSpacing': {
- margin: [0, 0, 0, 12]
- },
- 'headingColor':
- {
- color: '#999966'
- },
- tableHeader: {
- bold: true,
- fontSize: 13,
- color: '#669999'
- }
- }
Header
- header: function() {
-
- return {
- columns: [
- {
- text:'Csharp' ,
- width: 200,
- margin: [50, 20, 5, 5]
- },
- {
- stack: [
- { text: 'Project Details', alignment: 'right', fontSize: 12, margin: [0, 30, 50, 0] }
- ]
- }
- ]
- }
- },
In this example, the header is included inside the function. If there are multiple pages, the header is moving on, it will not happen within the function.
Footer
- footer: function (currentPage, pageCount) {
- return {
- stack: [{ canvas: [{ type: 'line', x1: 0, y1: 5, x2: 595, y2: 5, lineWidth: 1, lineColor: '#ffff00', style: ['lineSpacing'] }] },
- { text: '', margin: [0, 0, 0, 5] },
- {
- columns: [
- {},
- { text: currentPage.toString(), alignment: 'center' },
- { text: moment(new Date()).format("DD-MMM-YYYY"), alignment: 'right', margin: [0, 0, 20, 0] }
- ]
- }]
-
- };
- },
Table
- return [
- { text: 'PDF Print Test', fontSize: 20, bold: false, alignment: 'center', style: ['lineSpacing', 'headingColor'] },
- { canvas: [{ type: 'line', x1: 0, y1: 5, x2: 595 - 2 * 40, y2: 5, lineWidth: 1, lineColor: '#990033', style: ['lineSpacing'] }] },
- {text:'',style:['doublelineSpacing']},
- {
- table: {
- widths: ['auto', 'auto', 'auto', 'auto'],
- headerRows: 1,
- // keepWithHeaderRows: 1,
- body: [
- ['Project', { text: 'Technology', style: 'tableHeader' },'Language','Database'],
- ['Intranet', 'Microsoft', { text: 'Sharepoint', colSpan: 2 }, {}],
- ['Online Jobs', 'Microsoft','Asp.Net','SQL Server']
-
- ]
- }, layout: getLayout()
- }
-
- ];
Download PDF
- var date = new Date();
- date = moment(date).format('DD_MMM_YYYY_HH_mm_ss');
- pdfMake.createPdf(docDefinition).download('PDF_' + date + '.pdf');
-
- //pdfMake.createPdf(docDefinition).open(); //to open pdf in new window
References
http://pdfmake.org/#/gettingstarted