### Install and Run Dev Playground Source: https://github.com/bpampuch/pdfmake/blob/master/dev-playground/README.md Navigate to the dev-playground directory, install dependencies, and start the server using nodemon for live development. Ensure nodemon is installed globally. ```bash cd dev-playground npm install # or: yarn npm install -g nodemon cd .. nodemon ./dev-playground/server.js ``` -------------------------------- ### Install and Configure pdfmake Source: https://context7.com/bpampuch/pdfmake/llms.txt Initializes the library, registers fonts, and sets security policies for URL and local file access. ```javascript // Install: npm install pdfmake const pdfmake = require('pdfmake'); // Add fonts (required before creating PDFs) const Roboto = require('pdfmake/build/fonts/Roboto'); pdfmake.addFonts(Roboto); // Or define fonts manually pdfmake.addFonts({ Roboto: { normal: 'path/to/Roboto-Regular.ttf', bold: 'path/to/Roboto-Medium.ttf', italics: 'path/to/Roboto-Italic.ttf', bolditalics: 'path/to/Roboto-MediumItalic.ttf' } }); // Set security policies (recommended for server-side) pdfmake.setUrlAccessPolicy((url) => { return url.startsWith('https://'); }); pdfmake.setLocalAccessPolicy((path) => { return path.startsWith('fonts/'); }); ``` -------------------------------- ### Initialize PlaygroundController Source: https://github.com/bpampuch/pdfmake/blob/master/dev-playground/public/index.html Sets up the scope, http service, Ace editor, and loads initial examples. It also handles loading previously saved document definitions from local storage. ```javascript function PlaygroundController($scope, $http) { $scope.examples = []; var editor = ace.edit('editor'); setupEditor(editor); var names = ['basics', 'styles1', 'styles2', 'styles3', 'columns', 'tables', 'lists', 'margin', 'images', 'svgs', 'attachments']; var i = 0; ['basics', 'named-styles', 'inline-styling', 'style-overrides', 'columns', 'tables', 'lists', 'margins', 'images', 'svgs', 'attachments'].forEach(function (example) { $scope.examples.push({ name: names[i++], activate: function () { $http.get('samples/' + example).success(function (data) { editor.getSession().setValue('// playground requires you to assign document definition to a variable called dd\n\nvar dd = {\n' + data.replace(/(\r?)\n/g, '\n').replace(/(^)/gm, '\t') + '\n}'); }); } }); }); var old = localStorage.pdfMakeDD; if (!old) { $scope.examples[0].activate(); } else { editor.getSession().setValue(old); } var timer; function setupEditor() { var lastGen, lastChanged; editor.setTheme('ace/theme/monokai'); editor.getSession().setMode('ace/mode/javascript'); editor.getSession().on('change', function (e) { if (timer) { clearTimeout(timer); } lastChanged = new Date(); localStorage.pdfMakeDD = editor.getSession().getValue(); timer = setTimeout(function () { if (!lastGen || lastGen < lastChanged) { generate(); }; }, 300); }); function generate() { lastGen = new Date(); var content = editor.getSession().getValue(); $http.post('/pdf', { content: content }). success(function (data, status, headers, config) { document.getElementById('pdfV').src = data; }). error(function (data, status, headers, config) { console.log('ERROR', data); }); } } }; ``` -------------------------------- ### Create Lists with pdfmake Source: https://context7.com/bpampuch/pdfmake/llms.txt Shows how to create unordered and ordered lists with various marker types, colors, and nesting. Supports custom start values and separators for ordered lists. ```javascript const docDefinition = { content: [ { text: 'Unordered List', style: 'header' }, { ul: ['item 1', 'item 2', 'item 3'] }, '\n', { text: 'Ordered List with Roman numerals', style: 'header' }, { type: 'upper-roman', ol: ['First item', 'Second item', 'Third item'] }, '\n', { text: 'Colored list with custom markers', style: 'header' }, { color: 'blue', markerColor: 'red', ul: [ 'item 1', 'item 2', { text: 'item 3 with custom color', markerColor: 'lime' } ] }, '\n', { text: 'Nested lists', style: 'header' }, { ol: [ 'First level item 1', { ul: [ 'Nested bullet 1', 'Nested bullet 2', { ol: [ 'Deep nested 1', 'Deep nested 2' ] } ] }, 'First level item 2' ] }, '\n', { text: 'Custom ordered list', style: 'header' }, { start: 50, separator: ['(', ')'], type: 'lower-alpha', ol: ['Starting at 50', 'Next item', 'Another item'] } ], styles: { header: { bold: true, fontSize: 14, margin: [0, 10, 0, 5] } } }; pdfmake.createPdf(docDefinition).write('lists.pdf'); ``` -------------------------------- ### Build pdfmake from source Source: https://github.com/bpampuch/pdfmake/blob/master/README.md Commands to clone the repository and build the project using package managers. ```bash git clone https://github.com/bpampuch/pdfmake.git cd pdfmake npm install npm run build ``` ```bash git clone https://github.com/bpampuch/pdfmake.git cd pdfmake yarn yarn run build ``` -------------------------------- ### Create Tables with pdfmake Source: https://context7.com/bpampuch/pdfmake/llms.txt Demonstrates creating simple and complex tables with custom column widths, row/column spans, and styling. Includes automatic header repetition and layout customization. ```javascript const docDefinition = { content: [ { text: 'Simple Table', style: 'header' }, { table: { body: [ ['Column 1', 'Column 2', 'Column 3'], ['Row 1 data', 'Data here', 'More data'] ] } }, '\n', { text: 'Table with column widths and styling', style: 'header' }, { table: { headerRows: 1, widths: [100, '*', 200, '*'], // Fixed, star, fixed, star heights: [20, 50], body: [ [ { text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, { text: 'Header 3', style: 'tableHeader' }, { text: 'Header 4', style: 'tableHeader' } ], ['Fixed 100', 'Star-sized', 'Fixed 200', 'Star-sized'], [ { rowSpan: 2, text: 'Row span 2' }, { colSpan: 2, text: 'Column span 2' }, {}, 'Normal cell' ], ['', 'Cell 2', 'Cell 3', 'Cell 4'] ] }, layout: { hLineWidth: (i, node) => (i === 0 || i === node.table.body.length) ? 2 : 1, vLineWidth: (i, node) => (i === 0 || i === node.table.widths.length) ? 2 : 1, hLineColor: (i, node) => (i === 0 || i === node.table.body.length) ? 'black' : 'gray', vLineColor: (i, node) => (i === 0 || i === node.table.widths.length) ? 'black' : 'gray', fillColor: (rowIndex) => (rowIndex % 2 === 0) ? '#CCCCCC' : null } } ], styles: { header: { fontSize: 16, bold: true, margin: [0, 10, 0, 5] }, tableHeader: { bold: true, fontSize: 13, color: 'white', fillColor: '#2196F3' } } }; pdfmake.createPdf(docDefinition).write('tables.pdf'); ``` -------------------------------- ### Create Columns with pdfmake Source: https://context7.com/bpampuch/pdfmake/llms.txt Illustrates creating multi-column layouts with equal, mixed, and snaking column widths. Includes options for column gaps and alignment. ```javascript const docDefinition = { content: [ 'Two equal columns:\n\n', { alignment: 'justify', columns: [ { text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore.' }, { text: 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.' } ], columnGap: 20 }, '\n\nMixed width columns:\n\n', { columns: [ { width: 'auto', text: 'Auto width' }, { width: '*', text: 'This star-sized column takes remaining space' }, { width: 100, text: 'Fixed 100pt' } ] }, '\n\nSnaking columns (newspaper-style flow):\n\n', { columns: [ { text: 'Long text that will flow from column to column...'.repeat(20), width: '*' }, { text: '', width: '*' } ], columnGap: 30, snakingColumns: true // Content flows column to column } ], defaultStyle: { columnGap: 20 } }; pdfmake.createPdf(docDefinition).write('columns.pdf'); ``` -------------------------------- ### Create and Export PDF Documents Source: https://context7.com/bpampuch/pdfmake/llms.txt Demonstrates creating a document definition and exporting it via file write, buffer, download, open, or print methods. ```javascript const pdfmake = require('pdfmake'); const Roboto = require('pdfmake/build/fonts/Roboto'); pdfmake.addFonts(Roboto); const docDefinition = { content: [ 'First paragraph', 'Another paragraph with longer text to demonstrate line wrapping capabilities' ] }; const pdf = pdfmake.createPdf(docDefinition); // Write to file (Node.js) pdf.write('output.pdf').then(() => { console.log('PDF created successfully'); }).catch(err => { console.error('Error creating PDF:', err); }); // Get as buffer (Node.js) pdf.getBuffer().then(buffer => { // Use buffer for email attachments, storage, etc. }); // Download in browser pdf.download('document.pdf'); // Open in new browser tab pdf.open(); // Print directly pdf.print(); ``` -------------------------------- ### createPdf(docDefinition, options) Source: https://context7.com/bpampuch/pdfmake/llms.txt Creates a PDF document instance from a provided document definition object, returning a promise-based object for output operations. ```APIDOC ## createPdf(docDefinition, options) ### Description Creates a PDF document from a document definition object. Returns a promise-based document object with methods for writing, downloading, or printing the PDF. ### Parameters - **docDefinition** (Object) - Required - A JSON object describing the structure and content of the PDF. - **options** (Object) - Optional - Configuration options for the PDF generation. ### Request Example { "content": [ "First paragraph", "Another paragraph" ] } ### Response #### Success Response (Promise) - **write(filename)** (Function) - Writes the PDF to a file (Node.js). - **getBuffer()** (Function) - Returns the PDF as a buffer (Node.js). - **download(filename)** (Function) - Triggers a browser download. - **open()** (Function) - Opens the PDF in a new browser tab. - **print()** (Function) - Triggers the browser print dialog. ``` -------------------------------- ### Create Multi-Section Documents Source: https://context7.com/bpampuch/pdfmake/llms.txt Define documents with varying page sizes, orientations, and headers per section. Use 'inherit' to propagate settings from previous sections. ```javascript const docDefinition = { header: () => 'Default Header', footer: () => 'Default Footer', watermark: 'Default Watermark', content: [ { section: [ 'SECTION 1', 'Default page settings from document level.' ] }, { header: (currentPage, pageCount) => `Section 2: ${currentPage}/${pageCount}`, footer: (currentPage, pageCount) => `Footer: ${currentPage}/${pageCount}`, watermark: 'SECTION 2', pageOrientation: 'landscape', section: [ 'SECTION 2', 'Landscape page with custom header/footer.' ] }, { header: null, footer: null, watermark: null, pageSize: 'A5', pageOrientation: 'portrait', section: [ 'SECTION 3', 'A5 page with no header/footer/watermark.' ] }, { pageSize: 'inherit', pageOrientation: 'inherit', pageMargins: 'inherit', watermark: 'inherit', section: [ 'SECTION 4', 'Inherits settings from previous section.' ] } ] }; pdfmake.createPdf(docDefinition).write('sections.pdf'); ``` -------------------------------- ### Configure Security Access Policies Source: https://context7.com/bpampuch/pdfmake/llms.txt Restrict external URL and local file system access to mitigate security risks. Requires setting policies before document generation. ```javascript const pdfmake = require('pdfmake'); const Roboto = require('pdfmake/build/fonts/Roboto'); pdfmake.addFonts(Roboto); // Restrict external URL access pdfmake.setUrlAccessPolicy((url) => { // Only allow HTTPS URLs from trusted domains const allowedDomains = ['example.com', 'cdn.example.com']; try { const urlObj = new URL(url); return urlObj.protocol === 'https:' && allowedDomains.some(domain => urlObj.hostname.endsWith(domain)); } catch { return false; } }); // Restrict local file system access pdfmake.setLocalAccessPolicy((path) => { // Only allow access to specific directories return path.startsWith('fonts/') || path.startsWith('images/'); }); const docDefinition = { content: [ 'Secure PDF with restricted resource access', { image: 'images/logo.png', width: 100 } // Allowed ] }; pdfmake.createPdf(docDefinition).write('secure.pdf'); ``` -------------------------------- ### Include Images in PDF Source: https://context7.com/bpampuch/pdfmake/llms.txt Demonstrates how to embed images from local paths, URLs, or data URLs. Supports various sizing and fitting options like width, height, fit, and cover modes. Images can also have opacity and be linked. ```javascript const docDefinition = { content: [ 'Image at original size:', { image: 'path/to/image.jpg' }, '\n', 'Image with width (proportional scaling):', { image: 'path/to/image.jpg', width: 150 }, '\n', 'Image stretched to specific dimensions:', { image: 'path/to/image.jpg', width: 150, height: 100 }, '\n', 'Image fit inside rectangle (maintains aspect ratio):', { image: 'path/to/image.jpg', fit: [200, 100] }, '\n', 'Image cover (crops to fill rectangle):', { image: 'path/to/image.jpg', cover: { width: 150, height: 150, valign: 'center', align: 'center' } }, '\n', 'Image with opacity:', { image: 'path/to/image.jpg', width: 150, opacity: 0.5 }, '\n', 'Image from URL:', { image: 'snow', width: 200 }, '\n', 'Image with link:', { image: 'path/to/image.jpg', width: 100, link: 'https://example.com' } ], images: { snow: 'https://picsum.photos/200/300', logo: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA...' } }; pdfmake.createPdf(docDefinition).write('images.pdf'); ``` -------------------------------- ### Add Headers, Footers, and Watermarks Source: https://context7.com/bpampuch/pdfmake/llms.txt Allows dynamic content for headers and footers, including page numbers and total page counts. Also supports adding background elements and watermarks to the document. Configuration includes page size, orientation, and margins. ```javascript const docDefinition = { header: (currentPage, pageCount) => ({ text: `Page ${currentPage} of ${pageCount}`, alignment: 'center', margin: [0, 10, 0, 0] }), footer: (currentPage, pageCount) => ({ columns: [ { text: 'Company Name', alignment: 'left' }, { text: `${currentPage}/${pageCount}`, alignment: 'right' } ], margin: [40, 0] }), background: (currentPage) => { if (currentPage === 1) { return { text: 'DRAFT', color: 'gray', opacity: 0.1, fontSize: 100, alignment: 'center', margin: [0, 300] }; } return null; }, watermark: { text: 'CONFIDENTIAL', color: 'blue', opacity: 0.2, bold: true, italics: false }, content: [ 'First page content...', { text: 'Second page', pageBreak: 'before' }, 'Second page content...' ], pageSize: 'A4', pageOrientation: 'portrait', pageMargins: [40, 60, 40, 60] }; pdfmake.createPdf(docDefinition).write('headers-footers.pdf'); ``` -------------------------------- ### Add Links and Bookmarks in PDF Source: https://context7.com/bpampuch/pdfmake/llms.txt Enables the creation of external hyperlinks, internal page navigation, and destination bookmarks within a PDF document. Text can be styled to indicate links, and specific sections can be marked as destinations. ```javascript const docDefinition = { content: [ { text: [ 'Visit ', { text: 'pdfmake website', link: 'https://pdfmake.org', decoration: 'underline', color: 'blue' }, ' for documentation.' ] }, '\n', { text: 'Go to page 2', linkToPage: 2, decoration: 'underline' }, '\n', { text: 'Jump to Section 2', linkToDestination: 'section2', decoration: 'underline' }, '\n', // Image with link { image: 'path/to/image.jpg', width: 100, link: 'https://example.com' }, // Page 2 content { text: 'Page 2 Header', fontSize: 18, bold: true, pageBreak: 'before' }, 'Content on page 2...', '\n\n', // Bookmark destination { text: 'Section 2', id: 'section2', fontSize: 18, bold: true }, 'This is the section 2 content that can be linked to.', // Outlines/Bookmarks { text: 'Chapter 1', style: 'header', outline: true, outlineExpanded: true } ] }; pdfmake.createPdf(docDefinition).write('links.pdf'); ``` -------------------------------- ### Apply Text Styling and Named Styles Source: https://context7.com/bpampuch/pdfmake/llms.txt Defines reusable styles and applies inline formatting to document content. ```javascript const docDefinition = { content: [ { text: 'This is a header', style: 'header' }, 'Normal paragraph text.\n\n', { text: 'Subheader text', style: 'subheader' }, 'More content here.\n\n', { text: 'This uses multiple styles', style: ['quote', 'small'] // Styles applied in order }, { text: [ 'Inline styling: ', { text: 'bold text', bold: true }, ', ', { text: 'italic text', italics: true }, ', ', { text: 'colored text', color: 'blue' }, ', ', { text: 'with background', background: 'yellow' } ] } ], styles: { header: { fontSize: 18, bold: true, margin: [0, 0, 0, 10] }, subheader: { fontSize: 15, bold: true }, quote: { italics: true }, small: { fontSize: 8 } }, defaultStyle: { fontSize: 12, font: 'Roboto' } }; pdfmake.createPdf(docDefinition).write('styled.pdf'); ``` -------------------------------- ### Generate Table of Contents in PDF Source: https://context7.com/bpampuch/pdfmake/llms.txt Automatically generates a table of contents from elements marked with 'tocItem: true'. Allows customization of the TOC title, number styling, text margins, and sorting by page or title. Content elements can be styled and marked for inclusion. ```javascript const docDefinition = { content: [ { text: 'Document with Table of Contents', style: 'title' }, '\n', { toc: { title: { text: 'TABLE OF CONTENTS', style: 'tocTitle' }, numberStyle: { bold: true }, textMargin: [0, 0, 0, 0], sortBy: 'page' // 'page' or 'title' } }, // Content with tocItem markers { text: 'Chapter 1: Introduction', style: 'header', tocItem: true, tocStyle: { italics: true }, tocMargin: [0, 10, 0, 0], pageBreak: 'before' }, 'Introduction content...\n\n', { text: 'Chapter 2: Getting Started', style: 'header', tocItem: true, pageBreak: 'before' }, 'Getting started content...\n\n', { text: 'Chapter 3: Advanced Topics', style: 'header', tocItem: true, pageBreak: 'before' }, 'Advanced topics content...' ], styles: { title: { fontSize: 22, bold: true, alignment: 'center' }, tocTitle: { fontSize: 16, bold: true, margin: [0, 0, 0, 10] }, header: { fontSize: 18, bold: true } } }; pdfmake.createPdf(docDefinition).write('toc.pdf'); ``` -------------------------------- ### Embed SVG Vector Graphics Source: https://context7.com/bpampuch/pdfmake/llms.txt Include SVG strings directly in the document content. Use 'width' or 'fit' properties to control scaling and dimensions. ```javascript const docDefinition = { content: [ { text: 'SVG Graphics', style: 'header' }, '\n', { svg: 'SVG Rectangle' }, '\n', { svg: 'Circle', width: 150 // Scale SVG }, '\n', { svg: '', fit: [100, 100] } ], styles: { header: { fontSize: 18, bold: true } } }; pdfmake.createPdf(docDefinition).write('svg.pdf'); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.