### pdfform() - Create PDF Form Handler Source: https://context7.com/phihag/pdfform.js/llms.txt Initializes a new pdfform instance. Optionally accepts a PDF library reference for custom parsing. ```APIDOC ## pdfform() ### Description Creates a new pdfform instance for processing PDF documents. Optionally accepts a PDF library reference for custom PDF parsing. ### Parameters - **pdf_library** (object) - Optional - A reference to a PDF parsing library (e.g., minipdf or pdf.js wrapper). ### Request Example ```javascript const handler = pdfform(); ``` ``` -------------------------------- ### Create PDF Form Handler with pdfform.js Source: https://context7.com/phihag/pdfform.js/llms.txt Instantiate a pdfform handler. Use the built-in minipdf library by default or provide a custom PDF.js wrapper. ```javascript const handler = pdfform(); ``` ```javascript const pdfjs_wrap = require('./minipdf_js.js'); const handler = pdfform(pdfjs_wrap); ``` ```javascript const handler = pdfform(minipdf); // Built-in minipdf ``` ```javascript const handler = pdfform(minipdf_js); // pdf.js wrapper ``` -------------------------------- ### Client-Side PDF Filling with XHR Source: https://context7.com/phihag/pdfform.js/llms.txt Demonstrates how to fetch a PDF from a URL using XMLHttpRequest, fill its form fields programmatically, and trigger a download of the filled PDF in the browser. ```APIDOC ## Client-Side PDF Filling with XHR ### Description Fetches a PDF from a URL, fills its form fields with provided data, and triggers an automatic download of the completed PDF. ### Usage ```javascript // Load PDF from URL (must be same-origin or CORS-enabled) function loadAndFillPdf(pdfUrl, fieldValues) { const xhr = new XMLHttpRequest(); xhr.open('GET', pdfUrl, true); xhr.responseType = 'arraybuffer'; xhr.onload = function() { if (this.status === 200) { try { // Fill the PDF with provided values const filledPdf = pdfform().transform(this.response, fieldValues); // Create download link const blob = new Blob([filledPdf], { type: 'application/pdf' }); const url = URL.createObjectURL(blob); // Auto-download const link = document.createElement('a'); link.href = url; link.download = 'completed-form.pdf'; document.body.appendChild(link); link.click(); document.body.removeChild(link); // Clean up setTimeout(() => URL.revokeObjectURL(url), 100); } catch (error) { console.error('PDF processing error:', error); } } else { console.error('Failed to load PDF:', this.status); } }; xhr.onerror = function() { console.error('Network error loading PDF'); }; xhr.send(); } // Example Usage: loadAndFillPdf('/forms/application.pdf', { 'applicant_name': ['Jane Smith'], 'date': ['2024-01-15'], 'signature_checkbox': [true] }); ``` ``` -------------------------------- ### Handle Diverse PDF Field Types Source: https://context7.com/phihag/pdfform.js/llms.txt Demonstrates how to inspect and populate various PDF field types including text, booleans, selects, and radio buttons. ```javascript const fs = require('fs'); const pdfform = require('pdfform.js'); const pdfBuffer = fs.readFileSync('multi-field-form.pdf'); // First, inspect the fields const fieldInfo = pdfform().list_fields(pdfBuffer); /* Example fieldInfo structure: { // Text input fields 'full_name': [{ type: 'string' }], 'email': [{ type: 'string' }], // Multiple text fields with same name (indexed) 'phone': [ { type: 'string' }, // phone[0] { type: 'string' } // phone[1] ], // Checkbox (boolean) 'agree_terms': [{ type: 'boolean' }], 'opt_in_marketing': [{ type: 'boolean' }], // Dropdown select 'country': [{ type: 'select', options: ['USA', 'Canada', 'UK', 'Germany', 'France'] }], // Radio buttons 'payment_type': [{ type: 'radio', options: ['Credit', 'Debit', 'PayPal'] }] } */ // Fill all field types const filledPdf = pdfform().transform(pdfBuffer, { // String fields - always use array 'full_name': ['John Michael Doe'], 'email': ['john.doe@company.com'], // Multiple instances - provide value at each index 'phone': ['555-123-4567', '555-987-6543'], // Boolean fields - true/false 'agree_terms': [true], 'opt_in_marketing': [false], // Select field - use the option text 'country': ['Germany'], // Radio button - use the option text 'payment_type': ['PayPal'] }); fs.writeFileSync('filled-multi-field.pdf', filledPdf); ``` -------------------------------- ### Load and fill PDF via XHR Source: https://context7.com/phihag/pdfform.js/llms.txt Fetches a PDF from a URL and fills it programmatically in the browser. Requires the PDF to be same-origin or CORS-enabled. ```javascript // Load PDF from URL (must be same-origin or CORS-enabled) function loadAndFillPdf(pdfUrl, fieldValues) { const xhr = new XMLHttpRequest(); xhr.open('GET', pdfUrl, true); xhr.responseType = 'arraybuffer'; xhr.onload = function() { if (this.status === 200) { try { // Fill the PDF with provided values const filledPdf = pdfform().transform(this.response, fieldValues); // Create download link const blob = new Blob([filledPdf], { type: 'application/pdf' }); const url = URL.createObjectURL(blob); // Auto-download const link = document.createElement('a'); link.href = url; link.download = 'completed-form.pdf'; document.body.appendChild(link); link.click(); document.body.removeChild(link); // Clean up setTimeout(() => URL.revokeObjectURL(url), 100); } catch (error) { console.error('PDF processing error:', error); } } else { console.error('Failed to load PDF:', this.status); } }; xhr.onerror = function() { console.error('Network error loading PDF'); }; xhr.send(); } // Usage loadAndFillPdf('/forms/application.pdf', { 'applicant_name': ['Jane Smith'], 'date': ['2024-01-15'], 'signature_checkbox': [true] }); ``` -------------------------------- ### Load and Fill PDF Form in Browser Source: https://context7.com/phihag/pdfform.js/llms.txt Requires the pdfform.minipdf.dist.js library. Handles file reading, field discovery, and PDF transformation via Blob. ```html PDF Form Filler
``` -------------------------------- ### list_fields(data) - List Available Form Fields Source: https://context7.com/phihag/pdfform.js/llms.txt Parses a PDF buffer and returns an object containing all fillable form fields with their types and options. ```APIDOC ## list_fields(data) ### Description Parses a PDF and returns an object containing all fillable form fields with their types and options. ### Parameters - **data** (Buffer/Uint8Array) - Required - The PDF file content. ### Response - **fields** (Object) - An object where keys are field names and values are arrays of field specifications (type, options). ### Response Example { "FirstName": [{ "type": "string" }], "Country": [{ "type": "select", "options": ["USA", "Canada"] }] } ``` -------------------------------- ### Fill PDF Form Fields with pdfform.js Source: https://context7.com/phihag/pdfform.js/llms.txt Transform a PDF buffer by filling specified form fields. Values must be provided as arrays, even for single-instance fields. Requires 'fs' and 'pdfform.js'. ```javascript const fs = require('fs'); const pdfform = require('pdfform.js'); // Read the input PDF const inputPdf = fs.readFileSync('application-form.pdf'); // Define field values // Each field value is an array (even for single fields) const fieldValues = { // Text fields - strings 'FirstName': ['John'], 'LastName': ['Doe'], 'Email': ['john.doe@example.com'], 'Address': ['123 Main Street, Suite 100'], // Multiple instances of same field 'PhoneNumber': ['555-1234', '555-5678', '555-9999'], // Numeric fields (passed as numbers or strings) 'Age': [30], 'Salary': ['75000'], // Checkbox fields - booleans 'AgreeTerms': [true], 'Newsletter': [false], // Radio button - select by option name 'PaymentMethod': ['Credit Card'], // Dropdown select - select by option value 'Country': ['Germany'], // Unicode and special characters 'Notes': ['Price: $100 (a ≤ b)'], 'InternationalName': ['Müller'], }; // Transform the PDF with filled values const filledPdf = pdfform().transform(inputPdf, fieldValues); // Write the output PDF fs.writeFileSync('filled-application.pdf', filledPdf); console.log('PDF form filled successfully!'); ``` -------------------------------- ### Batch Process PDF Forms in Node.js Source: https://context7.com/phihag/pdfform.js/llms.txt Automates filling multiple PDF forms from a template using an array of data records. ```javascript const fs = require('fs'); const path = require('path'); const pdfform = require('pdfform.js'); async function batchFillPdfs(templatePath, dataRecords, outputDir) { // Read template once const templateBuffer = fs.readFileSync(templatePath); // Get field info for validation const availableFields = pdfform().list_fields(templateBuffer); console.log('Available fields:', Object.keys(availableFields)); const results = []; for (let i = 0; i < dataRecords.length; i++) { const record = dataRecords[i]; const outputPath = path.join(outputDir, `output-${i + 1}.pdf`); try { // Transform field data to pdfform format const fields = {}; for (const [key, value] of Object.entries(record)) { // Wrap single values in arrays fields[key] = Array.isArray(value) ? value : [value]; } // Fill the PDF const filledPdf = pdfform().transform(templateBuffer, fields); // Write output fs.writeFileSync(outputPath, filledPdf); results.push({ index: i + 1, success: true, path: outputPath }); } catch (error) { results.push({ index: i + 1, success: false, error: error.message }); } } return results; } // Example usage const employeeData = [ { employee_name: 'Alice Johnson', department: 'Engineering', hire_date: '2023-06-15', is_full_time: true }, { employee_name: 'Bob Smith', department: 'Marketing', hire_date: '2023-08-01', is_full_time: false }, { employee_name: 'Carol Williams', department: 'HR', hire_date: '2023-09-20', is_full_time: true } ]; batchFillPdfs('./templates/employee-form.pdf', employeeData, './output') .then(results => { console.log('Batch processing complete:'); results.forEach(r => { if (r.success) { console.log(` Record ${r.index}: Success - ${r.path}`); } else { console.log(` Record ${r.index}: Failed - ${r.error}`); } }); }); ``` -------------------------------- ### List Available Form Fields in a PDF Source: https://context7.com/phihag/pdfform.js/llms.txt Parse a PDF buffer to retrieve all fillable form fields, their types, and options. Requires the 'fs' and 'pdfform.js' modules. ```javascript const fs = require('fs'); const pdfform = require('pdfform.js'); // Read PDF file const pdfBuffer = fs.readFileSync('form.pdf'); // Get all form fields const fields = pdfform().list_fields(pdfBuffer); // Example output: // { // 'FirstName': [{ type: 'string' }], // 'LastName': [{ type: 'string' }], // 'Email': [{ type: 'string' }], // 'Subscribe': [{ type: 'boolean' }], // 'Country': [{ // type: 'select', // options: ['USA', 'Canada', 'UK', 'Germany'] // }], // 'PaymentMethod': [{ // type: 'radio', // options: ['Credit Card', 'PayPal', 'Bank Transfer'] // }], // 'PhoneNumbers': [ // { type: 'string' }, // PhoneNumbers[0] // { type: 'string' }, // PhoneNumbers[1] // { type: 'string' } // PhoneNumbers[2] // ] // } // Process field information for (const fieldName in fields) { const specs = fields[fieldName]; specs.forEach((spec, index) => { console.log(`Field: ${fieldName}[${index}] - Type: ${spec.type}`); if (spec.options) { console.log(` Options: ${spec.options.join(', ')}`); } }); } ``` -------------------------------- ### transform(data, fields) - Fill PDF Form Fields Source: https://context7.com/phihag/pdfform.js/llms.txt Populates a PDF form with provided values and returns the resulting PDF as a Uint8Array. ```APIDOC ## transform(data, fields) ### Description Takes a PDF buffer and a fields object, returns a new Uint8Array containing the filled PDF. ### Parameters - **data** (Buffer/Uint8Array) - Required - The input PDF file content. - **fields** (Object) - Required - A map of field names to arrays of values. ### Request Example { "FirstName": ["John"], "AgreeTerms": [true] } ### Response - **filledPdf** (Uint8Array) - The resulting PDF document with filled fields. ``` -------------------------------- ### Browser Usage of pdfform.js Source: https://github.com/phihag/pdfform.js/blob/master/README.md Include the library via a script tag and use the `pdfform()` function to transform PDF data with specified fields. Ensure the PDF data is loaded into an ArrayBuffer. ```html ``` -------------------------------- ### Express.js PDF Form API Source: https://context7.com/phihag/pdfform.js/llms.txt Implements server-side endpoints to list PDF fields and fill forms using Express.js and pdfform.js. ```javascript const express = require('express'); const fs = require('fs'); const path = require('path'); const pdfform = require('pdfform.js'); const app = express(); app.use(express.json()); // Endpoint to list available fields in a PDF template app.get('/api/pdf/:template/fields', (req, res) => { const templatePath = path.join(__dirname, 'templates', `${req.params.template}.pdf`); try { const pdfBuffer = fs.readFileSync(templatePath); const fields = pdfform().list_fields(pdfBuffer); res.json({ success: true, fields }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); // Endpoint to fill a PDF form app.post('/api/pdf/:template/fill', (req, res) => { const templatePath = path.join(__dirname, 'templates', `${req.params.template}.pdf`); const fieldValues = req.body.fields; try { const pdfBuffer = fs.readFileSync(templatePath); const filledPdf = pdfform().transform(pdfBuffer, fieldValues); res.setHeader('Content-Type', 'application/pdf'); res.setHeader('Content-Disposition', `attachment; filename="filled-${req.params.template}.pdf"`); res.send(Buffer.from(filledPdf)); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); app.listen(3000, () => { console.log('PDF form server running on port 3000'); }); // Example client request: // curl -X POST http://localhost:3000/api/pdf/application/fill \ // -H "Content-Type: application/json" \ // -d '{"fields": {"name": ["John Doe"], "email": ["john@example.com"]}}' \ // --output filled.pdf ``` -------------------------------- ### Node.js Express.js PDF Form API Source: https://context7.com/phihag/pdfform.js/llms.txt Provides server-side API endpoints using Express.js for listing PDF form fields and filling PDF forms. ```APIDOC ## Node.js Express.js PDF Form API ### Description Server-side PDF form processing using Express.js. Includes endpoints to list fields of a PDF template and to fill a PDF form with provided data. ### Endpoints #### GET /api/pdf/:template/fields ##### Description Retrieves a list of all form fields available in a specified PDF template. ##### Method GET ##### Endpoint `/api/pdf/:template/fields` ##### Parameters * **template** (string) - Path Parameter - The name of the PDF template file (without extension). ##### Response * **success** (boolean) - Indicates if the operation was successful. * **fields** (object) - An object containing the form fields and their properties. ##### Example Response (Success) ```json { "success": true, "fields": { "field_name_1": { ... }, "field_name_2": { ... } } } ``` #### POST /api/pdf/:template/fill ##### Description Fills the form fields of a specified PDF template with the provided data and returns the filled PDF. ##### Method POST ##### Endpoint `/api/pdf/:template/fill` ##### Parameters * **template** (string) - Path Parameter - The name of the PDF template file (without extension). ##### Request Body * **fields** (object) - Required - An object where keys are field names and values are arrays containing the data to fill into the fields. * Example: `{"name": ["John Doe"], "email": ["john@example.com"]}` ##### Response * Returns the filled PDF file. ##### Example Client Request (using curl) ```bash curl -X POST http://localhost:3000/api/pdf/application/fill \ -H "Content-Type: application/json" \ -d '{"fields": {"name": ["John Doe"], "email": ["john@example.com"]}}' \ --output filled.pdf ``` ### Server Setup Example ```javascript const express = require('express'); const fs = require('fs'); const path = require('path'); const pdfform = require('pdfform.js'); const app = express(); app.use(express.json()); // Endpoint to list available fields in a PDF template app.get('/api/pdf/:template/fields', (req, res) => { const templatePath = path.join(__dirname, 'templates', `${req.params.template}.pdf`); try { const pdfBuffer = fs.readFileSync(templatePath); const fields = pdfform().list_fields(pdfBuffer); res.json({ success: true, fields }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); // Endpoint to fill a PDF form app.post('/api/pdf/:template/fill', (req, res) => { const templatePath = path.join(__dirname, 'templates', `${req.params.template}.pdf`); const fieldValues = req.body.fields; try { const pdfBuffer = fs.readFileSync(templatePath); const filledPdf = pdfform().transform(pdfBuffer, fieldValues); res.setHeader('Content-Type', 'application/pdf'); res.setHeader('Content-Disposition', `attachment; filename="filled-${req.params.template}.pdf"`); res.send(Buffer.from(filledPdf)); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); app.listen(3000, () => { console.log('PDF form server running on port 3000'); }); ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.