### Install PDFDancer TypeScript Client Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Install the PDFDancer TypeScript client package using npm. This package requires Node.js version 18 or higher. ```bash npm install pdfdancer-client-typescript ``` -------------------------------- ### Project Development and Testing Commands Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Provides a set of common npm commands for managing the PDFDancer client project. These include installing dependencies, building the project, running various test suites (all, unit, E2E), and linting the code. ```bash # Install dependencies npm install # Build the project npm run build # Run all tests npm test # Run only unit tests npm run test:unit # Run e2e tests (requires fixtures and a running server) npm run test:e2e # Run linter npm run lint ``` -------------------------------- ### Find Available Fonts using PDFDancer Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt Demonstrates how to search for fonts matching a specific name pattern on the PDFDancer service. The example shows finding fonts by name and size, and then using a found font to style a paragraph. Dependencies include the PDFDancer library. ```typescript async function findFonts(pdf: PDFDancer) { // Find fonts matching name const helveticaFonts = await pdf.findFonts('Helvetica', 12); for (const font of helveticaFonts) { console.log('Font name:', font.name); console.log('Font size:', font.size); } // Search for Arial fonts const arialFonts = await pdf.findFonts('Arial', 14); // Use found font if (helveticaFonts.length > 0) { await pdf.page(0).newParagraph() .text('Using found font') .font(helveticaFonts[0]) .at(100, 400) .apply(); } } ``` -------------------------------- ### Create and Use Colors in TypeScript Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt Illustrates how to create and utilize the `Color` class from the `pdfdancer-client-typescript` library for defining colors in PDFs. Examples include creating standard RGB colors (0-255 range) and colors with an alpha channel for transparency, and then applying these colors to text elements within paragraphs. The `Color` class is imported from the library. ```typescript import { Color } from 'pdfdancer-client-typescript'; async function useColors(pdf: PDFDancer) { // RGB colors (values 0-255) const black = new Color(0, 0, 0); const white = new Color(255, 255, 255); const red = new Color(255, 0, 0); const green = new Color(0, 128, 0); const blue = new Color(0, 0, 255); // Color with alpha channel (transparency) const semiTransparent = new Color(100, 100, 100, 128); // 50% opacity const fullyOpaque = new Color(50, 50, 50, 255); // 100% opacity // Use colors in paragraphs await pdf.page(0).newParagraph() .text('Red warning text') .font(StandardFonts.HELVETICA_BOLD, 14) .color(red) .at(100, 500) .apply(); // Gray text const gray = new Color(128, 128, 128); await pdf.page(0).newParagraph() .text('Gray footer text') .font(StandardFonts.HELVETICA, 10) .color(gray) .at(72, 50) .apply(); } ``` -------------------------------- ### Save and Export PDF using PDFDancer Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt Provides examples for downloading a modified PDF as bytes or saving it to disk using the PDFDancer client. It covers obtaining PDF bytes, saving to a file in Node.js, triggering a download in the browser, and streaming the PDF as an HTTP response in a Node.js server. Dependencies include the PDFDancer library and potentially Node.js `express` or browser `Blob`, `URL`, `document` APIs. ```typescript async function savePdf(pdf: PDFDancer) { // Get PDF as bytes (works in Node.js and browser) const pdfBytes = await pdf.getBytes(); console.log('PDF size:', pdfBytes.length, 'bytes'); // Save to file in Node.js await pdf.save('output.pdf'); // Browser: trigger download const blob = new Blob([pdfBytes], { type: 'application/pdf' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = 'modified.pdf'; link.click(); URL.revokeObjectURL(url); // Stream to HTTP response (Node.js server) import { Response } from 'express'; function sendPdf(res: Response, pdfBytes: Uint8Array) { res.contentType('application/pdf'); res.send(Buffer.from(pdfBytes)); } } ``` -------------------------------- ### Handle PDFDancer Client Exceptions in TypeScript Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt Demonstrates how to catch and handle various exceptions thrown by the PDFDancer client library. This includes specific error types like FontNotFoundException, ValidationException, SessionException, HttpClientException, and the general PdfDancerException, allowing for targeted error recovery and logging. It assumes the `pdfdancer-client-typescript` library is installed and imported. ```typescript import { PdfDancerException, ValidationException, HttpClientException, SessionException, FontNotFoundException } from 'pdfdancer-client-typescript'; async function robustPdfOperation() { try { const pdf = await PDFDancer.open(pdfBytes); await pdf.page(0).newParagraph() .text('Hello World') .font('NonExistentFont', 12) .at(100, 100) .apply(); } catch (error) { if (error instanceof FontNotFoundException) { console.error('Font not available:', error.message); // Fallback to standard font } else if (error instanceof ValidationException) { console.error('Invalid input provided:', error.message); // Fix input parameters } else if (error instanceof SessionException) { console.error('Session error:', error.message); // Retry session creation } else if (error instanceof HttpClientException) { console.error('API communication error:', error.message); console.error('Status code:', error.statusCode); console.error('Response:', error.response); // Check network or API status } else if (error instanceof PdfDancerException) { console.error('General PDFDancer error:', error.message); console.error('Cause:', error.cause); } else { console.error('Unexpected error:', error); } } } ``` -------------------------------- ### Manage PDF Pages Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Access and manipulate individual pages within a PDF document. This includes retrieving a specific page by its index, getting all pages, and deleting a page. Page indices are zero-based. ```typescript const page = pdf.page(0); const allPages = await pdf.pages(); // Array await page.delete(); // Remove the page from the document ``` -------------------------------- ### Work with PDF Form Fields using pdfdancer-client-typescript Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt This example demonstrates how to interact with AcroForm fields in a PDF document using pdfdancer-client-typescript. It shows how to select all form fields, iterate through them to log their names, values, and types, and fill specific text fields. It also covers finding fields by name, selecting fields on a particular page or at specific coordinates, and deleting form fields. ```typescript async function workWithForms(pdf: PDFDancer) { // Find all form fields in document const fields = await pdf.selectFormFields(); for (const field of fields) { console.log('Field name:', field.name); console.log('Field value:', field.value); console.log('Field type:', field.type); // Fill text fields if (field.name === 'firstName') { await field.fill('Jane'); } if (field.name === 'lastName') { await field.fill('Doe'); } } // Find specific fields by name const emailFields = await pdf.selectFieldsByName('email'); if (emailFields.length > 0) { await emailFields[0].fill('jane.doe@example.com'); } // Find form fields on specific page const pageFields = await pdf.page(0).selectFormFields(); // Find form fields at coordinates const fieldsAtPoint = await pdf.page(0).selectFormFieldsAt(200, 300); // Delete a form field if (fields.length > 0) { await fields[0].delete(); } } ``` -------------------------------- ### Search for Paragraphs by Text in PDFDancer Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt Shows how to locate paragraph elements within a PDF document using the PDFDancer TypeScript client. It supports finding paragraphs by text content (exact match, starting with, or regex matching) and by specific coordinates on a given page or across the entire document. ```typescript async function findParagraphs(pdf: PDFDancer) { // Find all paragraphs starting with specific text on page 0 const headings = await pdf.page(0).selectParagraphsStartingWith('Executive Summary'); if (headings.length > 0) { const heading = headings[0]; console.log('Found heading at:', heading.position.getX(), heading.position.getY()); console.log('Text content:', heading.getText()); console.log('Font:', heading.getFontName(), 'Size:', heading.getFontSize()); } // Find paragraphs matching regex pattern const datePattern = await pdf.page(0).selectParagraphsMatching('\\d{4}-\\d{2}-\\d{2}'); // Find all paragraphs on a page const allParagraphs = await pdf.page(0).selectParagraphs(); // Find paragraphs at specific coordinates const paraAtPoint = await pdf.page(0).selectParagraphsAt(200, 400); // Search across all pages const allParagraphsInDoc = await pdf.selectParagraphs(); } ``` -------------------------------- ### Search Text Lines in PDF using PDFDancer Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt Demonstrates how to find individual text lines within a PDF document using the PDFDancer client. It includes methods for selecting all lines, lines starting with specific text, lines matching a regex pattern, lines at specific coordinates, and editing existing text lines. Dependencies include the PDFDancer library. ```typescript async function searchTextLines(pdf: PDFDancer) { // Find all text lines on page 0 const lines = await pdf.page(0).selectTextLines(); for (const line of lines) { console.log('Line text:', line.getText()); console.log('Font:', line.getFontName(), 'Size:', line.getFontSize()); // Check text status (font type, modification state) const status = line.objectRef().status; if (status) { console.log('Font type:', status.getFontType()); console.log('Modified:', status.isModified()); console.log('Encodable:', status.isEncodable()); const rec = status.getFontRecommendation(); console.log('Recommended font:', rec.getFontName(), 'Score:', rec.getSimilarityScore()); } } // Find lines starting with specific text const headers = await pdf.page(0).selectTextLinesStartingWith('Chapter'); // Find lines matching regex pattern const phoneNumbers = await pdf.page(0).selectTextLinesMatching('\\d{3}-\\d{3}-\\d{4}'); // Find lines at specific coordinates const linesAtPoint = await pdf.page(0).selectTextLinesAt(150, 400); // Edit a text line if (lines.length > 0) { const result = await lines[0].edit() .text('Updated line text') .apply(); } // Search all lines in document const allLines = await pdf.selectLines(); } ``` -------------------------------- ### Get Text Object Status Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Retrieve status information for text objects like paragraphs and lines, including font type, modification state, and encodability. Font recommendations may also be available if text cannot be rendered with its current font. ```typescript const lines = await pdf.page(0).selectTextLines(); const line = lines[0]; // Check text object status const status = line.objectRef().status; if (status) { console.log('Font type:', status.getFontType()); // SYSTEM, STANDARD, or EMBEDDED console.log('Is modified:', status.isModified()); // true if text was changed console.log('Is encodable:', status.isEncodable()); // true if text can be rendered // Get font recommendation if available const recommendation = status.getFontRecommendation(); console.log('Recommended font:', recommendation.getFontName()); console.log('Similarity score:', recommendation.getSimilarityScore()); } ``` -------------------------------- ### Register Custom Fonts in PDF using PDFDancer Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt Shows how to upload and register TrueType font files for use in PDF text operations with the PDFDancer client. It supports registering fonts from file paths, byte arrays, and browser File objects. The example also demonstrates using a registered font to style text. Dependencies include the PDFDancer library and potentially Node.js `fs` module or browser DOM APIs. ```typescript async function registerFonts(pdf: PDFDancer) { // Register font from file path const fontName1 = await pdf.registerFont('fonts/Roboto-Regular.ttf'); console.log('Registered font:', fontName1); // Register font from bytes const fontBytes = new Uint8Array(await fs.readFile('fonts/OpenSans-Bold.ttf')); const fontName2 = await pdf.registerFont(fontBytes); // Register font from File object (browser) const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement; if (fileInput.files && fileInput.files[0]) { const fontName3 = await pdf.registerFont(fileInput.files[0]); } // Use registered font in paragraph await pdf.page(0).newParagraph() .text('Text using custom font') .font(fontName1, 14) .at(100, 500) .apply(); } ``` -------------------------------- ### Create New Blank PDF with PDFDancer Client Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt Illustrates how to create a new, blank PDF document using the PDFDancer TypeScript client. This function allows for specifying page size, orientation, and initial page count, or creating a default A4 portrait PDF with one page. It optionally accepts an API token and base URL. ```typescript import { PDFDancer, Orientation } from 'pdfdancer-client-typescript'; async function createBlankPdf() { // Create a new PDF with custom options const pdf = await PDFDancer.new( { pageSize: 'A4', orientation: Orientation.PORTRAIT, initialPageCount: 3 }, 'your-api-token', 'https://api.pdfdancer.com' ); // Create with defaults (A4, portrait, 1 page) const simplePdf = await PDFDancer.new(); return pdf; } ``` -------------------------------- ### Configure PDF Dancer Client Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Initialize the PDF Dancer client with optional authentication token, base URL, and request timeout. Authentication can be managed via environment variables for convenience. The base URL can be overridden for different environments. ```typescript const pdf = await PDFDancer.open( pdfData, // Uint8Array, File, or ArrayBuffer token, // Optional: defaults to process.env.PDFDANCER_TOKEN baseUrl, // Optional: defaults to process.env.PDFDANCER_BASE_URL or https://api.pdfdancer.com timeout // Optional request timeout in ms (default: 30000) ); ``` -------------------------------- ### Open Existing PDF with PDFDancer Client Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt Demonstrates how to open an existing PDF document using the PDFDancer TypeScript client. This function reads a PDF file into memory and establishes a manipulation session with the PDFDancer API. It requires the PDF file content and optionally accepts an API token, base URL, and timeout. ```typescript import { PDFDancer } from 'pdfdancer-client-typescript'; import { promises as fs } from 'node:fs'; async function openPdf() { // Read PDF file into memory const pdfBytes = await fs.readFile('invoice.pdf'); // Open the PDF with authentication // Token can be provided explicitly or via PDFDANCER_TOKEN env var // Base URL defaults to https://api.pdfdancer.com or PDFDANCER_BASE_URL env var const pdf = await PDFDancer.open( pdfBytes, 'your-api-token', // optional if PDFDANCER_TOKEN is set 'https://api.pdfdancer.com', // optional base URL 30000 // optional timeout in ms ); // PDF is now ready for manipulation return pdf; } ``` -------------------------------- ### Manage PDF Pages with pdfdancer-client-typescript Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt This snippet demonstrates page management operations within a PDF document using pdfdancer-client-typescript. It shows how to retrieve all pages, access individual pages, move pages to different positions within the document (both by index and using a PageClient object), and delete pages by index or using a PageClient object. It also logs basic page information like size and orientation. ```typescript async function managePages(pdf: PDFDancer) { // Get all pages const pages = await pdf.pages(); console.log(`Document has ${pages.length} pages`); for (let i = 0; i < pages.length; i++) { const page = pages[i]; console.log(`Page ${i}:`, page.pageSize, page.orientation); } // Get specific page const firstPage = pdf.page(0); // Move page from index 2 to index 0 (make it first) await pdf.movePage(2, 0); // Move page using PageClient const page = pdf.page(1); await page.moveTo(3); // Move to index 3 // Delete a page by index await pdf.deletePage(1); // Delete page using PageClient const lastPage = pdf.page(pages.length - 1); await lastPage.delete(); } ``` -------------------------------- ### Create a New Blank PDF with PDFDancer TypeScript Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Illustrates how to create a new, blank PDF document from scratch using PDFDancer. This includes adding text with custom fonts and colors, and embedding an image. The newly created PDF can then be saved to disk. ```typescript import { PDFDancer, Color, StandardFonts } from 'pdfdancer-client-typescript'; async function createNew() { const pdf = await PDFDancer.new('your-api-token'); await pdf.page(0).newParagraph() .text('Quarterly Summary') .font(StandardFonts.TIMES_BOLD, 18) .color(new Color(10, 10, 80)) .lineSpacing(1.2) .at(72, 730) .apply(); await pdf.newImage() .fromFile('logo.png') .at(0, 420, 710) .add(); await pdf.save('summary.pdf'); } createNew().catch(console.error); ``` -------------------------------- ### Utilize Position Helpers in TypeScript Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt Shows how to use the `Position` class from the `pdfdancer-client-typescript` library to define precise locations for elements within a PDF. It covers creating positions based on page coordinates, entire pages, text search, named elements (like form fields), and modifying existing positions with offsets. The `Position` class and related enums are imported from the library. ```typescript import { Position, PositionMode, ShapeType } from 'pdfdancer-client-typescript'; async function usePositions(pdf: PDFDancer) { // Position at specific page coordinates const pos1 = Position.atPageCoordinates(0, 250, 400); // Position for entire page const pos2 = Position.atPage(1); // Position with text search const pos3 = Position.atPageWithText(0, 'Invoice Number'); // Position by name (for form fields) const pos4 = Position.byName('firstName'); // Modify position with offsets const pos5 = Position.atPageCoordinates(0, 100, 200) .moveX(50) // Move right 50 points .moveY(-20); // Move up 20 points // Access coordinates console.log('X:', pos1.getX()); console.log('Y:', pos1.getY()); // Copy position const posCopy = pos1.copy(); } ``` -------------------------------- ### Add Image to PDF Page with pdfdancer-client-typescript Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt This code demonstrates how to add images to PDF pages using the pdfdancer-client-typescript library. It supports adding images from both file paths and byte arrays in memory. The function `addImages` takes a PDFDancer instance and adds specified images at given coordinates on specific pages. It requires file system access (`fs`) if reading images from disk. ```typescript async function addImages(pdf: PDFDancer) { // Add image from file path await pdf.newImage() .fromFile('logo.png') .at(0, 420, 710) // pageIndex=0, x=420, y=710 .add(); // Add image from bytes in memory const imageData = new Uint8Array(await fs.readFile('photo.jpg')); await pdf.newImage() .fromBytes(imageData) .at(1, 200, 500) .add(); // Add watermark image await pdf.newImage() .fromFile('watermark.png') .at(0, 150, 300) .add(); } ``` -------------------------------- ### Complete PDF Manipulation Workflow in TypeScript Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt Executes a full PDF manipulation workflow using the PDFDancer TypeScript Client. It demonstrates opening a PDF, inspecting its structure, updating form fields, editing existing text, adding new text and images, removing elements, and saving the modified document. Error handling for PDF operations is also included. Dependencies include 'pdfdancer-client-typescript' and Node.js file system modules. ```typescript import { PDFDancer, StandardFonts, Color } from 'pdfdancer-client-typescript'; import { promises as fs } from 'node:fs'; async function completeWorkflow() { try { // 1. Open existing PDF const pdfBytes = await fs.readFile('contract.pdf'); const pdf = await PDFDancer.open(pdfBytes); // 2. Inspect document structure const pages = await pdf.pages(); console.log(`Processing ${pages.length} pages`); // 3. Find and update form fields const fields = await pdf.selectFormFields(); for (const field of fields) { if (field.name === 'contractDate') { await field.fill('2025-10-21'); } if (field.name === 'signerName') { await field.fill('John Smith'); } } // 4. Find and edit existing text const headers = await pdf.page(0).selectParagraphsStartingWith('CONTRACT AGREEMENT'); if (headers.length > 0) { await headers[0].edit() .replace('CONTRACT AGREEMENT - EXECUTED') .font(StandardFonts.HELVETICA_BOLD, 16) .color(new Color(0, 0, 0)) .apply(); } // 5. Add new content await pdf.page(0).newParagraph() .text('Document processed on 2025-10-21') .font(StandardFonts.HELVETICA, 10) .color(new Color(128, 128, 128)) .at(72, 50) .apply(); // 6. Add signature image await pdf.newImage() .fromFile('signature.png') .at(0, 150, 200) .add(); // 7. Remove watermark images from left margin const images = await pdf.page(0).selectImages(); for (const img of images) { const x = img.position.boundingRect?.x; if (x !== undefined && x < 50) { await img.delete(); } } // 8. Save final document await pdf.save('contract-executed.pdf'); console.log('PDF processing complete!'); } catch (error) { if (error instanceof PdfDancerException) { console.error('PDF operation failed:', error.message); } throw error; } } completeWorkflow().catch(console.error); ``` -------------------------------- ### Edit Existing PDF with PDFDancer TypeScript Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Demonstrates how to open an existing PDF, locate and modify a paragraph, add a new paragraph with specific formatting, and save the modified PDF. This process involves reading the PDF into bytes, opening it with PDFDancer, applying edits using fluent builders, and then saving the result. ```typescript import { PDFDancer, Color, StandardFonts } from 'pdfdancer-client-typescript'; import { promises as fs } from 'node:fs'; async function run() { const pdfBytes = await fs.readFile('input.pdf'); // Token defaults to PDFDANCER_TOKEN environment variable when omitted const pdf = await PDFDancer.open( pdfBytes, 'your-api-token', // optional when PDFDANCER_TOKEN is set 'https://api.pdfdancer.com' // optional base URL ); // Locate and update an existing paragraph const heading = (await pdf.page(0).selectParagraphsStartingWith('Executive Summary'))[0]; await heading.moveTo(72, 680); const result = await heading.edit() .replace('Overview') .apply(); // Add a new paragraph with precise placement await pdf.page(0).newParagraph() .text('Generated with PDFDancer') .font(StandardFonts.HELVETICA, 12) .color(new Color(70, 70, 70)) .lineSpacing(1.4) .at(72, 520) .apply(); // Persist the modified document await pdf.save('output.pdf'); // or keep it in memory const updatedBytes = await pdf.getBytes(); } run().catch(console.error); ``` -------------------------------- ### Handle PDFDancer Exceptions in TypeScript Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Demonstrates how to wrap PDFDancer operations in a try-catch block to handle specific exceptions like `FontNotFoundException`, `ValidationException`, `HttpClientException`, and `SessionException`. This ensures graceful error management and provides actionable feedback to users. ```typescript import { ValidationException, HttpClientException, SessionException, FontNotFoundException, PdfDancerException } from 'pdfdancer-client-typescript'; try { await pdf.page(0).newParagraph() .text('Hello') .font('Unknown-Font', 12) .at(100, 100) .apply(); } catch (error) { if (error instanceof FontNotFoundException) { console.error('Font not found:', error.message); } else if (error instanceof ValidationException) { console.error('Invalid input:', error.message); } else if (error instanceof HttpClientException) { console.error('API error:', error.message); } else if (error instanceof SessionException) { console.error('Session error:', error.message); } else if (error instanceof PdfDancerException) { console.error('Unexpected failure:', error.message); } } ``` -------------------------------- ### Work with Vector Paths in PDF using PDFDancer Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt Illustrates how to select and manipulate vector path objects within a PDF using the PDFDancer client. It covers finding all paths, paths at specific coordinates, moving paths to new locations, and deleting paths. Dependencies include the PDFDancer library. ```typescript async function workWithPaths(pdf: PDFDancer) { // Find all vector paths on page 0 const paths = await pdf.page(0).selectPaths(); console.log(`Found ${paths.length} vector paths`); for (const path of paths) { console.log('Path ID:', path.internalId); console.log('Position:', path.position); // Move path to new coordinates await path.moveTo(150, 250); // Delete path await path.delete(); } // Find paths at specific coordinates const pathsAtPoint = await pdf.page(0).selectPathsAt(200, 300); // Find all paths in document const allPaths = await pdf.selectPaths(); } ``` -------------------------------- ### Add Paragraph to PDF Page with pdfdancer-client-typescript Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt This snippet demonstrates how to create and add new paragraphs to specific pages in a PDF document using pdfdancer-client-typescript. It shows how to set text content, font styles (including custom font files), color, line spacing, and precise positioning. Dependencies include the 'pdfdancer-client-typescript' library and potentially file system access for custom fonts. ```typescript import { StandardFonts, Color } from 'pdfdancer-client-typescript'; async function addParagraph(pdf: PDFDancer) { // Add a simple paragraph await pdf.page(0).newParagraph() .text('This is a new paragraph\nwith multiple lines') .font(StandardFonts.HELVETICA, 12) .color(new Color(0, 0, 0)) .lineSpacing(1.4) .at(72, 600) // Position at x=72, y=600 .apply(); // Add paragraph with custom font file await pdf.page(1).newParagraph() .text('Custom font paragraph') .fontFile('fonts/Roboto-Regular.ttf', 14) .color(new Color(50, 50, 50)) .at(100, 500) .apply(); // Use font by name (if already registered) await pdf.page(0).newParagraph() .text('Generated by PDFDancer') .font('Times-Roman', 10) .color(new Color(128, 128, 128)) .lineSpacing(1.2) .at(72, 50) .apply(); } ``` -------------------------------- ### Manage Images in PDF with pdfdancer-client-typescript Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt This snippet illustrates how to select, manipulate, and delete images within a PDF document using pdfdancer-client-typescript. It covers selecting all images on a page, selecting images at specific coordinates, moving images to new positions, and deleting individual or all images in the document. The code logs image positions and conditionally deletes images based on their horizontal placement. ```typescript async function manageImages(pdf: PDFDancer) { // Find all images on page 0 const images = await pdf.page(0).selectImages(); console.log(`Found ${images.length} images on page 0`); for (const image of images) { const x = image.position.boundingRect?.x; const y = image.position.boundingRect?.y; console.log(`Image at (${x}, ${y})`); // Delete images on left side of page if (x !== undefined && x < 100) { await image.delete(); } } // Find images at specific coordinates const imagesAtPoint = await pdf.page(0).selectImagesAt(250, 400); // Move an image to new position if (images.length > 0) { await images[0].moveTo(300, 350); } // Delete all images across entire document const allImages = await pdf.selectImages(); for (const img of allImages) { await img.delete(); } } ``` -------------------------------- ### Find Objects in PDF Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Search for various objects within the PDF document, such as paragraphs, images, and form fields. You can select objects based on content, position, or name. The `Position` helper class can be used for coordinate-based selections. ```typescript const paragraphs = await pdf.selectParagraphs(); const header = await pdf.page(0).selectParagraphsStartingWith('Invoice #'); const imagesAtPoint = await pdf.page(2).selectImagesAt(120, 300); const fieldsByName = await pdf.selectFieldsByName('firstName'); const textLines = await pdf.selectLines(); // All text lines across the document ``` ```typescript import { Position } from 'pdfdancer-client-typescript'; const point = Position.atPageCoordinates(1, 250, 400); const paragraphsAtPoint = await pdf.page(1).selectParagraphsAt(point.getX()!, point.getY()!); ``` -------------------------------- ### Work with Forms and Layout in PDFDancer TypeScript Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Shows how to interact with PDF form fields and manipulate content layout. This includes inspecting the document structure, filling form fields by name, and selectively deleting images based on their coordinates. Modified documents can be saved. ```typescript import { PDFDancer } from 'pdfdancer-client-typescript'; async function workWithForms() { const pdf = await PDFDancer.open('contract.pdf'); // Inspect global document structure const pages = await pdf.pages(); console.log('Total pages:', pages.length); // Update form fields const signature = (await pdf.selectFieldsByName('signature'))[0]; await signature.fill('Signed by Jane Doe'); // Trim or move content at specific coordinates const images = await pdf.page(1).selectImages(); for (const image of images) { const x = image.position.boundingRect?.x; if (x !== undefined && x < 100) { await image.delete(); } } await pdf.save('contract-updated.pdf'); } ``` -------------------------------- ### TypeScript Interfaces for Command Results and Text Status Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Defines the `CommandResult` interface for text modification operations, detailing properties like `commandName`, `elementId`, `message`, `success`, and `warning`. It also defines the `TextStatus` interface, providing information about text modification status, encodability, font type, and font recommendations. ```typescript interface CommandResult { commandName: string; // Name of the operation elementId: string | null; // ID of the affected element message: string | null; // Optional status message success: boolean; // Operation success status warning: string | null; // Warning message (e.g., embedded font issues) } interface TextStatus { modified: boolean; // Whether text has been modified encodable: boolean; // Whether text is encodable with current font fontType: FontType; // Type of font being used fontRecommendation: FontRecommendation; // Recommended alternative font } ``` -------------------------------- ### Add and Manipulate Images in PDF Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Incorporate new images into a PDF document or modify existing ones. Images can be added from files or byte arrays. Existing images can be repositioned or deleted. ```typescript await pdf.newImage() .fromFile('fixtures/logo-80.png') .at(0, 420, 200) .add(); const images = await pdf.selectImages(); await images[0].moveTo(200, 350); await images[1].delete(); ``` -------------------------------- ### Edit Existing Paragraph Text in PDFDancer Source: https://context7.com/menschmachine/pdfdancer-client-typescript/llms.txt Explains how to modify the text and formatting of existing paragraphs within a PDF using the PDFDancer TypeScript client. This includes simple text replacement, changing font, size, color, and repositioning the paragraph. The `apply()` method returns a result object that may contain warnings or success status. ```typescript import { Color, StandardFonts } from 'pdfdancer-client-typescript'; async function editParagraph(pdf: PDFDancer) { // Find and edit a paragraph const paragraphs = await pdf.page(0).selectParagraphsStartingWith('Invoice Total'); if (paragraphs.length > 0) { const para = paragraphs[0]; // Simple text replacement (preserves original formatting) const result = await para.edit() .replace('Invoice Total: $1,234.56') .apply(); // Edit with new formatting const fullEdit = await para.edit() .replace('PAID IN FULL') .font(StandardFonts.HELVETICA_BOLD, 14) .color(new Color(0, 128, 0)) // Green color .moveTo(100, 650) // New position .apply(); // Check for warnings (e.g., embedded font issues) if (typeof fullEdit === 'object' && fullEdit.warning) { console.warn('Warning:', fullEdit.warning); console.log('Success:', fullEdit.success); console.log('Element ID:', fullEdit.elementId); } } } ``` -------------------------------- ### Save and Export PDF Document Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Obtain the modified PDF document as a byte array or save it directly to a file. The `save` method is a Node.js convenience function that wraps `fs.writeFile`. For browser environments, you'll need to handle the download using the byte array. ```typescript const pdfBytes = await pdf.getBytes(); await pdf.save('output.pdf'); // Node.js helper that writes the file ``` -------------------------------- ### Create New Paragraph in PDF Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Add a new paragraph to a specific page in the PDF document. You can define the text content, font, size, line spacing, color, and position of the new paragraph before applying the changes. ```typescript await pdf.page(0).newParagraph() .text('Awesomely\nObvious!') .font('Roboto-Regular', 14) .lineSpacing(0.8) .color(new Color(0, 0, 0)) .at(300, 500) .apply(); ``` -------------------------------- ### Manage Form Fields in PDF Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Interact with form fields within the PDF document. You can select form fields by name, fill them with data, or delete them. This is useful for programmatic form completion. ```typescript const fields = await pdf.selectFormFields(); for (const field of fields) { if (field.name === 'firstName') { await field.fill('Ada'); } } const zipFields = await pdf.selectFieldsByName('zip'); await zipFields[0]?.delete(); ``` -------------------------------- ### Edit Existing Paragraph in PDF Source: https://github.com/menschmachine/pdfdancer-client-typescript/blob/main/README.md Modify an existing paragraph in the PDF document. You can replace text, change font properties, and reposition the paragraph. Be aware of potential warnings when modifying text with embedded fonts, as this can lead to unrenderable characters. ```typescript const [para] = await pdf.page(0).selectParagraphsStartingWith('The Complete'); if (para) { const result = await para.edit() .replace('Awesomely\nObvious!') .font('Helvetica', 12) .color(new Color(0, 0, 0)) .moveTo(280, 460) .apply(); // Check for warnings (e.g., embedded font modifications) if (typeof result === 'object' && result.warning) { console.warn('Operation warning:', result.warning); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.