### Install tinypdf Source: https://github.com/lulzx/tinypdf/blob/main/README.md Install the tinypdf package using npm. This is the first step to using the library in your project. ```bash npm install tinypdf ``` -------------------------------- ### Generate Professional Invoice PDF with Tinypdf Source: https://context7.com/lulzx/tinypdf/llms.txt Provides a comprehensive example of creating a professional invoice PDF using the tinypdf library. It includes features like headers, company information, itemized tables, totals, and footers. Requires `tinypdf` and `fs` modules. ```typescript import { pdf, measureText } from 'tinypdf' import { writeFileSync } from 'fs' const doc = pdf() doc.page(612, 792, (ctx) => { const margin = 40 const pageWidth = 532 // 612 - 40*2 // Header with blue background ctx.rect(margin, 716, pageWidth, 36, '#2563eb') ctx.text('INVOICE', margin + 15, 726, 24, { color: '#ffffff' }) ctx.text('#INV-2025-001', margin + pageWidth - 100, 728, 12, { color: '#ffffff' }) // Company information (left side) ctx.text('Acme Corporation', margin, 670, 16, { color: '#000000' }) ctx.text('123 Business Street', margin, 652, 11, { color: '#666666' }) ctx.text('New York, NY 10001', margin, 638, 11, { color: '#666666' }) ctx.text('contact@acme.com', margin, 624, 11, { color: '#666666' }) // Bill To (right side) ctx.text('Bill To:', margin + 300, 670, 12, { color: '#666666' }) ctx.text('John Smith', margin + 300, 652, 14, { color: '#000000' }) ctx.text('456 Customer Avenue', margin + 300, 636, 11, { color: '#666666' }) ctx.text('Los Angeles, CA 90001', margin + 300, 622, 11, { color: '#666666' }) // Invoice details ctx.text('Invoice Date: January 15, 2025', margin, 590, 10, { color: '#666666' }) ctx.text('Due Date: February 14, 2025', margin, 576, 10, { color: '#666666' }) // Table header ctx.rect(margin, 540, pageWidth, 25, '#f3f4f6') ctx.text('Description', margin + 10, 548, 11, { color: '#000000' }) ctx.text('Qty', margin + 270, 548, 11, { color: '#000000' }) ctx.text('Price', margin + 340, 548, 11, { color: '#000000' }) ctx.text('Total', margin + 440, 548, 11, { color: '#000000' }) // Table rows const items = [ { desc: 'Website Development', qty: '1', price: '$5,000.00', total: '$5,000.00' }, { desc: 'Hosting (Annual)', qty: '1', price: '$200.00', total: '$200.00' }, { desc: 'Maintenance Package', qty: '12', price: '$150.00', total: '$1,800.00' }, { desc: 'SSL Certificate', qty: '1', price: '$100.00', total: '$100.00' }, ] let y = 515 for (const item of items) { ctx.text(item.desc, margin + 10, y, 11) ctx.text(item.qty, margin + 270, y, 11) ctx.text(item.price, margin + 340, y, 11) ctx.text(item.total, margin + 440, y, 11) ctx.line(margin, y - 15, margin + pageWidth, y - 15, '#e5e7eb', 0.5) y -= 30 } // Totals section const totalsY = y - 20 ctx.line(margin, totalsY + 10, margin + pageWidth, totalsY + 10, '#000000', 1) ctx.text('Subtotal:', margin + 340, totalsY - 15, 11) ctx.text('$7,100.00', margin + 440, totalsY - 15, 11) ctx.text('Tax (8%):', margin + 340, totalsY - 35, 11) ctx.text('$568.00', margin + 440, totalsY - 35, 11) // Total due with blue background ctx.rect(margin + 330, totalsY - 70, 202, 25, '#2563eb') ctx.text('Total Due:', margin + 340, totalsY - 58, 12, { color: '#ffffff' }) ctx.text('$7,668.00', margin + 440, totalsY - 58, 12, { color: '#ffffff' }) // Payment information ctx.text('Payment Methods:', margin, 200, 12, { color: '#333333' }) ctx.text('Bank Transfer: Account #1234567890', margin, 182, 10, { color: '#666666' }) ctx.text('PayPal: payments@acme.com', margin, 166, 10, { color: '#666666' }) // Footer ctx.line(margin, 100, margin + pageWidth, 100, '#e5e7eb', 0.5) ctx.text('Thank you for your business!', margin, 80, 12, { align: 'center', width: pageWidth, color: '#666666' } ) ctx.text('Payment due within 30 days. Late payments subject to 1.5% monthly fee.', margin, 62, 9, { align: 'center', width: pageWidth, color: '#999999' } ) }) const bytes = doc.build() writeFileSync('invoice.pdf', bytes) console.log(`Invoice created: ${bytes.length} bytes`) ``` -------------------------------- ### Draw Filled Rectangles with tinypdf ctx.rect() Source: https://context7.com/lulzx/tinypdf/llms.txt Shows how to use the `ctx.rect()` method in tinypdf to draw filled rectangles on a PDF page. The examples demonstrate creating background elements for headers, table headers, and highlight boxes, as well as drawing multiple colored boxes. The method takes position, dimensions, and a fill color as arguments. ```typescript import { pdf } from 'tinypdf' import { writeFileSync } from 'fs' const doc = pdf() doc.page((ctx) => { // Blue header background ctx.rect(40, 720, 532, 40, '#2563eb') ctx.text('INVOICE', 50, 732, 24, { color: '#ffffff' }) // Light gray table header ctx.rect(40, 600, 532, 25, '#f3f4f6') ctx.text('Description', 50, 608, 11) ctx.text('Amount', 450, 608, 11) // Highlight box ctx.rect(40, 100, 200, 30, '#fef3c7') ctx.text('Important note', 50, 110, 12, { color: '#92400e' }) // Multiple colored boxes ctx.rect(300, 500, 50, 50, '#ef4444') // Red ctx.rect(360, 500, 50, 50, '#22c55e') // Green ctx.rect(420, 500, 50, 50, '#3b82f6') // Blue }) writeFileSync('rectangles.pdf', doc.build()) ``` -------------------------------- ### Draw Lines with tinypdf ctx.line() Source: https://context7.com/lulzx/tinypdf/llms.txt Demonstrates the use of the `ctx.line()` method in tinypdf to draw lines on a PDF page. The examples showcase drawing simple horizontal and vertical lines, lines with custom widths and colors, and diagonal lines. This method is useful for creating separators, borders, and decorative elements. ```typescript import { pdf } from 'tinypdf' import { writeFileSync } from 'fs' const doc = pdf() doc.page((ctx) => { // Simple horizontal line ctx.line(50, 700, 550, 700, '#000000') // Line with custom width ctx.line(50, 680, 550, 680, '#000000', 2.5) // Colored lines ctx.line(50, 650, 550, 650, '#ff0000', 1) // Red, 1pt ctx.line(50, 630, 550, 630, '#0000ff', 0.5) // Blue, 0.5pt // Light gray separator (common for tables) ctx.line(50, 600, 550, 600, '#e5e7eb', 0.5) // Vertical line ctx.line(300, 500, 300, 400, '#333333', 1) // Diagonal line ctx.line(50, 350, 200, 250, '#666666', 1) }) writeFileSync('lines.pdf', doc.build()) ``` -------------------------------- ### Render Text with tinypdf ctx.text() Source: https://context7.com/lulzx/tinypdf/llms.txt Illustrates the usage of the `ctx.text()` method in tinypdf for rendering text on a PDF page. It covers basic text rendering, applying custom colors using hex codes (including short hex formats), and text alignment (center and right) within a specified width. The example also highlights that special characters are automatically escaped. ```typescript import { pdf } from 'tinypdf' import { writeFileSync } from 'fs' const doc = pdf() doc.page((ctx) => { // Basic text rendering ctx.text('Simple text', 50, 750, 12) // Text with custom color (hex format) ctx.text('Red text', 50, 720, 16, { color: '#ff0000' }) ctx.text('Blue text', 50, 690, 16, { color: '#0000ff' }) // Short hex colors work too ctx.text('Green text', 50, 660, 16, { color: '#0f0' }) // Center-aligned text within a box width ctx.text('Centered Title', 50, 620, 24, { align: 'center', width: 500, color: '#333333' }) // Right-aligned text ctx.text('Right aligned', 50, 580, 14, { align: 'right', width: 500 }) // Special characters are escaped automatically ctx.text('Path: C:\Users\file (copy).txt', 50, 540, 12) }) writeFileSync('text-example.pdf', doc.build()) ``` -------------------------------- ### Create PDF Document with tinypdf Source: https://context7.com/lulzx/tinypdf/llms.txt Demonstrates how to create a new PDF document using the `pdf()` function from the tinypdf library. It shows how to add pages with default and custom sizes, render text, and build the final PDF output as a Uint8Array. The output is then saved to a file using Node.js's `writeFileSync`. ```typescript import { pdf } from 'tinypdf' import { writeFileSync } from 'fs' // Create a new PDF document const doc = pdf() // Add a page with default size (612x792 points = US Letter) doc.page((ctx) => { ctx.text('Hello, World!', 50, 700, 24, { color: '#000000' }) }) // Add a page with custom size (A4: 595x842 points) doc.page(595, 842, (ctx) => { ctx.text('A4 Page', 50, 800, 18) }) // Build and save the PDF const bytes = doc.build() // Returns Uint8Array writeFileSync('output.pdf', bytes) // Output: Creates a valid PDF file with 2 pages ``` -------------------------------- ### ctx.link() - Add Clickable URLs Source: https://context7.com/lulzx/tinypdf/llms.txt Creates clickable URL annotations over a specified rectangular area. Can be combined with `text()` to create visible hyperlink text. Supports an optional underline style. ```APIDOC ## ctx.link() - Add Clickable URLs ### Description The `link()` method creates a clickable URL annotation over a rectangular area. Combine with `text()` to create clickable text links. The optional underline parameter draws a colored line under the link. ### Method ```typescript ctx.link(url: string, x: number, y: number, width: number, height: number, options?: { underline?: string }) ``` ### Parameters * **url** (string) - The URL to link to. * **x** (number) - The x-coordinate for the top-left corner of the link area. * **y** (number) - The y-coordinate for the top-left corner of the link area. * **width** (number) - The width of the clickable link area. * **height** (number) - The height of the clickable link area. * **options** (object, optional) - Configuration options. * **underline** (string, optional) - The color of the underline to draw (e.g., '#0066cc'). ### Request Example ```typescript import { pdf, measureText } from 'tinypdf' import { writeFileSync } from 'fs' const doc = pdf() doc.page((ctx) => { // Basic link (invisible clickable area) ctx.text('Click here for Google', 50, 700, 14, { color: '#0066cc' }) ctx.link('https://google.com', 50, 696, 150, 20) // Link with underline (common hyperlink style) const linkText = 'Visit GitHub' const fontSize = 14 ctx.text(linkText, 50, 660, fontSize, { color: '#0066cc' }) ctx.link('https://github.com', 50, 656, measureText(linkText, fontSize), 18, { underline: '#0066cc' }) // Multiple links on same page const links = [ { text: 'Documentation', url: 'https://docs.example.com' }, { text: 'Support', url: 'https://support.example.com' }, { text: 'Contact Us', url: 'https://example.com/contact' }, ] let y = 600 for (const link of links) { ctx.text(link.text, 50, y, 12, { color: '#0066cc' }) ctx.link(link.url, 50, y - 4, measureText(link.text, 12), 16, { underline: '#0066cc' }) y -= 30 } }) writeFileSync('links.pdf', doc.build()) ``` ``` -------------------------------- ### Create Clickable URLs in PDF using TinyPDF Source: https://context7.com/lulzx/tinypdf/llms.txt Shows how to create clickable URL annotations in a PDF using the `ctx.link()` method. This method can be combined with `ctx.text()` to create visible links, and an optional `underline` parameter can be used to draw a colored line beneath the link. ```typescript import { pdf, measureText } from 'tinypdf' import { writeFileSync } from 'fs' const doc = pdf() doc.page((ctx) => { // Basic link (invisible clickable area) ctx.text('Click here for Google', 50, 700, 14, { color: '#0066cc' }) ctx.link('https://google.com', 50, 696, 150, 20) // Link with underline (common hyperlink style) const linkText = 'Visit GitHub' const fontSize = 14 ctx.text(linkText, 50, 660, fontSize, { color: '#0066cc' }) ctx.link('https://github.com', 50, 656, measureText(linkText, fontSize), 18, { underline: '#0066cc' }) // Multiple links on same page const links = [ { text: 'Documentation', url: 'https://docs.example.com' }, { text: 'Support', url: 'https://support.example.com' }, { text: 'Contact Us', url: 'https://example.com/contact' }, ] let y = 600 for (const link of links) { ctx.text(link.text, 50, y, 12, { color: '#0066cc' }) ctx.link(link.url, 50, y - 4, measureText(link.text, 12), 16, { underline: '#0066cc' }) y -= 30 } }) writeFileSync('links.pdf', doc.build()) ``` -------------------------------- ### Convert Markdown to PDF with Tinypdf Source: https://context7.com/lulzx/tinypdf/llms.txt Demonstrates converting markdown text into a PDF document using the tinypdf library. It utilizes the `markdown` function and `writeFileSync` to save the PDF. No external dependencies are required beyond tinypdf. ```javascript import { pdf, markdown } from 'tinypdf' import { writeFileSync } from 'fs' const fullPdf = markdown('# Hello World\n\nThis is a **bold** text.') writeFileSync('documentation.pdf', fullPdf) // Custom page size and margins const customPdf = markdown('# Custom Layout\n\nThis document uses A4 size with wider margins. - Better for printing - European standard ', { width: 595, // A4 width in points height: 842, // A4 height in points margin: 90 // Wider margins (default is 72) }) writeFileSync('custom-layout.pdf', customPdf) // Long content automatically paginates const longContent = Array(50).fill('\n## Section\n\nThis is a paragraph of text that will be part of a very long document.\nThe markdown function automatically handles pagination when content\nexceeds the page height. - Item one - Item two - Item three ').join('\n') const multiPagePdf = markdown(longContent) writeFileSync('multi-page.pdf', multiPagePdf) ``` -------------------------------- ### Create a basic PDF with text and shapes Source: https://github.com/lulzx/tinypdf/blob/main/README.md Generates a PDF document with a blue rectangle, white text, and a black line. It demonstrates the core drawing capabilities of the library using a callback function for page content. The output is saved to 'output.pdf'. ```typescript import { pdf } from 'tinypdf' import { writeFileSync } from 'fs' const doc = pdf() doc.page((ctx) => { ctx.rect(50, 700, 200, 40, '#2563eb') // blue rectangle ctx.text('Hello PDF!', 60, 712, 24, { color: '#ffffff' }) ctx.line(50, 680, 250, 680, '#000000', 1) // black line }) writeFileSync('output.pdf', doc.build()) ``` -------------------------------- ### markdown() - Convert Markdown to PDF Source: https://context7.com/lulzx/tinypdf/llms.txt Converts a markdown string directly into a PDF document. Supports headers (h1-h3), lists (bulleted and numbered), horizontal rules, and paragraphs with automatic word wrapping and pagination. ```APIDOC ## markdown() - Convert Markdown to PDF ### Description The `markdown()` function converts a markdown string directly to a PDF. It supports headers (h1-h3), bullet lists, numbered lists, horizontal rules, and paragraphs with automatic word wrapping and pagination. ### Method ```typescript markdown(markdownString: string): Uint8Array ``` ### Parameters * **markdownString** (string) - The markdown content to convert. ### Returns * (Uint8Array) - The generated PDF document as a Uint8Array. ### Request Example ```typescript import { markdown } from 'tinypdf' import { writeFileSync } from 'fs' // Simple markdown to PDF const simplePdf = markdown(` # Welcome to TinyPDF This is a simple markdown document converted to PDF. `) writeFileSync('simple.pdf', simplePdf) // Full-featured markdown document const fullPdf = markdown(` # Project Documentation A comprehensive guide to using our API. ## Getting Started Follow these steps to begin: 1. Install the package 2. Import the module 3. Create your first document ## Features - Lightweight and fast - Zero dependencies - TypeScript support - Cross-platform ### Code Examples The library provides simple methods for PDF creation. --- ## Advanced Usage For complex documents, combine multiple features: - Headers for structure - Lists for organization - Rules for separation `) writeFileSync('full.pdf', fullPdf) ``` ``` -------------------------------- ### Convert Markdown to PDF Source: https://github.com/lulzx/tinypdf/blob/main/README.md Transforms Markdown-formatted text into a PDF document. This feature simplifies the creation of documents with basic rich text formatting like headers, lists, and horizontal rules. The output PDF is saved to 'output.pdf'. ```typescript import { markdown } from 'tinypdf' import { writeFileSync } from 'fs' const pdf = markdown(` # Hello World A minimal PDF from markdown. ## Features - Headers (h1, h2, h3) - Bullet lists - Numbered lists - Horizontal rules --- Automatic word wrapping and pagination included. `) writeFileSync('output.pdf', pdf) ``` -------------------------------- ### pdf() - Create a PDF Document Source: https://context7.com/lulzx/tinypdf/llms.txt The `pdf()` function initializes a new PDF document builder, returning a `PDFBuilder` object. This object allows for adding pages and constructing the final PDF output. The document defaults to PDF version 1.4 and uses Helvetica as the font. ```APIDOC ## pdf() - Create a PDF Document ### Description Creates a new PDF document builder. ### Method `pdf()` ### Endpoint N/A (This is a library function) ### Parameters None ### Request Example ```typescript import { pdf } from 'tinypdf' import { writeFileSync } from 'fs' const doc = pdf() doc.page((ctx) => { ctx.text('Hello, World!', 50, 700, 24, { color: '#000000' }) }) const bytes = doc.build() writeFileSync('output.pdf', bytes) ``` ### Response #### Success Response (PDFBuilder Object) - **PDFBuilder Object**: An object with methods to manipulate and build the PDF. #### Response Example ```javascript // Returns a PDFBuilder object { page: Function, build: Function } ``` ``` -------------------------------- ### ctx.rect() - Draw Filled Rectangles Source: https://context7.com/lulzx/tinypdf/llms.txt The `rect()` method draws a filled rectangle on the PDF page. You can specify its position, dimensions, and fill color. This is useful for backgrounds, headers, and visual elements. ```APIDOC ## ctx.rect() - Draw Filled Rectangles ### Description Draws a filled rectangle at the specified position with given dimensions and fill color. ### Method `ctx.rect(x: number, y: number, width: number, height: number, color: string): void` ### Endpoint N/A (This is a method of the PDF context object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Parameters are passed directly to the function) #### Function Parameters - **x** (number) - Required - The x-coordinate of the rectangle's top-left corner. - **y** (number) - Required - The y-coordinate of the rectangle's top-left corner. - **width** (number) - Required - The width of the rectangle. - **height** (number) - Required - The height of the rectangle. - **color** (string) - Required - The fill color of the rectangle in hex format (e.g., '#2563eb'). ### Request Example ```typescript ctx.rect(40, 720, 532, 40, '#2563eb') ``` ### Response #### Success Response (void) This method does not return a value; it modifies the PDF context. #### Response Example N/A ``` -------------------------------- ### Convert Markdown to PDF using TinyPDF Source: https://context7.com/lulzx/tinypdf/llms.txt Demonstrates the `markdown()` function, which converts a markdown string directly into a PDF document. It supports common markdown elements like headers (h1-h3), lists (bulleted and numbered), horizontal rules, and paragraphs, with automatic word wrapping and pagination. ```typescript import { markdown } from 'tinypdf' import { writeFileSync } from 'fs' // Simple markdown to PDF const simplePdf = markdown(` # Welcome to TinyPDF This is a simple markdown document converted to PDF. `) writeFileSync('simple.pdf', simplePdf) // Full-featured markdown document const fullPdf = markdown(` # Project Documentation A comprehensive guide to using our API. ## Getting Started Follow these steps to begin: 1. Install the package 2. Import the module 3. Create your first document ## Features - Lightweight and fast - Zero dependencies - TypeScript support - Cross-platform ### Code Examples The library provides simple methods for PDF creation. --- ## Advanced Usage For complex documents, combine multiple features: - Headers for structure - Lists for organization - Rules for separation `) writeFileSync('full.pdf', fullPdf) ``` -------------------------------- ### measureText() - Calculate Text Width Source: https://context7.com/lulzx/tinypdf/llms.txt Calculates the width of a given string in PDF points for a specified font size. Essential for layout calculations, text alignment, and positioning interactive elements. ```APIDOC ## measureText() - Calculate Text Width ### Description The `measureText()` function returns the width of a string in points for a given font size. This is essential for text alignment, link positioning, and layout calculations. It uses Helvetica character widths. ### Method ```typescript measureText(text: string, fontSize: number): number ``` ### Parameters * **text** (string) - The string to measure. * **fontSize** (number) - The font size in points. ### Returns * (number) - The calculated width of the text in PDF points. ### Request Example ```typescript import { measureText, pdf } from 'tinypdf' import { writeFileSync } from 'fs' // Basic width measurement const width1 = measureText('Hello', 12) console.log(`"Hello" at 12pt = ${width1.toFixed(2)}pt`) // ~27.34pt const width2 = measureText('Hello World', 24) console.log(`"Hello World" at 24pt = ${width2.toFixed(2)}pt`) // ~133.34pt // Empty string returns 0 console.log(measureText('', 12)) // 0 // Width scales linearly with font size const w12 = measureText('Test', 12) const w24 = measureText('Test', 24) console.log(w24 / w12) // 2.0 // Practical usage: right-align text const doc = pdf() doc.page((ctx) => { const pageWidth = 612 const margin = 50 const text = 'Right-aligned price: $1,234.56' const fontSize = 12 const textWidth = measureText(text, fontSize) const x = pageWidth - margin - textWidth ctx.text(text, x, 700, fontSize) }) writeFileSync('measured.pdf', doc.build()) // Practical usage: center text manually const centerText = 'Centered Heading' const centerWidth = measureText(centerText, 18) const centerX = (612 - centerWidth) / 2 console.log(`Center X position: ${centerX.toFixed(2)}`) ``` ``` -------------------------------- ### ctx.text() - Render Text Source: https://context7.com/lulzx/tinypdf/llms.txt The `text()` method within a PDF context (`ctx`) renders text at a specified position. It supports customization of font size, color (hex format), alignment, and width for text wrapping. Special characters are automatically escaped. ```APIDOC ## ctx.text() - Render Text ### Description Renders text at a specified position with customizable font size, color, and alignment. ### Method `ctx.text(x: number, y: number, text: string, size: number, options?: { color?: string, align?: 'left' | 'center' | 'right', width?: number }): void` ### Endpoint N/A (This is a method of the PDF context object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Parameters are passed directly to the function) #### Function Parameters - **x** (number) - Required - The x-coordinate for the text's starting position. - **y** (number) - Required - The y-coordinate for the text's starting position. - **text** (string) - Required - The text content to render. - **size** (number) - Required - The font size for the text. - **options** (object) - Optional - Configuration options for the text. - **color** (string) - Optional - The text color in hex format (e.g., '#ff0000'). Defaults to '#000000'. - **align** (string) - Optional - Text alignment ('left', 'center', 'right'). Defaults to 'left'. - **width** (number) - Optional - The maximum width for text wrapping. Used with `align`. ### Request Example ```typescript ctx.text('Hello, World!', 50, 700, 24, { color: '#000000', align: 'center', width: 500 }) ``` ### Response #### Success Response (void) This method does not return a value; it modifies the PDF context. #### Response Example N/A ``` -------------------------------- ### Add clickable links to a PDF Source: https://github.com/lulzx/tinypdf/blob/main/README.md Adds a hyperlink to a PDF page. It renders text and then overlays a clickable link area with an optional underline. The 'measureText' function is used to accurately determine the link's bounding box based on the text and font size. ```typescript import { pdf, measureText } from 'tinypdf' doc.page((ctx) => { const text = 'Visit Example.com' const y = 700 ctx.text(text, 50, y, 14, { color: '#0066cc' }) ctx.link('https://example.com', 50, y - 4, measureText(text, 14), 18, { underline: '#0066cc' }) }) ``` -------------------------------- ### ctx.image() - Embed JPEG Images Source: https://context7.com/lulzx/tinypdf/llms.txt Embeds JPEG images into the PDF document at specified coordinates and dimensions. Supports only JPEG format and automatically extracts image dimensions. ```APIDOC ## ctx.image() - Embed JPEG Images ### Description The `image()` method embeds a JPEG image at the specified position and dimensions. Only JPEG format is supported (not PNG, GIF, or SVG). Image dimensions are extracted automatically from the JPEG header. ### Method ```typescript ctx.image(image: Uint8Array, x: number, y: number, width: number, height: number) ``` ### Parameters * **image** (Uint8Array) - The JPEG image data as a Uint8Array. * **x** (number) - The x-coordinate for the top-left corner of the image. * **y** (number) - The y-coordinate for the top-left corner of the image. * **width** (number) - The desired width of the image in PDF points. * **height** (number) - The desired height of the image in PDF points. ### Request Example ```typescript import { pdf } from 'tinypdf' import { readFileSync, writeFileSync } from 'fs' const doc = pdf() doc.page((ctx) => { // Load JPEG image as Uint8Array const logo = new Uint8Array(readFileSync('company-logo.jpg')) const photo = new Uint8Array(readFileSync('product-photo.jpg')) const signature = new Uint8Array(readFileSync('signature.jpg')) // Place logo at top-left (100x50 points) ctx.image(logo, 50, 720, 100, 50) // Product photo in the middle (200x150 points) ctx.image(photo, 200, 500, 200, 150) // Small signature at bottom (80x30 points) ctx.image(signature, 400, 100, 80, 30) // Add caption under image ctx.text('Product Photo', 200, 480, 10, { color: '#666666' }) }) writeFileSync('images.pdf', doc.build()) ``` ### Response This method does not return a value directly, but modifies the PDF context. ### Notes * Images are stored with DCTDecode filter (native JPEG compression). * The PDF file size will increase based on the size of the embedded images. ``` -------------------------------- ### ctx.line() - Draw Lines Source: https://context7.com/lulzx/tinypdf/llms.txt The `line()` method draws a stroked line between two points on the PDF page. You can customize the line's color and width. This is useful for separators, borders, and decorative elements. ```APIDOC ## ctx.line() - Draw Lines ### Description Draws a stroked line between two points with customizable color and width. ### Method `ctx.line(x1: number, y1: number, x2: number, y2: number, color: string, width?: number): void` ### Endpoint N/A (This is a method of the PDF context object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Parameters are passed directly to the function) #### Function Parameters - **x1** (number) - Required - The x-coordinate of the starting point. - **y1** (number) - Required - The y-coordinate of the starting point. - **x2** (number) - Required - The x-coordinate of the ending point. - **y2** (number) - Required - The y-coordinate of the ending point. - **color** (string) - Required - The color of the line in hex format (e.g., '#000000'). - **width** (number) - Optional - The width of the line in points. Defaults to 1. ### Request Example ```typescript ctx.line(50, 700, 550, 700, '#000000', 2.5) ``` ### Response #### Success Response (void) This method does not return a value; it modifies the PDF context. #### Response Example N/A ``` -------------------------------- ### Embed JPEG Images in PDF using TinyPDF Source: https://context7.com/lulzx/tinypdf/llms.txt Demonstrates how to embed JPEG images into a PDF document at specified positions and dimensions using the `ctx.image()` method. It requires image files to be loaded as Uint8Array and supports only JPEG format. The dimensions are automatically extracted from the JPEG header. ```typescript import { pdf } from 'tinypdf' import { readFileSync, writeFileSync } from 'fs' const doc = pdf() doc.page((ctx) => { // Load JPEG image as Uint8Array const logo = new Uint8Array(readFileSync('company-logo.jpg')) const photo = new Uint8Array(readFileSync('product-photo.jpg')) const signature = new Uint8Array(readFileSync('signature.jpg')) // Place logo at top-left (100x50 points) ctx.image(logo, 50, 720, 100, 50) // Product photo in the middle (200x150 points) ctx.image(photo, 200, 500, 200, 150) // Small signature at bottom (80x30 points) ctx.image(signature, 400, 100, 80, 30) // Add caption under image ctx.text('Product Photo', 200, 480, 10, { color: '#666666' }) }) writeFileSync('images.pdf', doc.build()) // Note: Images are stored with DCTDecode filter (native JPEG compression) // The PDF will be larger depending on image file sizes ``` -------------------------------- ### Add JPEG images to a PDF Source: https://github.com/lulzx/tinypdf/blob/main/README.md Incorporates a JPEG image into a PDF page. The image is read from a file as a Uint8Array and then placed on the document at specified coordinates and dimensions. Assumes 'logo.jpg' exists in the project directory. ```typescript import { readFileSync } from 'fs' doc.page((ctx) => { const logo = new Uint8Array(readFileSync('logo.jpg')) ctx.image(logo, 50, 700, 100, 50) }) ``` -------------------------------- ### Measure text width Source: https://github.com/lulzx/tinypdf/blob/main/README.md Calculates the width of a given string at a specific font size in PDF points. This utility function is useful for precise layout calculations, such as positioning links or other elements relative to text. ```typescript import { measureText } from 'tinypdf' measureText('Hello', 12) // => 27.34 (points) ``` -------------------------------- ### Generate PDF Invoice with tinypdf in TypeScript Source: https://github.com/lulzx/tinypdf/blob/main/README.md This code snippet uses the tinypdf library to generate a PDF invoice. It defines page dimensions, margins, and content including headers, company and billing details, an itemized table with dynamic data, and final totals. The generated PDF is then saved to a file named 'invoice.pdf'. ```typescript import { pdf } from 'tinypdf' import { writeFileSync } from 'fs' const doc = pdf() doc.page(612, 792, (p) => { const margin = 40, pw = 532 // Header p.rect(margin, 716, pw, 36, '#2563eb') p.text('INVOICE', 55, 726, 24, { color: '#fff' }) p.text('#INV-2025-001', 472, 728, 12, { color: '#fff' }) // Company & billing info p.text('Acme Corporation', margin, 670, 16) p.text('123 Business Street', margin, 652, 11, { color: '#666' }) p.text('New York, NY 10001', margin, 638, 11, { color: '#666' }) p.text('Bill To:', 340, 670, 12, { color: '#666' }) p.text('John Smith', 340, 652, 14) p.text('456 Customer Ave', 340, 636, 11, { color: '#666' }) p.text('Los Angeles, CA 90001', 340, 622, 11, { color: '#666' }) // Table p.rect(margin, 560, pw, 25, '#f3f4f6') p.text('Description', 50, 568, 11) p.text('Qty', 310, 568, 11) p.text('Price', 380, 568, 11) p.text('Total', 480, 568, 11) const items = [ ['Website Development', '1', '$5,000.00', '$5,000.00'], ['Hosting (Annual)', '1', '$200.00', '$200.00'], ['Maintenance Package', '12', '$150.00', '$1,800.00'], ] let y = 535 for (const [desc, qty, price, total] of items) { p.text(desc, 50, y, 11) p.text(qty, 310, y, 11) p.text(price, 380, y, 11) p.text(total, 480, y, 11) p.line(margin, y - 15, margin + pw, y - 15, '#e5e7eb', 0.5) y -= 30 } // Totals p.line(margin, y, margin + pw, y, '#000', 1) p.text('Subtotal:', 380, y - 25, 11) p.text('$7,000.00', 480, y - 25, 11) p.text('Tax (8%):', 380, y - 45, 11) p.text('$560.00', 480, y - 45, 11) p.rect(370, y - 75, 202, 25, '#2563eb') p.text('Total Due:', 380, y - 63, 12, { color: '#fff' }) p.text('$7,560.00', 480, y - 63, 12, { color: '#fff' }) // Footer p.text('Thank you for your business!', margin, 80, 12, { align: 'center', width: pw, color: '#666' }) p.text('Payment due within 30 days', margin, 62, 10, { align: 'center', width: pw, color: '#999' }) }) writeFileSync('invoice.pdf', doc.build()) ``` -------------------------------- ### Calculate Text Width in PDF using TinyPDF Source: https://context7.com/lulzx/tinypdf/llms.txt Explains how to use the `measureText()` function to calculate the width of a string in PDF points for a given font size. This is crucial for text alignment, positioning links, and other layout calculations. It uses Helvetica character widths and scales linearly with font size. ```typescript import { measureText, pdf } from 'tinypdf' import { writeFileSync } from 'fs' // Basic width measurement const width1 = measureText('Hello', 12) console.log(`"Hello" at 12pt = ${width1.toFixed(2)}pt`) // ~27.34pt const width2 = measureText('Hello World', 24) console.log(`"Hello World" at 24pt = ${width2.toFixed(2)}pt`) // ~133.34pt // Empty string returns 0 console.log(measureText('', 12)) // 0 // Width scales linearly with font size const w12 = measureText('Test', 12) const w24 = measureText('Test', 24) console.log(w24 / w12) // 2.0 // Practical usage: right-align text const doc = pdf() doc.page((ctx) => { const pageWidth = 612 const margin = 50 const text = 'Right-aligned price: $1,234.56' const fontSize = 12 const textWidth = measureText(text, fontSize) const x = pageWidth - margin - textWidth ctx.text(text, x, 700, fontSize) }) writeFileSync('measured.pdf', doc.build()) // Practical usage: center text manually const centerText = 'Centered Heading' const centerWidth = measureText(centerText, 18) const centerX = (612 - centerWidth) / 2 console.log(`Center X position: ${centerX.toFixed(2)}`) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.