### Initialize a PDFDocument Source: https://pdfkit.org/docs/getting_started.html Basic setup for requiring the module and instantiating a new PDF document. ```javascript const PDFDocument = require('pdfkit'); const doc = new PDFDocument(); ``` -------------------------------- ### Install PDFKit via npm Source: https://pdfkit.org/index.html Use this command to install the PDFKit package in your project. ```bash npm install pdfkit ``` -------------------------------- ### Example: Adding Multiple Annotations Source: https://pdfkit.org/docs/annotations.html Demonstrates how to add various annotations, including links, highlights, strike-throughs, and notes, with custom colors and icons. ```javascript doc.fontSize(25) .fillColor('blue') .text('This is a link!', 20, 0); const width = doc.widthOfString('This is a link!'); const height = doc.currentLineHeight(); doc.underline(20, 0, width, height, {color: 'blue'}) .link(20, 0, width, height, 'http://google.com/'); doc.moveDown() .fillColor('black') .highlight(20, doc.y, doc.widthOfString('This text is highlighted!'), height) .text('This text is highlighted!'); doc.addSpotColor('PANTONE185C', 0, 100, 78, 9) .moveDown() .fillColor('PANTONE185C') .text('This text uses spot color!'); doc.moveDown() .strike(20, doc.y, doc.widthOfString('STRIKE!'), height) .text('STRIKE!'); doc.note(10, 30, 30, 30, "Text of note"); doc.note(10, 80, 30, 30, "Text of custom note", {Name: 'Key', color: 'red'}); doc.goTo(20, doc.y, 10, 20, 'LINK', {}); ``` -------------------------------- ### Example: Combined Text Formatting and Annotations Source: https://pdfkit.org/docs/annotations.html Shows how to apply text formatting, including links and underlines, directly within the `text` method. ```javascript doc.fontSize(20) .fillColor('red') .text('Another link!', 20, 0, { link: 'http://apple.com/', underline: true }); ``` -------------------------------- ### Adding and Scaling Images in PDFKit Source: https://pdfkit.org/docs/images.html Examples of using the image method with various scaling, fitting, and alignment options. ```javascript // Scale proprotionally to the specified width doc.image('images/test.jpeg', 0, 15, {width: 300}) .text('Proportional to width', 0, 0); // Fit the image within the dimensions doc.image('images/test.jpeg', 320, 15, {fit: [100, 100]}) .rect(320, 15, 100, 100) .stroke() .text('Fit', 320, 0); // Stretch the image doc.image('images/test.jpeg', 320, 145, {width: 200, height: 100}) .text('Stretch', 320, 130); // Scale the image doc.image('images/test.jpeg', 320, 280, {scale: 0.25}) .text('Scale', 320, 265); // Fit the image in the dimensions, and center it both horizontally and vertically doc.image('images/test.jpeg', 430, 15, {fit: [100, 100], align: 'center', valign: 'center'}) .rect(430, 15, 100, 100).stroke() .text('Centered', 430, 0); ``` -------------------------------- ### Style Precedence Example Source: https://pdfkit.org/docs/table.html Shows the order of precedence for styles when defining a table: `defaultStyle`, `columnStyles`, `rowStyles`, and `cellStyle`. The resulting cell style is a combination of these. ```javascript doc.table({ defaultStyle: { border: 1 }, columnStyles: { border: { right: 2 } }, rowStyles: { border: { bottom: 3 } }, data: [ [{ border: { left: 4 } }] ] }) ``` -------------------------------- ### Add Link and Underline Annotations to Text Source: https://pdfkit.org/docs/annotations.html A simplified example showing how to add both a link and an underline to a piece of text using a single options object. This is useful for common text annotations. ```javascript doc.fontSize(20) .fillColor('red') .text('Another link!', 20, 0, { link: 'http://apple.com/', underline: true } ); ``` -------------------------------- ### Table with Row and Column Spans Source: https://pdfkit.org/docs/table.html Illustrates creating a table with cells that span multiple rows and columns, using `rowSpan` and `colSpan` properties. This example also sets a `defaultStyle` for the table. ```javascript doc.table({ defaultStyle: { border: false, width: 60 }, data: [ ["", "column 1", "column 2", "column 3"], [ "row 1", { rowSpan: 3, colSpan: 3, border: true, backgroundColor: "#ccc", text: "rowSpan: 3\ncolSpan: 3\n\nborder:\n[true, true, true, true]", }, ], ["row 2"], ["row 3"], ], }) ``` -------------------------------- ### Wrap and justify text in PDFKit Source: https://pdfkit.org/docs/text.html Configure text wrapping and justification by passing an options object to the `text` method. Options include `width`, `align`, and `lineBreak`. This example demonstrates left, center, right, and justified alignment. ```javascript const lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in suscipit purus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus nec hendrerit felis. Morbi aliquam facilisis risus eu lacinia. Sed eu leo in turpis fringilla hendrerit. Ut nec accumsan nisl.'; doc.fontSize(8); doc.text(`This text is left aligned. ${lorem}`, { width: 410, align: 'left' } ); doc.moveDown(); doc.text(`This text is centered. ${lorem}`, { width: 410, align: 'center' } ); doc.moveDown(); doc.text(`This text is right aligned. ${lorem}`, { width: 410, align: 'right' } ); doc.moveDown(); doc.text(`This text is justified. ${lorem}`, { width: 410, align: 'justify' } ); // draw bounding rectangle doc.rect(doc.x, 0, 410, doc.y).stroke(); ``` -------------------------------- ### Apply Gradient Fill Source: https://pdfkit.org/examples/browserify/browser.html Creates and applies a linear gradient fill to a rectangular shape. Define the gradient's start and end points, and use `stop()` to specify colors at different positions. ```javascript // a gradient fill var gradient = doc .linearGradient(100, 300, 200, 300) .stop(0, 'green') .stop(0.5, 'red') .stop(1, 'green'); doc.rect(100, 300, 100, 100).fill(gradient); ``` -------------------------------- ### Light Horizontal Lines for Table Rows in PDFKit Source: https://pdfkit.org/docs/table.html Create subtle horizontal lines for table rows using `rowStyles`. This example applies a thicker black border to the header and thinner gray borders to subsequent rows. ```javascript doc.table({ rowStyles: (i) => { return i < 1 ? { border: [0, 0, 2, 0], borderColor: "black" } : { border: [0, 0, 1, 0], borderColor: "#aaa" }; }, data: [ ["Header 1", "Header 2", "Header 3"], ["Sample value 1", "Sample value 2", "Sample value 3"], ["Sample value 1", "Sample value 2", "Sample value 3"], ["Sample value 1", "Sample value 2", "Sample value 3"], ["Sample value 1", "Sample value 2", "Sample value 3"], ["Sample value 1", "Sample value 2", "Sample value 3"], ], }) ``` -------------------------------- ### goTo Source: https://pdfkit.org/docs/destinations.html Creates a link to a previously defined named destination. ```APIDOC ## goTo(x, y, width, height, destination) ### Description Creates an annotation that acts as a link to a specific named destination. ### Parameters - **x** (number) - Required - X coordinate of the link area. - **y** (number) - Required - Y coordinate of the link area. - **width** (number) - Required - Width of the link area. - **height** (number) - Required - Height of the link area. - **destination** (string) - Required - The name of the destination to link to. ``` -------------------------------- ### Navigate to Destinations Source: https://pdfkit.org/docs/destinations.html Use goTo to create interactive links that jump to previously defined named destinations. ```javascript // Go to annotation doc.goTo(10, 10, 100, 20, 'LINK') // Go to annotation for this text doc.text('Another goto', 20, 0, { goTo: 'ENDP', underline: true }); ``` -------------------------------- ### Generate a PDF document Source: https://pdfkit.org/index.html Demonstrates creating a document, piping output to a file, embedding fonts, adding images, drawing vector graphics, and adding annotations. ```javascript const PDFDocument = require('pdfkit'); const fs = require('fs'); // Create a document const doc = new PDFDocument(); // Pipe its output somewhere, like to a file or HTTP response // See below for browser usage doc.pipe(fs.createWriteStream('output.pdf')); // Embed a font, set the font size, and render some text doc .font('fonts/PalatinoBold.ttf') .fontSize(25) .text('Some text with an embedded font!', 100, 100); // Add an image, constrain it to a given size, and center it vertically and horizontally doc.image('path/to/image.png', { fit: [250, 300], align: 'center', valign: 'center' }); // Add another page doc .addPage() .fontSize(25) .text('Here is some vector graphics...', 100, 100); // Draw a triangle doc .save() .moveTo(100, 150) .lineTo(100, 250) .lineTo(200, 250) .fill('#FF3300'); // Apply some transforms and render an SVG path with the 'even-odd' fill rule doc .scale(0.6) .translate(470, -380) .path('M 250,75 L 323,301 131,161 369,161 177,301 z') .fill('red', 'even-odd') .restore(); // Add some text with annotations doc .addPage() .fillColor('blue') .text('Here is a link!', 100, 100) .underline(100, 100, 160, 27, { color: '#0000FF' }) .link(100, 100, 160, 27, 'http://google.com/'); // Finalize PDF file doc.end(); ``` -------------------------------- ### Wrap Text into Columns Source: https://pdfkit.org/examples/browserify/browser.html Adds wrapped text to the PDF, starting at a specified position. Subsequent text can be styled with a different font and size, and positioned using `moveDown()`. ```javascript // and some justified text wrapped into columns doc .text('And here is some wrapped text...', 100, 450) .font('Times-Roman', 13) .moveDown() ``` -------------------------------- ### Set Font and Font Size Source: https://pdfkit.org/docs/text.html Demonstrates setting the font size and then switching between standard PDF fonts and embedded TrueType or collection fonts. Ensure font files are accessible by path. ```javascript // Set the font size doc.fontSize(18); // Using a standard PDF font doc.font('Times-Roman') .text('Hello from Times Roman!') .moveDown(0.5); // Using a TrueType font (.ttf) doc.font('fonts/GoodDog.ttf') .text('This is Good Dog!') .moveDown(0.5); // Using a collection font (.ttc or .dfont) doc.font('fonts/Chalkboard.ttc', 'Chalkboard-Bold') .text('This is Chalkboard, not Comic Sans.'); ``` -------------------------------- ### Cancel Link in Rich Text Source: https://pdfkit.org/docs/text.html To remove a hyperlink from subsequent text, set the `link` option to `null` in the `text` method. This example demonstrates changing colors and applying/removing links. ```javascript doc.fillColor('red') .text(lorem.slice(0, 199), { width: 465, continued: true }) .fillColor('blue') .text(lorem.slice(199, 282), { link: 'http://www.example.com', continued: true }) .fillColor('green') .text(lorem.slice(182, 400), { link: null }); ``` -------------------------------- ### Create a Simple Table Source: https://pdfkit.org/docs/table.html Define a basic table with data. Alternatively, use the row-by-row method for more control. ```javascript doc.table({ data: [ ['Column 1', 'Column 2', 'Column 3'], ['One value goes here', 'Another one here', 'OK?'] ] }) ``` ```javascript doc.table() .row(['Column 1', 'Column 2', 'Column 3']) .row(['One value goes here', 'Another one here', 'OK?']) ``` -------------------------------- ### Browser PDFKit with blob-stream Source: https://pdfkit.org/index.html Use this snippet to integrate PDFKit in the browser with Browserify or webpack. It requires the blob-stream module to handle PDF output as a Blob. Ensure you have the necessary dependencies installed. ```javascript require('pdfkit'); const blobStream = require('blob-stream'); const doc = new PDFDocument(); const stream = doc.pipe(blobStream()); doc.end(); stream.on('finish', function() { const blob = stream.toBlob('application/pdf'); const url = stream.toBlobURL('application/pdf'); iframe.src = url; }); ``` -------------------------------- ### Equivalent Structure Construction for Text Source: https://pdfkit.org/docs/accessibility.html This demonstrates the manual equivalent of using `structParent` with `text()`, showing how paragraphs are added as 'P' type structure elements. ```javascript const section = doc.struct('Sect'); doc.addStructure(section); section.add(doc.struct('P', () => { doc.text("Foo. "); }); section.add(doc.struct('P', () => { doc.text("Bar. "); }); ``` -------------------------------- ### List Creation Source: https://pdfkit.org/docs/text.html How to create bulleted lists, including multi-level lists and custom styling. ```APIDOC ## Lists The `list` method generates bulleted lists. It accepts an array of strings and optional `x`, `y` coordinates. ### Options: - `bulletRadius` (number): The radius of the bullet. - `textIndent` (number): Indentation for the list text. - `bulletIndent` (number): Indentation for the bullet itself. Nested arrays can be used to create multi-level lists. ### Example: ```javascript doc.list(['Item 1', 'Item 2', ['Subitem 2.1', 'Subitem 2.2'], 'Item 3']); ``` ``` -------------------------------- ### Apply multi-column text layout Source: https://pdfkit.org/docs/text.html Demonstrates wrapping text into multiple columns with specific dimensions and alignment. ```javascript const lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in suscipit purus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus nec hendrerit felis. Morbi aliquam facilisis risus eu lacinia. Sed eu leo in turpis fringilla hendrerit. Ut nec accumsan nisl. Suspendisse rhoncus nisl posuere tortor tempus et dapibus elit porta. Cras leo neque, elementum a rhoncus ut, vestibulum non nibh. Phasellus pretium justo turpis. Etiam vulputate, odio vitae tincidunt ultricies, eros odio dapibus nisi, ut tincidunt lacus arcu eu elit. Aenean velit erat, vehicula eget lacinia ut, dignissim non tellus. Aliquam nec lacus mi, sed vestibulum nunc. Suspendisse potenti. Curabitur vitae sem turpis. Vestibulum sed neque eget dolor dapibus porttitor at sit amet sem. Fusce a turpis lorem. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;'; doc.text(lorem, { columns: 3, columnGap: 15, height: 100, width: 465, align: 'justify' }); ``` -------------------------------- ### Draw a Path with Lines and Curves in PDFKit Source: https://pdfkit.org/docs/vector.html Use moveTo, lineTo, quadraticCurveTo, and bezierCurveTo to define a path. All methods are chainable. The path is stroked to be visible. ```javascript doc.moveTo(0, 20) // set the current point .lineTo(100, 160) // draw a line .quadraticCurveTo(130, 200, 150, 120) // draw a quadratic curve .bezierCurveTo(190, -40, 200, 200, 300, 150) // draw a bezier curve .lineTo(400, 90) // draw another line .stroke(); // stroke the path ``` -------------------------------- ### Create PDF Document and Pipe to Blob Stream Source: https://pdfkit.org/examples/browserify/browser.html Initializes a new PDFDocument and pipes its output to a blob stream for browser-based PDF generation. Ensure blob-stream is available in your environment. ```javascript // create a document and pipe to a blob var doc = new PDFDocument(); var stream = doc.pipe(blobStream()); ``` -------------------------------- ### Initializing Form Support Source: https://pdfkit.org/docs/forms.html Before adding any form annotations, you must initialize the form functionality for the document. ```APIDOC ## Initialize Form Support ### Description Initializes the PDF document to support form annotations. This method must be called before adding any form fields. ### Method `initForm()` ### Endpoint N/A (Method on document object) ### Parameters None ### Request Example ```javascript doc.font('Helvetica'); // establishes the default form field font doc.initForm(); ``` ### Response N/A ``` -------------------------------- ### Add hierarchical bookmarks in PDFKit Source: https://pdfkit.org/docs/outline.html Demonstrates creating a top-level bookmark and a nested sub-section using the outline root. ```javascript // Get a reference to the Outline root const { outline } = doc; // Add a top-level bookmark const top = outline.addItem('Top Level'); // Add a sub-section top.addItem('Sub-section'); ``` -------------------------------- ### Deferred Content Execution with Closures Source: https://pdfkit.org/docs/accessibility.html Demonstrates using closures to defer content addition until the structure element is attached to the document. ```javascript const myParagraph = doc.struct('P', [ () => { doc.text("Please see ", { continued: true }); }, doc.struct('Link', () => { doc.text("something", { link: "http://www.example.com/", continued: true }); }), () => { doc.text(" for details. ", { link: null }); } ]); ``` ```javascript doc.addStructure(section1); section1.add(myParagraph); // Content is added now ``` ```javascript section1.add(myParagraph); doc.addStructure(section1); // Content is added now ``` -------------------------------- ### Table Options Source: https://pdfkit.org/docs/table.html Lists and describes the available options for configuring a table. ```APIDOC ## Table options * `position` - The position of the table (default `{x: doc.x, y: doc.y}`) * `maxWidth` - The maximum width the table can expand to (defaults to the remaining content width (offset from the tables position)) * `columnStyles` - Column definitions of the table. (default `auto`) * `rowStyles` - Row definitions of the table. (default `*`) * `defaultStyle` - Defaults to apply to every cell * `data` - The data to render (not required, you can call `.row()`). This can be an iterable (async or sync) * `debug` - Whether to show the debug lines for all the cells (default `false`) ``` -------------------------------- ### Create Dashed Lines with PDFKit Source: https://pdfkit.org/docs/vector.html Use the `dash` method to create dashed lines. Specify dash length and optional space and phase. Use `undash` to return to solid lines. ```javascript doc.circle(100, 50, 50) .dash(5, {space: 10}) .stroke(); ``` -------------------------------- ### Initialize PDF Forms Source: https://pdfkit.org/docs/forms.html Call initForm() before adding any form annotations to the document. ```javascript doc.font('Helvetica'); // establishes the default form field font doc.initForm(); ``` -------------------------------- ### Configure Line Cap and Line Join Styles in PDFKit Source: https://pdfkit.org/docs/vector.html Demonstrates different line cap styles (butt, round, square) and line join styles (miter, round, bevel) by setting the respective properties and drawing shapes. A large line width is used for better visualization. ```javascript // these examples are easier to see with a large line width doc.lineWidth(25); // line cap settings doc.lineCap('butt') .moveTo(50, 20) .lineTo(100, 20) .stroke(); doc.lineCap('round') .moveTo(150, 20) .lineTo(200, 20) .stroke(); // square line cap shown with a circle instead of a line so you can see it doc.lineCap('square') .moveTo(250, 20) .circle(275, 30, 15) .stroke(); // line join settings doc.lineJoin('miter') .rect(50, 100, 50, 50) .stroke(); doc.lineJoin('round') .rect(150, 100, 50, 50) .stroke(); doc.lineJoin('bevel') .rect(250, 100, 50, 50) .stroke(); ``` -------------------------------- ### Incremental Structure Construction Source: https://pdfkit.org/docs/accessibility.html Illustrates building structure elements incrementally and ending them to free memory. ```javascript // Begin a new section and add it to the document's structure const mySection = doc.struct('Sect'); doc.addStructure(mySection); // Create a new paragraph and add it to the section const myParagraph = doc.struct('P'); mySection.add(myParagraph); // Add content, both to the page, and the paragraph const myParagraphContent = doc.markStructureContent('P'); myParagraph.add(myParagraphContent); doc.text('Hello, world! '); // End the paragraph, allowing it to be flushed out, freeing memory myParagraph.end(); ``` -------------------------------- ### Generate PDF content in the browser Source: https://pdfkit.org/demo/browser.html Initializes a PDF document and pipes it to a blob stream for browser-based output. ```javascript // create a document and pipe to a blob var doc = new PDFDocument(); var stream = doc.pipe(blobStream()); // draw some text doc.fontSize(25).text('Here is some vector graphics...', 100, 80); // some vector graphics doc .save() .moveTo(100, 150) .lineTo(100, 250) .lineTo(200, 250) .fill('#FF3300'); doc.circle(280, 200, 50).fill('#6600FF'); // an SVG path doc .scale(0.6) .translate(470, 130) .path('M 250,75 L 323,301 131,161 369,161 177,301 z') .fill('red', 'even-odd') .restore(); doc.save(); // a gradient fill var gradient = doc .linearGradient(100, 300, 200, 300) .stop(0, 'green') .stop(0.5, 'red') .stop(1, 'green'); doc.rect(100, 300, 100, 100).fill(gradient); // stroke & fill uncolored tiling pattern var stripe45d = doc.pattern( [1, 1, 4, 4], 3, 3, '1 w 0 1 m 4 5 l s 2 0 m 5 3 l s' ); doc.circle(280, 350, 50).fill([stripe45d, 'blue']); doc .rect(380, 300, 100, 100) .fillColor('lime') .strokeColor([stripe45d, 'orange']) .lineWidth(5) .fillAndStroke(); doc.restore(); // and some justified text wrapped into columns doc .text('And here is some wrapped text...', 100, 450) .font('Times-Roman', 13) .moveDown() ``` -------------------------------- ### Table with Optional Borders Source: https://pdfkit.org/docs/table.html Demonstrates how to apply optional borders to table cells using various configurations. ```APIDOC ## Optional border ```javascript doc.table({ data: [ [ { border: [true, false, false, false], backgroundColor: "#eee", text: "border:\n[true, false, false, false]" }, { border: false, backgroundColor: "#ddd", text: "border:\nfalse" }, { border: true, backgroundColor: "#eee", text: "border:\ntrue" }, ], [ { rowSpan: 3, border: true, backgroundColor: "#eef", text: "rowSpan: 3\n\nborder:\ntrue" }, { border: undefined, backgroundColor: "#eee", text: "border:\nundefined (default)" }, { border: [false, false, false, true], backgroundColor: "#ddd", text: "border:\n[false, false, false, true]" }, ], [ { colSpan: 2, border: true, backgroundColor: "#efe", text: "colSpan: 2\n\nborder:\ntrue" }, ], [ { border: 0, backgroundColor: "#eee", text: "border:\n0 (same as false)" }, { border: [false, true, true, false], backgroundColor: "#ddd", text: "border:\n[false, true, true, false]" }, ], ], }) ``` ``` -------------------------------- ### Create a Text Field Source: https://pdfkit.org/docs/forms.html Adds a text field with specific formatting options. ```javascript doc.formText('leaf2', 10, 60, 200, 40, { multiline: true, align: 'right', format: { type: 'date', params: 'm/d' } }); ``` -------------------------------- ### Apply Winding Rules for Path Filling in PDFKit Source: https://pdfkit.org/docs/vector.html Use winding rules 'non-zero' or 'even-odd' with `fill` or `fillAndStroke` to control how paths are filled. Transformations like `translate` and `scale` can be applied before drawing. ```javascript // Initial setup doc.fillColor('red') .translate(-100, -50) .scale(0.8); // Draw the path with the non-zero winding rule doc.path('M 250,75 L 323,301 131,161 369,161 177,301 z') .fill('non-zero'); // Draw the path with the even-odd winding rule doc.translate(280, 0) .path('M 250,75 L 323,301 131,161 369,161 177,301 z') .fill('even-odd'); ``` -------------------------------- ### Define Table with Optional Borders Source: https://pdfkit.org/docs/table.html Demonstrates how to define a table with various border configurations for individual cells, including boolean, array, and numeric values for the `border` property. ```javascript doc.table({ data: [ [ { border: [true, false, false, false], backgroundColor: "#eee", text: "border:\n[true, false, false, false]" }, { border: false, backgroundColor: "#ddd", text: "border:\nfalse" }, { border: true, backgroundColor: "#eee", text: "border:\ntrue" }, ], [ { rowSpan: 3, border: true, backgroundColor: "#eef", text: "rowSpan: 3\n\nborder:\ntrue" }, { border: undefined, backgroundColor: "#eee", text: "border:\nundefined (default)" }, { border: [false, false, false, true], backgroundColor: "#ddd", text: "border:\n[false, false, false, true]" }, ], [ { colSpan: 2, border: true, backgroundColor: "#efe", text: "colSpan: 2\n\nborder:\ntrue" }, ], [ { border: 0, backgroundColor: "#eee", text: "border:\n0 (same as false)" }, { border: [false, true, true, false], backgroundColor: "#ddd", text: "border:\n[false, true, true, false]" }, ], ], }) ``` -------------------------------- ### Number and Percent Formatting Source: https://pdfkit.org/docs/forms.html Details options for formatting numeric fields, including decimal places, separators, negative number styles, and currency. ```APIDOC ## Number and percent format * `format.nDec` [_number_] - the number of places after the decimal point * `format.sepComma` [_boolean_] - display a comma separator, otherwise do not display a separator. * `format.negStyle` _string_ - the value must be one of `MinusBlack` , `Red`, `ParensBlack`, `ParensRed` * `format.currency` _string_ - a currency symbol to display * `format.currencyPrepend` _boolean_ - set to true to prepend the currency symbol ```javascript // Currency text field formatting doc.formText('leaf2', 10, 60, 200, 40, { multiline: true, align: 'right', format: { type: 'number', nDec: 2, sepComma: true, negStyle: 'ParensRed', currency: '$', currencyPrepend: true } }); ``` ``` -------------------------------- ### Create Linear and Radial Gradients in PDFKit Source: https://pdfkit.org/docs/vector.html Create gradient fills using `linearGradient` or `radialGradient`. Define color stops with percentage, color, and optional opacity. Gradients are applied using `fill` or `fillColor`. ```javascript // Create a linear gradient let grad = doc.linearGradient(50, 0, 150, 100); grad.stop(0, 'green') .stop(1, 'red'); doc.rect(50, 0, 100, 100); doc.fill(grad); // Create a radial gradient grad = doc.radialGradient(300, 50, 0, 300, 50, 50); grad.stop(0, 'orange', 0) .stop(1, 'orange', 1); doc.circle(300, 50, 50); doc.fill(grad); ``` -------------------------------- ### Configure expanded bookmarks in PDFKit Source: https://pdfkit.org/docs/outline.html Uses the expanded option to ensure child bookmarks are visible by default when the parent is added. ```javascript // Add a top-level bookmark const top = outline.addItem('Top Level', { expanded: true }); // Add a sub-section top.addItem('Sub-section'); ``` -------------------------------- ### Encryption and Access Privileges Source: https://pdfkit.org/docs/getting_started.html Configure PDF encryption and permission settings using the options object during PDFDocument creation. ```APIDOC ## Encryption and Access Privileges ### Description Enable encryption and set access permissions for the PDF file. ### Request Body - **userPassword** (string) - Optional - Password required to open the file - **ownerPassword** (string) - Optional - Password for full access and permission management - **pdfVersion** (string) - Optional - PDF version (1.3, 1.4, 1.5, 1.6, 1.7, 1.7ext3) - **permissions** (object) - Optional - Object specifying file permissions ### Permissions Object - **printing** (string) - Optional - "lowResolution" or "highResolution" - **modifying** (boolean) - Optional - Allow modifying document content - **copying** (boolean) - Optional - Allow copying text or graphics - **annotating** (boolean) - Optional - Allow annotating and form filling - **fillingForms** (boolean) - Optional - Allow filling in form fields and signing - **contentAccessibility** (boolean) - Optional - Allow copying text for accessibility - **documentAssembly** (boolean) - Optional - Allow document assembly ``` -------------------------------- ### Add Various Annotations to PDF Source: https://pdfkit.org/docs/annotations.html Demonstrates adding multiple annotation types including links, underlines, highlights, spot colors, strikes, and notes. Remember that link annotations should be added last to ensure they are clickable. ```javascript // Add the link text doc.fontSize(25) .fillColor('blue') .text('This is a link!', 20, 0); // Measure the text const width = doc.widthOfString('This is a link!'); const height = doc.currentLineHeight(); // Add the underline and link annotations doc.underline(20, 0, width, height, {color: 'blue'}) .link(20, 0, width, height, 'http://google.com/'); // Create the highlighted text doc.moveDown() .fillColor('black') .highlight(20, doc.y, doc.widthOfString('This text is highlighted!'), height) .text('This text is highlighted!'); // Create text with a spot color doc.addSpotColor('PANTONE185C', 0, 100, 78, 9) doc.moveDown() .fillColor('PANTONE185C') .text('This text uses spot color!'); // Create the crossed out text doc.moveDown() .strike(20, doc.y, doc.widthOfString('STRIKE!'), height) .text('STRIKE!'); // Create note doc.note(10, 30, 30, 30, "Text of note"); // Create note with custom options doc.note(10, 80, 30, 30, "Text of custom note", {Name: 'Key', color: 'red'}); // Adding go to as annotation doc.goTo(20, doc.y, 10, 20, 'LINK', {}); ``` -------------------------------- ### Create a hierarchical form structure Source: https://pdfkit.org/docs/forms.html Demonstrates organizing form fields into a parent-child hierarchy and adding annotations to those fields. ```javascript doc.font('Helvetica'); // establishes the default font doc.initForm(); let rootField = doc.formField('rootField'); let child1Field = doc.formField('child1Field', { parent: rootField }); let child2Field = doc.formField('child2Field', { parent: rootField }); // Add text form annotation 'rootField.child1Field.leaf1' doc.formText('leaf1', 10, 10, 200, 40, { parent: child1Field, multiline: true }); // Add text form annotation 'rootField.child1Field.leaf2' doc.formText('leaf2', 10, 60, 200, 40, { parent: child1Field, multiline: true }); // Add text form annotation 'rootField.child2Field.leaf1' doc.formText('leaf1', 10, 110, 200, 80, { parent: child2Field, multiline: true }); // Add push button form annotation 'btn1' var opts = { backgroundColor: 'yellow', label: 'Test Button' }; doc.formPushButton('btn1', 10, 200, 100, 30, opts); ``` -------------------------------- ### Creating Complex Nested Structures Source: https://pdfkit.org/docs/accessibility.html Shows how to define nested structure elements and add them to the document's structure. ```javascript // Create nested structure elements const section1 = doc.struct('Sect', [ doc.struct('P', [ someTextStructureContent, doc.struct('Link', someLinkStructureContent), moreTextStructureContent ]) ]); const section2 = doc.struct('Sect', secondSectionStructureContent); // Add them to the document's structure doc.addStructure(section1).addStructure(section2); ``` -------------------------------- ### Marking Structure Content and Artifacts Source: https://pdfkit.org/docs/accessibility.html Demonstrates how to mark content as artifacts or structure elements, noting that these are mutually exclusive and will automatically end previous markings. ```javascript // Mark multiple paragraphs without needing to close them doc.markContent('Artifact', { type: "Layout" }); doc.rect(x1, y1, w1, h1); const myStructContent = doc.markStructureContent('P'); doc.text('Hello, world! '); doc.markContent('Artifact', { type: "Layout" }); doc.rect(x2, y2, w2, h1); const myStructContent = doc.markStructureContent('P'); doc.markContent('Span'); doc.text('Bonjour, tout le monde! '); doc.markContent('Artifact', { type: "Layout" }); doc.rect(x3, y3, w3, h1); const myStructContent = doc.markStructureContent('P'); doc.text('Hello again! '); ``` -------------------------------- ### Table Positioning Source: https://pdfkit.org/docs/table.html Demonstrates how tables are positioned within the document flow, and how subsequent content follows. ```APIDOC ## Table Positioning Internally, PDFKit keeps track of the current X and Y position of table as it is added to the document. This way, any calls to `text` or `table` will be placed below the table row. ```javascript doc .text('before') .table({ data: [ ['Column 1', 'Column 2', 'Column 3'], ['One value goes here', 'Another one here', 'OK?'] ] }) .text('after') ``` ``` -------------------------------- ### Common Form Annotation Options Source: https://pdfkit.org/docs/forms.html Configuration options applicable to most form annotation types. ```APIDOC ## Common Options ### Description These options can be used with most form annotation types to control their behavior and appearance. ### Options - **required** (_boolean_): If true, the field must have a value upon form submission. - **noExport** (_boolean_): If true, the field's value will not be included in form submissions. - **readOnly** (_boolean_): If true, the user cannot change the field's value, and it will not respond to clicks. Useful for computed fields. - **value** (_number|string_): The initial or current value of the field. - **defaultValue** (_number|string_): The value the field reverts to when a reset-form action is executed. - **backgroundColor** (_color_): Sets the background color of the field. Accepts RGB arrays, hex colors, or CSS color names. - **borderColor** (_color_): Sets the border color of the field. Accepts RGB arrays, hex colors, or CSS color names. ### Color Format Colors can be specified as: - An array of RGB values (e.g., `[255, 0, 0]` for red). - A hex color string (e.g., `'#FF0000'` for red). - A named CSS color value (e.g., `'red'`). ``` -------------------------------- ### Document Metadata Configuration Source: https://pdfkit.org/docs/getting_started.html Configure document metadata by adding properties to the doc.info object or passing an info object during document creation. ```APIDOC ## Document Metadata ### Description Set metadata properties for the PDF document. Properties must have their first letter capitalized. ### Request Body - **Title** (string) - Optional - The title of the document - **Author** (string) - Optional - The name of the author - **Subject** (string) - Optional - The subject of the document - **Keywords** (string) - Optional - Keywords associated with the document - **CreationDate** (date) - Optional - The date the document was created - **ModDate** (date) - Optional - The date the document was last modified ``` -------------------------------- ### Buffer pages for post-processing Source: https://pdfkit.org/docs/getting_started.html Enable page buffering to allow switching back to previous pages for tasks like adding page numbers. ```javascript // create a document, and enable bufferPages mode let i; let end; const doc = new PDFDocument({ bufferPages: true}); // add some content... doc.addPage(); // ... doc.addPage(); // see the range of buffered pages const range = doc.bufferedPageRange(); // => { start: 0, count: 2 } for (i = range.start, end = range.start + range.count, range.start <= end; i < end; i++) { doc.switchToPage(i); doc.text(`Page ${i + 1} of ${range.count}`); } // manually flush pages that have been buffered doc.flushPages(); // or, if you are at the end of the document anyway, // doc.end() will call it for you automatically. doc.end(); ``` -------------------------------- ### Cell Options Source: https://pdfkit.org/docs/table.html Lists and describes the available options for configuring individual table cells. ```APIDOC ## Cell options * `text` - The value, will be cast to a string (`null` and `undefined` are not rendered but the cell is still outlined) * `rowSpan` - How many rows this cell covers, follows the same logic as HTML `rowspan` * `colSpan` - How many columns this cell covers, follows the same logic as HTML `colspan` * `padding` - The padding for the cell (default `0.25em`) * `border` - The border for the cell (default `1pt`) * `borderColor` - The border colors for the cell (default `black`) * `font` - Font options for the cell * `backgroundColor` - Set the background color of the cell * `align` - The alignment of the cell text (default `{x: 'left', y: 'top'}`) * `textStroke` - The text stroke (default `0`) * `textStrokeColor` - Sets the text stroke color of the cells text (default `black`) * `textColor` - Sets the text color of the cells text (default `black`) * `type` - Sets the cell type (for accessibility) (default `TD`) * `textOptions` - Sets any text options you wish to provide (such as rotation) * `debug` - Whether to show the debug lines for the cell (default `false`) ``` -------------------------------- ### Create a Push Button Source: https://pdfkit.org/docs/forms.html Adds a push button with custom background color and label. ```javascript var opts = { backgroundColor: 'yellow', label: 'Test Button' }; doc.formPushButton('btn1', 10, 200, 100, 30, opts); ``` -------------------------------- ### Limitations and Testing Source: https://pdfkit.org/docs/forms.html Recommends testing PDF form documents across various platforms and viewers to ensure compatibility. ```APIDOC ## Limitations It is recommended that you test your PDF form documents across all platforms and viewers that you wish to support. ``` -------------------------------- ### Column Options Source: https://pdfkit.org/docs/table.html Lists and describes the options available for configuring table columns, extending cell options. ```APIDOC ## Column options Extends the cell options above with: * `width` - The width of the column (default `*`) * `minWidth` - The minimum width of the column (default `0`) * `maxWidth` - The maximum width of the column (default `Infinity`) ``` -------------------------------- ### Set default document font Source: https://pdfkit.org/docs/getting_started.html Configure the global font for the document during initialization. ```javascript // use Courier font by default const doc = new PDFDocument({font: 'Courier'}); ``` -------------------------------- ### Listen for page added events Source: https://pdfkit.org/docs/getting_started.html Execute code automatically whenever a new page is created. ```javascript doc.on('pageAdded', () => doc.text("Page Title")); ``` -------------------------------- ### Shortcut for Marked Content Elements Source: https://pdfkit.org/docs/accessibility.html Provides a shorthand for creating structure elements that contain only marked content using a closure. ```javascript doc.addStructure(doc.struct('P', () => { doc.text('Hello, world! '); })); ``` ```javascript const myStruct = doc.struct('P'); doc.addStructure(myStruct); const myStructContent = doc.markStructureContent('P'); doc.text('Hello, world! '); doc.endMarkedContent(); myStruct.add(myStructContent); myStruct.end(); ``` -------------------------------- ### Save and Restore Graphics State in PDFKit Source: https://pdfkit.org/docs/vector.html Manage the graphics state using `save` and `restore` methods. `save` pushes the current state (styles and transformations) onto a stack, and `restore` applies the last saved state. ```javascript // Example usage (conceptual, no direct code snippet provided in source) // doc.save(); // doc.fillColor('blue'); // doc.restore(); ``` -------------------------------- ### Pipe PDF output to streams Source: https://pdfkit.org/docs/getting_started.html Direct the document output to a file system stream or an HTTP response object before finalizing. ```javascript doc.pipe(fs.createWriteStream('/path/to/file.pdf')); // write to PDF doc.pipe(res); // HTTP response // add stuff to PDF here using methods described below... // finalize the PDF and end the stream doc.end(); ``` -------------------------------- ### Create a Combo Box Source: https://pdfkit.org/docs/forms.html Adds a combo box field with a predefined list of selectable options. ```javascript opts = { select: ['', 'github', 'bitbucket', 'gitlab'], value: '', defaultValue: '', align: 'left' }; doc.formCombo('ch1', 10, y, 100, 20, opts); ``` -------------------------------- ### Apply Tiling Pattern Fill and Stroke Source: https://pdfkit.org/examples/browserify/browser.html Defines and applies a custom tiling pattern for both fill and stroke operations. The pattern is defined using a specific syntax and can be combined with colors. ```javascript // stroke & fill uncolored tiling pattern var stripe45d = doc.pattern( [1, 1, 4, 4], 3, 3, '1 w 0 1 m 4 5 l s 2 0 m 5 3 l s' ); doc.circle(280, 350, 50).fill([stripe45d, 'blue']); doc .rect(380, 300, 100, 100) .fillColor('lime') .strokeColor([stripe45d, 'orange']) .lineWidth(5) .fillAndStroke(); doc.restore(); ```