CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-pdfkit

A PDF generation library for Node.js with comprehensive text, graphics, and form support

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

attachments.mddocs/

File Attachments

Embed files within PDF documents for comprehensive document packages, creating portable documents with associated resources.

Capabilities

File Embedding

Embed external files directly into PDF documents as attachments.

/**
 * Embed a file as an attachment in the PDF
 * @param src - File source (path or Buffer)
 * @param options - File attachment options
 * @returns PDF reference for the embedded file
 */
file(src: string | Buffer, options?: FileOptions): PDFReference;

interface FileOptions {
  /** Display name for the attachment */
  name?: string;
  /** MIME type of the file */
  type?: string;
  /** Description of the file */
  description?: string;
  /** Hide from embedded files list in viewer */
  hidden?: boolean;
  /** File creation date */
  creationDate?: Date;
  /** File modification date */
  modifiedDate?: Date;
  /** Relationship to the document */
  relationship?: FileRelationship;
}

type FileRelationship = 
  | 'Alternative'   // Alternative representation
  | 'Data'         // Data file
  | 'Source'       // Source file  
  | 'Supplement'   // Supplementary file
  | 'Unspecified'; // Unspecified relationship

Usage Examples:

// Embed a simple file
doc.file('./attachments/data.xlsx', {
  name: 'Quarterly Data.xlsx',
  description: 'Q1 2024 sales data'
});

// Embed with full metadata
doc.file('./attachments/source.zip', {
  name: 'Source Code.zip',
  type: 'application/zip',
  description: 'Complete source code for the project',
  relationship: 'Source',
  creationDate: new Date('2024-01-15'),
  modifiedDate: new Date('2024-03-20')
});

// Embed from Buffer
const fileBuffer = fs.readFileSync('./data/report.docx');
doc.file(fileBuffer, {
  name: 'Full Report.docx',
  type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  description: 'Complete project report with appendices'
});

Named File Management

Create named references to embedded files for later use.

/**
 * Add a named embedded file reference
 * @param name - Reference name for the file
 * @param fileRef - PDF reference to the embedded file
 * @returns Document instance for chaining
 */
addNamedEmbeddedFile(name: string, fileRef: PDFReference): PDFDocument;

Usage Examples:

// Embed file and create named reference
const dataFileRef = doc.file('./data/sales.csv', {
  name: 'Sales Data.csv',
  description: 'Monthly sales figures'
});

// Add named reference for later use
doc.addNamedEmbeddedFile('sales_data', dataFileRef);

// Reference in document content
doc.text('See attached sales data file for detailed figures.', 100, 100);

File Type Detection

PDFKit can automatically detect common file types, but explicit specification is recommended.

Common MIME Types:

// Document files
doc.file('./report.pdf', { type: 'application/pdf' });
doc.file('./document.docx', { 
  type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
});

// Spreadsheets
doc.file('./data.xlsx', { 
  type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
});
doc.file('./data.csv', { type: 'text/csv' });

// Images
doc.file('./photo.jpg', { type: 'image/jpeg' });
doc.file('./diagram.png', { type: 'image/png' });

// Archives
doc.file('./source.zip', { type: 'application/zip' });
doc.file('./backup.tar.gz', { type: 'application/gzip' });

// Text files
doc.file('./readme.txt', { type: 'text/plain' });
doc.file('./config.json', { type: 'application/json' });

Multiple File Attachments

Organize multiple related files within a single PDF document.

Usage Examples:

// Embed related project files
const projectFiles = [
  { path: './src/main.js', name: 'Main Script', desc: 'Primary application logic' },
  { path: './src/config.json', name: 'Configuration', desc: 'Application settings' },
  { path: './docs/api.md', name: 'API Documentation', desc: 'API reference guide' },
  { path: './tests/test.js', name: 'Test Suite', desc: 'Unit tests' }
];

projectFiles.forEach(file => {
  doc.file(file.path, {
    name: file.name,
    description: file.desc,
    relationship: file.path.includes('src/') ? 'Source' : 'Supplement'
  });
});

