### Asynchronous Open PDF Example Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods This example demonstrates opening a PDF in a new window asynchronously after an HTTP POST request. ```javascript $scope.generatePdf = function() { // create the window before the callback var win = window.open('', '_blank'); $http.post('/someUrl', data).then(function(response) { // pass the "win" argument pdfMake.createPdf(docDefinition).open(win); }); }; ``` -------------------------------- ### Install pdfmake via npm Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side Use npm to install the pdfmake package for client-side projects. ```bash npm install pdfmake ``` -------------------------------- ### Asynchronous Print PDF Example Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods This example shows how to print a PDF asynchronously after an HTTP POST request, passing the window object. ```javascript $scope.generatePdf = function() { // create the window before the callback var win = window.open('', '_blank'); $http.post('/someUrl', data).then(function(response) { // pass the "win" argument pdfMake.createPdf(docDefinition).print(win); }); }; ``` -------------------------------- ### Set Local File Access Policy - Basic Example Source: https://pdfmake.github.io/docs/0.3/getting-started/server-side/methods Defines a custom security policy for local files, restricting access to paths that start with 'fonts/'. ```javascript pdfmake.setLocalAccessPolicy((path) => { // check allowed local file path return path.startsWith("fonts/"); }); ``` -------------------------------- ### Link Syntax Examples Source: https://pdfmake.github.io/docs/0.3/document-definition-object/links Demonstrates various ways to define links within the document definition object. ```APIDOC ## Link Syntax To add external or internal links, use the following syntax: ```javascript { text: 'google', link: 'http://google.com' } { text: 'Go to page 2', linkToPage: 2 } { text: 'Go to Header', linkToDestination: 'header' }, { text: 'Header content', id: 'header' } ``` Or link to local computer file: ```javascript var dd = { content: [ { text: 'link', link: 'file:///c:/testFile.txt' } ] }; ``` ### Properties * `link` (string) - URL to external site * `linkToPage` (number) - link to page number * `linkToDestination` (string) - link to document destination ``` -------------------------------- ### Set URL Access Policy - Basic Example Source: https://pdfmake.github.io/docs/0.3/getting-started/server-side/methods Defines a custom security policy for external URLs, restricting access to URLs starting with a specific domain. ```javascript pdfmake.setUrlAccessPolicy((url) => { // check allowed domain return url.startsWith("https://example.com/"); }); ``` -------------------------------- ### Composer Configuration for pdfmake Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side Example composer.json for integrating pdfmake via asset-packagist.org. ```json { "require": { "npm-asset/pdfmake": "^0.3.0" }, "replace": { "npm-asset/pdfkit": "*", "npm-asset/linebreak": "*", "npm-asset/svg-to-pdfkit": "*", "npm-asset/xmldoc": "*" }, "repositories": [ { "type": "composer", "url": "https://asset-packagist.org" } ] } ``` -------------------------------- ### Creating Outlines/Bookmarks Source: https://pdfmake.github.io/docs/0.3/document-definition-object/outlines This example demonstrates how to add basic and custom-text bookmarks, as well as structured, expandable bookmarks with parent-child relationships using the 'outline' property and its associated options. ```APIDOC ## Outlines / Bookmarks PDF Outlines (also called Bookmarks) are a hierarchical navigation structure embedded in a PDF document that allows users to quickly jump to specific pages. They function as an interactive table of contents, typically displayed in the PDF viewer’s navigation panel. ### Properties * `outline: boolean` - set to `true` for add to bookmarks * `outlineText: string` (optional) - set custom bookmark text, otherwise text from node * `outlineExpanded: boolean` (optional) - set to `true` for expanded/opened bookmark * `outlineParentId: string` (optional) - parent bookmark `id` ### Example ```javascript var docDefinition = { content: [ { text: 'First header in bookmarks', outline: true, }, { text: 'Second header with custom bookmark', outline: true, outlineText: 'Custom bookmark text', }, { text: 'Structured bookmarks', id: 'structured-bookmarks', outline: true, outlineExpanded: true }, { text: 'First subheader', outline: true, outlineParentId: 'structured-bookmarks' }, { text: 'Second subheader', outline: true, outlineParentId: 'structured-bookmarks' }, { text: 'Third subheader', outline: true, outlineParentId: 'structured-bookmarks', id: 'third-subheader' } ] }; ``` ``` -------------------------------- ### Server-side pdfmake Usage Example Source: https://pdfmake.github.io/docs/0.3/getting-started/server-side Demonstrates how to define fonts, require the pdfmake module, and create a PDF document with custom fonts on the server. Ensure font files are correctly path-ed. ```javascript // Define font files var fonts = { Roboto: { normal: 'fonts/Roboto-Regular.ttf', bold: 'fonts/Roboto-Medium.ttf', italics: 'fonts/Roboto-Italic.ttf', bolditalics: 'fonts/Roboto-MediumItalic.ttf' } }; var pdfmake = require('pdfmake'); pdfmake.addFonts(fonts); var docDefinition = { // ... }; var options = { // ... } var pdf = pdfmake.createPdf(docDefinition); pdf.write('document.pdf').then(() => { // success event }, err => { // error event console.error(err); }); ``` -------------------------------- ### Build pdfmake with Standard Fonts (Client-Side) Source: https://pdfmake.github.io/docs/0.3/fonts/standard-14-fonts Instructions for cloning the pdfmake repository, installing dependencies, and building the library with standard fonts included for client-side use. This is necessary because including standard fonts increases the library size. ```bash git clone https://github.com/bpampuch/pdfmake.git cd pdfmake npm install gulp buildWithStandardFonts ``` -------------------------------- ### Static Headers and Footers in pdfmake Source: https://pdfmake.github.io/docs/0.3/document-definition-object/headers-footers Use simple strings or structured content for static headers and footers. The footer example demonstrates a basic column layout. ```javascript var docDefinition = { header: 'simple text', footer: { columns: [ 'Left part', { text: 'Right part', alignment: 'right' } ] }, content: (...) }; ``` -------------------------------- ### Get PDF as Buffer Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Generates the PDF document and returns it as a buffer. ```APIDOC ## .getBuffer() ### Description Generates the PDF document and returns it as a buffer. This is useful for server-side processing or when working with binary data. ### Method `.getBuffer()` ### Response #### Success Response - `buffer` (Buffer) - The PDF document as a buffer. ### Request Example ```javascript pdfMake.createPdf(docDefinition).getBuffer().then((buffer) => { // Use the buffer }, err => { console.error(err); }); ``` ``` -------------------------------- ### Basic Table of Contents Source: https://pdfmake.github.io/docs/0.3/document-definition-object/toc This example demonstrates the simplest way to add a table of contents to your document. It includes a title and marks content items as belonging to the ToC. ```APIDOC ## Basic Table of Contents ### Description This example demonstrates the simplest way to add a table of contents to your document. It includes a title and marks content items as belonging to the ToC. ### Method Not applicable (Document Definition Object configuration) ### Endpoint Not applicable (Document Definition Object configuration) ### Parameters #### ToC Properties - **title** (string | text node) - Optional - Title of the ToC. #### Node Properties - **tocItem** (boolean | string) - Marks an item to be included in the table of contents. ### Request Example ```javascript var docDefinition = { content: [ { toc: { title: {text: 'INDEX', style: 'header'} } }, { text: 'This is a header', style: 'header', tocItem: true } ] } ``` ### Response Not applicable (This is a configuration object, not an API endpoint.) ``` -------------------------------- ### Get PDF as Stream Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Generates the PDF document and returns it as a stream. ```APIDOC ## .getStream() ### Description Generates the PDF document and returns it as a stream. Streams are efficient for handling large documents. ### Method `.getStream()` ### Response #### Success Response - `stream` (Stream) - The PDF document as a stream. ### Request Example ```javascript pdfMake.createPdf(docDefinition).getStream().then((stream) => { // Use the stream }, err => { console.error(err); }); ``` ``` -------------------------------- ### Define and Use Standard Fonts (Client-Side) Source: https://pdfmake.github.io/docs/0.3/fonts/standard-14-fonts Configure standard fonts for client-side pdfmake usage by assigning them to the `pdfMake.fonts` object. This example demonstrates setting up Courier, Helvetica, and Times New Roman fonts. ```javascript pdfMake.fonts = { Courier: { normal: 'Courier', bold: 'Courier-Bold', italics: 'Courier-Oblique', bolditalics: 'Courier-BoldOblique' }, Helvetica: { normal: 'Helvetica', bold: 'Helvetica-Bold', italics: 'Helvetica-Oblique', bolditalics: 'Helvetica-BoldOblique' }, Times: { normal: 'Times-Roman', bold: 'Times-Bold', italics: 'Times-Italic', bolditalics: 'Times-BoldItalic' }, Symbol: { normal: 'Symbol' }, ZapfDingbats: { normal: 'ZapfDingbats' } }; var docDefinition = { content: [ 'First paragraph', 'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines', ], defaultStyle: { font: 'Helvetica' } }; pdfMake.createPdf(docDefinition).download('document.pdf'); ``` -------------------------------- ### Multiple Tables of Contents Source: https://pdfmake.github.io/docs/0.3/document-definition-object/toc This example illustrates how to define and use multiple tables of contents within a single document, with content items potentially belonging to more than one ToC. ```APIDOC ## Multiple Tables of Contents ### Description This example illustrates how to define and use multiple tables of contents within a single document, with content items potentially belonging to more than one ToC. ### Method Not applicable (Document Definition Object configuration) ### Endpoint Not applicable (Document Definition Object configuration) ### Parameters #### ToC Properties - **id** (string) - Optional - Used to identify a specific ToC when multiple are present. - **title** (string | text node) - Optional - Title of the ToC. #### Node Properties - **tocItem** (boolean | string | array) - Marks an item to be included in the table of contents. Can be a boolean, the ID of a target ToC, or an array of ToC IDs. ### Request Example ```javascript var docDefinition = { content: [ { toc: { id: 'mainToc', title: {text: 'INDEX', style: 'header'} }, toc: { id: 'subToc', title: {text: 'SUB INDEX', style: 'header'} } }, { text: 'This is a header', style: 'header', tocItem: ['mainToc', 'subToc'] } ] } ``` ### Response Not applicable (This is a configuration object, not an API endpoint.) ``` -------------------------------- ### Define and Use Standard Fonts (Server-Side) Source: https://pdfmake.github.io/docs/0.3/fonts/standard-14-fonts Configure standard fonts for server-side pdfmake usage by defining them in a fonts object and adding them using `pdfmake.addFonts`. This example shows how to set up Courier, Helvetica, and Times New Roman fonts. ```javascript var fonts = { Courier: { normal: 'Courier', bold: 'Courier-Bold', italics: 'Courier-Oblique', bolditalics: 'Courier-BoldOblique' }, Helvetica: { normal: 'Helvetica', bold: 'Helvetica-Bold', italics: 'Helvetica-Oblique', bolditalics: 'Helvetica-BoldOblique' }, Times: { normal: 'Times-Roman', bold: 'Times-Bold', italics: 'Times-Italic', bolditalics: 'Times-BoldItalic' }, Symbol: { normal: 'Symbol' }, ZapfDingbats: { normal: 'ZapfDingbats' } }; var pdfmake = require('pdfmake'); pdfmake.addFonts(fonts); var docDefinition = { content: [ 'First paragraph', 'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines', ], defaultStyle: { font: 'Helvetica' } }; var pdf = pdfmake.createPdf(docDefinition); pdf.write('pdfs/basics.pdf').then(() => { // success event }, err => { console.error(err); }); ``` -------------------------------- ### Get PDF as Blob Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Generates the PDF document and returns it as a Blob object. ```APIDOC ## .getBlob() ### Description Generates the PDF document and returns it as a Blob object, which can be used for further processing or uploading. ### Method `.getBlob()` ### Response #### Success Response - `blob` (Blob) - The PDF document as a Blob object. ### Request Example ```javascript pdfMake.createPdf(docDefinition).getBlob().then((blob) => { // Use the blob object }, err => { console.error(err); }); ``` ``` -------------------------------- ### Get PDF as Stream Source: https://pdfmake.github.io/docs/0.3/getting-started/server-side/methods Retrieves the generated PDF document as a stream. Returns a promise that resolves with the stream or rejects on error. ```javascript pdfmake.createPdf(docDefinition).getStream().then((stream) => { // ... }, err => { console.error(err); }); ``` -------------------------------- ### Get PDF as Buffer Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Retrieve the PDF document as a buffer using the `getBuffer()` method. This is often used in Node.js environments or for binary data processing. ```javascript pdfMake.createPdf(docDefinition).getBuffer().then((buffer) => { // ... }, err => { console.error(err); }); ``` -------------------------------- ### Get PDF as Data URL Source: https://pdfmake.github.io/docs/0.3/getting-started/server-side/methods Retrieves the generated PDF document as a Data URL. Returns a promise that resolves with the Data URL or rejects on error. ```javascript pdfmake.createPdf(docDefinition).getDataUrl().then((dataUrl) => { // ... }, err => { console.error(err); }); ``` -------------------------------- ### Using Multiple Tables of Contents Source: https://pdfmake.github.io/docs/0.3/document-definition-object/toc This example demonstrates how to define and use multiple tables of contents within a single document. The 'tocItem' property can accept an array of IDs to associate content with multiple ToCs. ```javascript var docDefinition = { content: [ { toc: { id: 'mainToc', title: {text: 'INDEX', style: 'header'} }, toc: { id: 'subToc', title: {text: 'SUB INDEX', style: 'header'} } }, { text: 'This is a header', style: 'header', tocItem: ['mainToc', 'subToc'] } ] } ``` -------------------------------- ### Table of Contents with ID Targeting Source: https://pdfmake.github.io/docs/0.3/document-definition-object/toc This example shows how to use the `id` property to associate specific content items with a particular table of contents, useful when you have multiple ToCs. ```APIDOC ## Table of Contents with ID Targeting ### Description This example shows how to use the `id` property to associate specific content items with a particular table of contents, useful when you have multiple ToCs. ### Method Not applicable (Document Definition Object configuration) ### Endpoint Not applicable (Document Definition Object configuration) ### Parameters #### ToC Properties - **id** (string) - Optional - Used to identify a specific ToC when multiple are present. - **title** (string | text node) - Optional - Title of the ToC. #### Node Properties - **tocItem** (boolean | string) - Marks an item to be included in the table of contents. Can be a boolean or the ID of the target ToC. ### Request Example ```javascript var docDefinition = { content: [ { toc: { id: 'mainToc', title: {text: 'INDEX', style: 'header'} } }, { text: 'This is a header', style: 'header', tocItem: 'mainToc' } ] } ``` ### Response Not applicable (This is a configuration object, not an API endpoint.) ``` -------------------------------- ### Dynamic Page Break Control with pageBreakBefore Function Source: https://pdfmake.github.io/docs/0.3/document-definition-object/page Implement custom page break logic using the `pageBreakBefore` function. This example demonstrates a 'no orphan child' rule by checking the `headlineLevel` and available space on the current page. ```javascript var dd = { content: [ {text: '1 Headline', headlineLevel: 1}, 'Some long text of variable length ...', {text: '2 Headline', headlineLevel: 1}, 'Some long text of variable length ...', {text: '3 Headline', headlineLevel: 1}, 'Some long text of variable length ...', ], pageBreakBefore: function(currentNode, nodeContainer) { // nodeContainer.getFollowingNodesOnPage(); // nodeContainer.getNodesOnNextPage(); // nodeContainer.getPreviousNodesOnPage(); return currentNode.headlineLevel === 1 && nodeContainer.getFollowingNodesOnPage().length === 0; } } ``` -------------------------------- ### Import pdfmake and add VFS with ES Modules Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side Import pdfmake and fonts separately, then add the virtual file system using import. ```javascript import pdfMake from "pdfmake/build/pdfmake"; import pdfFonts from "pdfmake/build/vfs_fonts"; pdfMake.addVirtualFileSystem(pdfFonts); ``` -------------------------------- ### Server-Side PDF Creation with Custom Layout Source: https://pdfmake.github.io/docs/0.3/document-definition-object/tables Demonstrates how to define and apply custom table layouts on the server-side using pdfmake. The PDF is then written to disk. ```javascript var pdfmake = require('pdfmake'); pdfmake.addFonts(fonts); // Declaring your layout var myTableLayouts = { exampleLayout: { /* Your layout here. */ } }; // Building the PDF var pdf = pdfmake.createPdf(docDefinition); // Writing it to disk pdf.write('document.pdf').then(() => { // success event }, err => { // error event console.error(err); }); ``` -------------------------------- ### Configure PDF/A Document Source: https://pdfmake.github.io/docs/0.3/document-definition-object/pdfa Use this configuration to create a PDF/A-compliant document. Ensure the 'version' property is set to 1.4 or above for PDF/A support. The 'subset' property specifies the PDF/A standard to adhere to. ```javascript var docDefinition = { version: '1.5', subset: 'PDF/A-3a', tagged: true, displayTitle: true, info: { title: 'Awesome PDF document from pdfmake' }, content: [ 'PDF/A document for archive' ] }; ``` -------------------------------- ### Get PDF as Base64 Data Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Generates the PDF document and returns its data as a Base64 encoded string. ```APIDOC ## .getBase64() ### Description Generates the PDF document and returns its data as a Base64 encoded string. ### Method `.getBase64()` ### Response #### Success Response - `data` (string) - The PDF document as a Base64 string. ### Request Example ```javascript pdfMake.createPdf(docDefinition).getBase64().then((data) => { alert(data); }, err => { console.error(err); }); ``` ``` -------------------------------- ### Get PDF as URL Data Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Generates the PDF document and returns its data as a URL, which can be used for embedding or displaying. ```APIDOC ## .getDataUrl() ### Description Generates the PDF document and returns its data as a URL string. This can be used to embed the PDF in an iframe or other elements. ### Method `.getDataUrl()` ### Response #### Success Response - `dataUrl` (string) - The PDF document as a data URL. ### Request Example ```javascript pdfMake.createPdf(docDefinition).getDataUrl().then((dataUrl) => { const iframe = document.createElement('iframe'); iframe.src = dataUrl; document.body.appendChild(iframe); }, err => { console.error(err); }); ``` ``` -------------------------------- ### Link to Local Computer File Source: https://pdfmake.github.io/docs/0.3/document-definition-object/links You can link to local files on the computer using the 'file://' protocol within the 'link' property. Ensure the path is correctly formatted. ```javascript var dd = { content: [ { text: 'link', link: 'file:///c:/testFile.txt' } ] }; ``` -------------------------------- ### Get PDF as Stream Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods The `getStream()` method provides the PDF document as a stream, which is efficient for handling large documents or real-time processing. ```javascript pdfMake.createPdf(docDefinition).getStream().then((stream) => { // ... }, err => { console.error(err); }); ``` -------------------------------- ### Basic Text Styling in pdfmake Source: https://pdfmake.github.io/docs/0.3/document-definition-object/styling Demonstrates how to apply basic styling properties like fontSize directly to text objects or parts of a text array within the content definition. Use this for simple, one-off styling needs. ```javascript var docDefinition = { content: [ // if you don't need styles, you can use a simple string to define a paragraph 'This is a standard paragraph, using default style', // using a { text: '...' } object lets you set styling properties { text: 'This paragraph will have a bigger font', fontSize: 15 }, // if you set the value of text to an array instead of a string, you'll be able // to style any part individually { text: [ 'This paragraph is defined as an array of elements to make it possible to ', { text: 'restyle part of it and make it bigger ', fontSize: 15 }, 'than the rest.' ] } ] }; ``` -------------------------------- ### Get PDF as Blob Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods The `getBlob()` method returns a promise that resolves with the PDF document as a Blob object, which can be used for file operations or uploads. ```javascript pdfMake.createPdf(docDefinition).getBlob().then((blob) => { // ... }, err => { console.error(err); }); ``` -------------------------------- ### Require pdfmake and add VFS with CommonJS Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side Import pdfmake and fonts separately, then explicitly add the virtual file system. ```javascript var pdfMake = require('pdfmake/build/pdfmake.js'); var pdfFonts = require('pdfmake/build/vfs_fonts.js'); pdfMake.addVirtualFileSystem(pdfFonts); ``` -------------------------------- ### Open PDF in Same Window Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Use `open(window)` to display the PDF within the current browser window. ```javascript pdfMake.createPdf(docDefinition).open(window); ``` -------------------------------- ### Get PDF as Base64 Data Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Use `getBase64()` to retrieve the PDF document as a base64 encoded string. This is useful for transmitting or storing the PDF data. ```javascript pdfMake.createPdf(docDefinition).getBase64().then((data) => { alert(data); }, err => { console.error(err); }); ``` -------------------------------- ### Get PDF as Data URL Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods The `getDataUrl()` method returns a promise that resolves with the PDF document as a data URL, suitable for embedding in iframes or images. ```javascript pdfMake.createPdf(docDefinition).getDataUrl().then((dataUrl) => { const targetElement = document.querySelector('#iframeContainer'); const iframe = document.createElement('iframe'); iframe.src = dataUrl; targetElement.appendChild(iframe); }, err => { console.error(err); }); ``` -------------------------------- ### Open PDF in New Window Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Use `open()` to display the PDF in a new browser window. An optional window object can be passed for asynchronous operations. ```javascript pdfMake.createPdf(docDefinition).open(); pdfMake.createPdf(docDefinition).open(win); ``` -------------------------------- ### Reusable Style Dictionaries in pdfmake Source: https://pdfmake.github.io/docs/0.3/document-definition-object/styling Shows how to define a dictionary of reusable styles and apply them to text elements using the 'style' property. The 'extends' property allows for style inheritance. This is useful for maintaining consistent styling across a document. ```javascript var docDefinition = { content: [ { text: 'This is a header', style: 'header' }, 'No styling here, this is a standard paragraph', { text: 'Another text', style: 'anotherStyle' }, { text: 'Multiple styles applied', style: [ 'header', 'anotherStyle' ] } ], styles: { header: { fontSize: 22, bold: true }, anotherStyle: { italics: true, alignment: 'right' }, subheader: { fontSize: 15, extends: 'header' // or array of strings } } }; ``` -------------------------------- ### Open PDF in New Window Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Generates a PDF and opens it in a new browser window. An optional window object can be provided for asynchronous operations. ```APIDOC ## .open() ### Description Generates a PDF document and opens it in a new browser window. This method can accept an optional window object, particularly useful for asynchronous operations. ### Method `.open()` `.open(win)` ### Parameters #### Path Parameters - `win` (object) - Optional - The window object to open the PDF in (when an asynchronous operation). ### Request Example ```javascript // Asynchronous example const win = window.open('', '_blank'); pdfMake.createPdf(docDefinition).open(win); // Opening in the same window pdfMake.createPdf(docDefinition).open(window); ``` ``` -------------------------------- ### Get PDF as Base64 Data Source: https://pdfmake.github.io/docs/0.3/getting-started/server-side/methods Retrieves the generated PDF document as base64 encoded data. Returns a promise that resolves with the base64 data or rejects on error. ```javascript pdfmake.createPdf(docDefinition).getBase64().then((data) => { console.log(data); }, err => { console.error(err); }); ``` -------------------------------- ### Basic Stack of Paragraphs in Columns Source: https://pdfmake.github.io/docs/0.3/document-definition-object/stack Demonstrates creating a stack of paragraphs within a column using an array shortcut. This structure renders paragraphs one below another. ```javascript var docDefinition = { content: [ 'paragraph 1', 'paragraph 2', { columns: [ 'first column is a simple text', [ // second column consists of paragraphs 'paragraph A', 'paragraph B', 'these paragraphs will be rendered one below another inside the column' ] ] } ] }; ``` -------------------------------- ### QR Code Usage Source: https://pdfmake.github.io/docs/0.3/document-definition-object/qr Demonstrates the basic and advanced usage of the QR code element in pdfmake, including customization options for color, size, and error correction. ```APIDOC ## QR Code Generation ### Description This section details how to generate QR codes within your PDF documents using the `qr` object in the `content` array. You can specify the text, colors, size, and other properties of the QR code. ### Usage ```javascript var docDefinition = { content: [ // basic usage { qr: 'text in QR' }, // colored QR { qr: 'text in QR', foreground: 'red', background: 'yellow' }, // resized QR { qr: 'text in QR', fit: '500' }, ] } ``` ### Properties * `qr` (string) - Required - The text content to be encoded in the QR code. * `foreground` (string) - Optional (default: black) - The color of the QR code's foreground. * `background` (string) - Optional (default: white) - The color of the QR code's background. * `fit` (integer) - Optional - Specifies the size to which the QR code image should be scaled. * `version` (integer) - Optional - Defines the QR code version, ranging from 1 to 40. Refer to Wikipedia for details. * `eccLevel` (string) - Optional (default: L) - The error correction capability. Possible values are 'L', 'M', 'Q', 'H'. Refer to Wikipedia for details. * `mode` (string) - Optional - The encoding mode. Possible values are 'numeric', 'alphanumeric', 'octet'. Refer to Wikipedia for details. * `mask` (integer) - Optional - The mask pattern, ranging from 0 to 7. Refer to Wikipedia for details. ``` -------------------------------- ### Get PDF as Data URL Source: https://pdfmake.github.io/docs/0.3/getting-started/server-side/methods Retrieves the generated PDF document as a Data URL. This is useful for embedding the PDF in web pages or for direct use in browsers. Returns a Promise. ```APIDOC ## Get PDF as Data URL ### Description Retrieves the generated PDF document as a Data URL. This is useful for embedding the PDF in web pages or for direct use in browsers. Returns a Promise. ### Method `pdfmake.createPdf(docDefinition).getDataUrl()` ### Parameters None ### Response #### Success Response - **dataUrl** (string) - The PDF document as a Data URL. ``` -------------------------------- ### Create PDF Document Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Use `createPdf` to generate a PDF document. It accepts a document definition object and optional advanced options. ```javascript pdfMake.createPdf(docDefinition); pdfMake.createPdf(docDefinition, options); ``` -------------------------------- ### Create Bulleted and Numbered Lists in pdfmake Source: https://pdfmake.github.io/docs/0.3/document-definition-object/lists Use the 'ul' key for bulleted lists and 'ol' key for numbered lists. Items can be simple strings or text objects with styling. Custom colors and marker colors can be applied to list items. ```javascript var docDefinition = { content: [ 'Bulleted list example:', { // to treat a paragraph as a bulleted list, set an array of items under the ul key ul: [ 'Item 1', 'Item 2', 'Item 3', { text: 'Item 4', bold: true }, ] }, 'Numbered list example:', { // for numbered lists set the ol key ol: [ 'Item 1', 'Item 2', 'Item 3' ] }, 'Colored unordered list:', { color: 'blue', ul: [ 'item 1', 'item 2', 'item 3' ] }, 'Colored unordered list with own marker color:', { color: 'blue', markerColor: 'red', ul: [ 'item 1', 'item 2', { text: 'item 3 with custom marker color', markerColor: 'lime' } // Minimal pdfmake version: 0.3.2 ] }, 'Colored ordered list', { color: 'blue', ol: [ 'item 1', 'item 2', 'item 3' ] }, 'Colored ordered list with own marker color:', { color: 'blue', markerColor: 'red', ol: [ 'item 1', 'item 2', { text: 'item 3 with custom marker color', markerColor: 'lime' } // Minimal pdfmake version: 0.3.2 ] }, ] }; ``` -------------------------------- ### Print PDF Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods The `print()` method initiates the browser's print dialog for the PDF. An optional window object can be provided for asynchronous operations. ```javascript pdfMake.createPdf(docDefinition).print(); pdfMake.createPdf(docDefinition).print(win); ``` -------------------------------- ### Basic Table of Contents Implementation Source: https://pdfmake.github.io/docs/0.3/document-definition-object/toc This snippet shows the simplest way to add a table of contents to your document. Ensure 'tocItem: true' is set on the content you want included. ```javascript var docDefinition = { content: [ { toc: { title: {text: 'INDEX', style: 'header'} //textMargin: [0, 0, 0, 0], //textStyle: {italics: true}, numberStyle: { bold: true }, } }, { text: 'This is a header', style: 'header', tocItem: true } ] } ``` -------------------------------- ### Download PDF Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Generates a PDF and prompts the user to download it. A filename can be specified. ```APIDOC ## .download() ### Description Generates a PDF document and initiates a download. You can specify a filename for the downloaded PDF. ### Method `.download()` `.download(filename)` ### Parameters #### Path Parameters - `filename` (string) - Optional - PDF document file name (default ‘file.pdf’) ### Request Example ```javascript pdfMake.createPdf(docDefinition).download('myDocument.pdf'); ``` ``` -------------------------------- ### Download PDF Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Call `download()` on the created PDF object to download the document. An optional filename can be provided. ```javascript pdfMake.createPdf(docDefinition).download(); pdfMake.createPdf(docDefinition).download('file.pdf'); ``` -------------------------------- ### Print PDF Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Generates a PDF and opens the browser's print dialog. An optional window object can be provided for asynchronous operations. ```APIDOC ## .print() ### Description Generates a PDF document and opens the browser's print dialog. This method can accept an optional window object, particularly useful for asynchronous operations. ### Method `.print()` `.print(win)` ### Parameters #### Path Parameters - `win` (object) - Optional - The window object to print the PDF in (when an asynchronous operation). ### Request Example ```javascript // Asynchronous example const win = window.open('', '_blank'); pdfMake.createPdf(docDefinition).print(win); // Printing in the same window pdfMake.createPdf(docDefinition).print(window); ``` ``` -------------------------------- ### Import pdfmake with TypeScript Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side Import pdfmake and its default fonts using TypeScript syntax. ```typescript import * as pdfMake from "pdfmake/build/pdfmake"; import * as pdfFonts from 'pdfmake/build/vfs_fonts'; (pdfMake).addVirtualFileSystem(pdfFonts); ``` -------------------------------- ### Dynamic Headers and Footers with Page Numbers Source: https://pdfmake.github.io/docs/0.3/document-definition-object/headers-footers Implement dynamic headers and footers by providing functions. These functions receive page information like current page number, total page count, and page size to generate content. ```javascript var docDefinition = { footer: function(currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; }, header: function(currentPage, pageCount, pageSize) { // you can apply any logic and return any valid pdfmake element return [ { text: 'simple text', alignment: (currentPage % 2) ? 'left' : 'right' }, { canvas: [ { type: 'rect', x: 170, y: 32, w: pageSize.width - 170, h: 40 } ] } ] }, (...) }; ``` -------------------------------- ### Define PDF Outlines with pdfmake Source: https://pdfmake.github.io/docs/0.3/document-definition-object/outlines Use the `outline` property to add content to the PDF's bookmark structure. Customize bookmark text with `outlineText`, control expansion with `outlineExpanded`, and establish hierarchy with `outlineParentId` by referencing a parent's `id`. ```javascript var docDefinition = { content: [ { text: 'First header in bookmarks', outline: true, }, { text: 'Second header with custom bookmark', outline: true, outlineText: 'Custom bookmark text', }, { text: 'Structured bookmarks', id: 'structured-bookmarks', outline: true, outlineExpanded: true }, { text: 'First subheader', outline: true, outlineParentId: 'structured-bookmarks' }, { text: 'Second subheader', outline: true, outlineParentId: 'structured-bookmarks' }, { text: 'Third subheader', outline: true, outlineParentId: 'structured-bookmarks', id: 'third-subheader' } ] }; ``` -------------------------------- ### Import pdfmake with ES Modules Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side Use import statements for pdfmake and its default fonts in ES Module environments. ```javascript import pdfMake from "pdfmake/build/pdfmake"; import "pdfmake/build/vfs_fonts"; ``` -------------------------------- ### Generate QR Codes in pdfmake Source: https://pdfmake.github.io/docs/0.3/document-definition-object/qr Use the 'qr' property within the content definition to create QR codes. You can customize their appearance with foreground and background colors, and control their size using the 'fit' property. ```javascript var docDefinition = { content: [ // basic usage { qr: 'text in QR' }, // colored QR { qr: 'text in QR', foreground: 'red', background: 'yellow' }, // resized QR { qr: 'text in QR', fit: '500' }, ] } ``` -------------------------------- ### Set Encryption and Permissions in Document Definition Source: https://pdfmake.github.io/docs/0.3/document-definition-object/security Use `userPassword`, `ownerPassword`, and the `permissions` object to control document security. By default, all operations are disallowed and must be explicitly permitted. ```javascript var docDefinition = { userPassword: '123', ownerPassword: '123456', permissions: { printing: 'highResolution', //'lowResolution' modifying: false, copying: false, annotating: true, fillingForms: true, contentAccessibility: true, documentAssembly: true }, content: [ '...' ] }; ``` -------------------------------- ### Styling a Stack of Paragraphs in Columns Source: https://pdfmake.github.io/docs/0.3/document-definition-object/stack Shows how to apply styling properties, like fontSize, to an entire stack of paragraphs by using the explicit '{ stack: [] }' syntax instead of an array shortcut. This is useful for restyling a group of paragraphs. ```javascript var docDefinition = { content: [ 'paragraph 1', 'paragraph 2', { columns: [ 'first column is a simple text', { stack: [ // second column consists of paragraphs 'paragraph A', 'paragraph B', 'these paragraphs will be rendered one below another inside the column' ], fontSize: 15 } ] } ] }; ``` -------------------------------- ### Create PDF Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Generates a PDF document from a document definition object. It can optionally accept advanced options. ```APIDOC ## pdfMake.createPdf(docDefinition) ### Description Generates a PDF document from a document definition object. ### Method `pdfMake.createPdf(docDefinition)` `pdfMake.createPdf(docDefinition, options)` ### Parameters #### Path Parameters - `docDefinition` (object) - Required - Object with document definition. - `options` (object) - Optional - Advanced options. ### Request Example ```javascript const docDefinition = { content: [ 'First paragraph', { text: 'Second paragraph, bold', bold: true } ] }; pdfMake.createPdf(docDefinition); ``` ``` -------------------------------- ### Set Page Size, Orientation, and Margins Source: https://pdfmake.github.io/docs/0.3/document-definition-object/page Define the page size using a string (e.g., 'A5'), set the page orientation to 'landscape', and specify page margins as an array of four values [left, top, right, bottom]. ```javascript var docDefinition = { // a string or { width: number, height: number } pageSize: 'A5', // by default we use portrait, you can change it to landscape if you wish pageOrientation: 'landscape', // [left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins pageMargins: [ 40, 60, 40, 60 ], }; ``` -------------------------------- ### Define Multi-Column Layout with pdfmake Source: https://pdfmake.github.io/docs/0.3/document-definition-object/columns Use the 'columns' property in your document definition to create a multi-column layout. Each column can have its width defined by 'auto', '*', a fixed number, or a percentage. The 'columnGap' property controls the spacing between columns. ```javascript var docDefinition = { content: [ 'This paragraph fills full width, as there are no columns. Next paragraph however consists of three columns', { columns: [ { // auto-sized columns have their widths based on their content width: 'auto', text: 'First column' }, { // star-sized columns fill the remaining space // if there's more than one star-column, available width is divided equally width: '*', text: 'Second column' }, { // fixed width width: 100, text: 'Third column' }, { // % width width: '20%', text: 'Fourth column' } ], // optional space between columns columnGap: 10 }, 'This paragraph goes below all columns and has full width' ] }; ``` -------------------------------- ### Print PDF in Same Window Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side/methods Use `print(window)` to trigger the print dialog for the PDF within the current browser window. ```javascript pdfMake.createPdf(docDefinition).print(window); ``` -------------------------------- ### Inherit Properties in Document Section Source: https://pdfmake.github.io/docs/0.3/document-definition-object/sections This snippet shows how to set properties like header, footer, background, watermark, page size, orientation, and margins to 'inherit'. This allows a section to automatically adopt the settings from the preceding section, simplifying configuration for sequential content. ```javascript var docDefinition = { content: [ { header: 'inherit', footer: 'inherit', background: 'inherit', watermark: 'inherit', pageSize: 'inherit', pageOrientation: 'inherit', pageMargins: 'inherit', section: [ 'Text in section.' ] } ] } ``` -------------------------------- ### Define Document Section with Custom Properties Source: https://pdfmake.github.io/docs/0.3/document-definition-object/sections This snippet demonstrates how to define a document section with custom page size, orientation, margins, header, footer, and background. Use this when you need specific page configurations for a part of your document. ```javascript var docDefinition = { content: [ { header: function (currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; }, footer: function (currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; }, background: function () { return {text: 'background', alignment: 'right'}; }, watermark: 'watermark', pageSize: 'A4', pageOrientation: 'landscape', pageMargins: 5, section: [ 'Text in section.' ] } ] } ``` -------------------------------- ### Create PDF Document Source: https://pdfmake.github.io/docs/0.3/getting-started/server-side/methods Generates a PDF document from a document definition object. It can optionally accept advanced options. ```APIDOC ## Create PDF Document ### Description Generates a PDF document from a document definition object. It can optionally accept advanced options. ### Method `pdfmake.createPdf(docDefinition, [options])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **docDefinition** (object) - Required - An object defining the document content and structure. - **options** (object) - Optional - Advanced options for PDF generation. ``` -------------------------------- ### Table with ColSpan and RowSpan Source: https://pdfmake.github.io/docs/0.3/document-definition-object/tables Illustrates the use of `colSpan` and `rowSpan` properties within table cells. When using these properties, ensure to use empty cells for subsequent columns or rows that are spanned. ```javascript var dd = { content: [ { table: { body: [ [{text: 'Header with Colspan = 2', style: 'tableHeader', colSpan: 2, alignment: 'center'}, '', {text: 'Header 3', style: 'tableHeader', alignment: 'center'}], [{text: 'Header 1', style: 'tableHeader', alignment: 'center'}, {text: 'Header 2', style: 'tableHeader', alignment: 'center'}, {text: 'Header 3', style: 'tableHeader', alignment: 'center'}], ['Sample value 1', 'Sample value 2', 'Sample value 3'], [{rowSpan: 3, text: 'rowSpan set to 3\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor'}, 'Sample value 2', 'Sample value 3'], ['', 'Sample value 2', 'Sample value 3'], ['Sample value 1', 'Sample value 2', 'Sample value 3'], ['Sample value 1', {colSpan: 2, rowSpan: 2, text: 'Both:\nrowSpan and colSpan\ncan be defined at the same time'}, ''], ['Sample value 1', '', ''], ] } } ] } ``` -------------------------------- ### Basic HTML Structure for pdfmake Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side Include these two script tags in your HTML to use pdfmake with default fonts in the browser. ```html my first pdfmake example ... ``` -------------------------------- ### Default Style in pdfmake Source: https://pdfmake.github.io/docs/0.3/document-definition-object/styling Illustrates how to set a default style that applies to all text elements unless overridden. This is ideal for establishing a base font size, weight, or other properties for the entire document. ```javascript var docDefinition = { content: [ 'Text styled by default style' ], defaultStyle: { fontSize: 15, bold: true } }; ``` -------------------------------- ### Apply Icon Style Source: https://pdfmake.github.io/docs/0.3/fonts/icons Create a style object that references the custom font. This style can then be applied to text elements to render icons. ```javascript icon: { font: 'Fontello' } ``` -------------------------------- ### Require pdfmake with CommonJS Source: https://pdfmake.github.io/docs/0.3/getting-started/client-side Import pdfmake and its fonts using require for CommonJS environments. ```javascript var pdfMake = require('pdfmake/build/pdfmake.js'); require('pdfmake/build/vfs_fonts.js'); ``` -------------------------------- ### Apply Pattern as Table Cell Overlay Source: https://pdfmake.github.io/docs/0.3/document-definition-object/patterns Applies a defined pattern ('stripe45d') with a specified color ('gray') as an overlay on a table cell, painted over its existing content and `fillColor`. `overlayOpacity` controls the pattern's transparency. ```javascript { text: 'Sample value', fillOpacity: 0.15, fillColor: 'blue', overlayPattern: ['stripe45d', 'gray'], overlayOpacity: 0.15 } ```