// Create table of contents for attachments
doc.addPage()
   .fontSize(16)
   .text('Attached Files', 100, 100);

let y = 130;
projectFiles.forEach(file => {
  doc.fontSize(12)
     .text(`• ${file.name}: ${file.desc}`, 120, y);
  y += 20;
});

Attachment Security and Compliance

Handle file attachments with security and compliance considerations.

interface SecureFileOptions extends FileOptions {
  /** Mark file as hidden from casual viewing */
  hidden?: boolean;
  /** Specify security relationship */
  relationship?: 'Source' | 'Data' | 'Alternative';
  /** Add compliance metadata */
  compliance?: {
    standard?: string;
    version?: string;
    checksum?: string;
  };
}

Usage Examples:

// Embed sensitive data with appropriate marking
doc.file('./sensitive/audit-trail.log', {
  name: 'Audit Trail',
  description: 'System audit log (restricted access)',
  hidden: true,
  relationship: 'Data',
  type: 'text/plain'
});

// Compliance-related attachments
doc.file('./compliance/validation-report.pdf', {
  name: 'Validation Report',
  description: 'FDA validation documentation',
  relationship: 'Supplement',
  compliance: {
    standard: 'FDA 21 CFR Part 11',
    version: '2.1',
    checksum: 'sha256:abc123...'
  }
});

File Attachment Patterns

Documentation Package

// Create comprehensive documentation package
const docPackage = [
  { file: './docs/user-guide.pdf', name: 'User Guide', relationship: 'Supplement' },
  { file: './docs/api-reference.pdf', name: 'API Reference', relationship: 'Supplement' },
  { file: './examples/samples.zip', name: 'Code Examples', relationship: 'Source' },
  { file: './data/test-data.json', name: 'Test Data', relationship: 'Data' }
];

// Add cover page explaining attachments
doc.fontSize(20).text('Document Package', 100, 100);
doc.fontSize(12).text('This PDF contains the following attached files:', 100, 140);

let y = 170;
docPackage.forEach(item => {
  // Embed the file
  doc.file(item.file, {
    name: item.name,
    relationship: item.relationship
  });
  
  // List in document
  doc.text(`• ${item.name}`, 120, y);
  y += 20;
});

Data Analysis Report

// Embed data files with analysis report
const analysisFiles = {
  rawData: './data/raw-data.csv',
  processedData: './data/processed-data.xlsx', 
  code: './analysis/analysis-script.py',
  config: './analysis/config.yaml'
};

// Embed all related files
Object.entries(analysisFiles).forEach(([key, path]) => {
  doc.file(path, {
    name: key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase()),
    description: `${key} file for the analysis`,
    relationship: key === 'code' ? 'Source' : 'Data'
  });
});

// Reference in report
doc.text('Data Analysis Report', 100, 100);
doc.text('All source data and analysis code are attached to this document.', 100, 130);

Archive and Backup

// Create archive with backup files
const backupDate = new Date();
const archiveRef = doc.file('./backup/system-backup.tar.gz', {
  name: `System Backup ${backupDate.toISOString().split('T')[0]}`,
  description: 'Complete system backup archive',
  type: 'application/gzip',
  creationDate: backupDate,
  relationship: 'Data'
});

// Add to named files for reference
doc.addNamedEmbeddedFile('latest_backup', archiveRef);

Best Practices

File Organization

  • Use descriptive names for attachments
  • Include file extensions in names for clarity
  • Organize related files with consistent naming
  • Provide meaningful descriptions

Metadata Management

  • Always specify MIME types explicitly
  • Include creation and modification dates
  • Use appropriate relationship types
  • Consider compliance requirements

Performance Considerations

  • Large files increase PDF size significantly
  • Consider compression for text-based files
  • Use hidden flag for auxiliary files
  • Limit number of attachments for better performance

Install with Tessl CLI

npx tessl i tessl/npm-pdfkit

docs

accessibility-features.md

attachments.md

color-management.md

document-management.md

font-management.md

image-handling.md

index.md

interactive-elements.md

outline.md

tables.md

text-rendering.md

vector-graphics.md

tile.json