npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

typescript-pdf

v0.6.1

Published

A modern TypeScript library for programmatic PDF generation with a declarative API

Readme

typescript-pdf

Version CI TypeScript License: MIT

A TypeScript library for programmatic PDF generation with a declarative, widget-based API inspired by Flutter. Build complex PDF documents with type safety.

typescript-pdf v0.6.1 represents a mature PDF generation library:

  • Production Stability - Comprehensive error handling and edge case coverage
  • Advanced Features - MultiPage documents, table text overflow, data visualization
  • Cross-Platform - Universal Node.js and browser compatibility

🎯 Use Cases

Business Applications

  • Financial Reports: Multi-page reports with tables and charts
  • Invoices & Receipts: Professional document generation
  • Certificates: Styled certificates with custom layouts
  • Analytics Dashboards: Data visualization with charts and metrics

Integration Scenarios

  • Web Applications: Client-side PDF generation in browsers
  • Node.js APIs: Server-side document generation services
  • React/Vue Apps: Component-based PDF creation
  • Express.js Routes: PDF endpoints for web applications
  • Automated Reporting: Scheduled report generation systems

🚀 Key Features

Core Capabilities

  • 🔒 Type-Safe: Complete TypeScript implementation
  • 📱 Declarative API: Widget-based approach similar to React/Flutter
  • 🌍 Universal: Works seamlessly in Node.js and browsers
  • ⚡ High Performance: Optimized constraint-based layout engine with caching
  • 📄 Multi-Page Support: Automatic page breaks with headers and footers
  • 📊 Data Visualization: Built-in tables and charts with advanced styling

Advanced Widget System

  • Layout Widgets: Container, Padding, Margin, Align, Center, Stack, Positioned
  • Flex Layouts: Row, Column, Flexible, Expanded with Flutter-style alignment
  • Text Rendering: Rich text, font fallbacks, text overflow (clip/ellipsis/visible)
  • Data Tables: Advanced tables with column layouts, borders, and text overflow
  • Charts & Graphs: Bar charts, line charts with customizable styling
  • Theme System: Comprehensive theming with style inheritance

📦 Installation

npm install typescript-pdf
# or
pnpm add typescript-pdf
# or  
yarn add typescript-pdf

🎬 Visual Examples

Advanced Table System

Professional tables with borders, text overflow, and custom styling:

Advanced Tables

Data Visualization

Built-in chart widgets for business reports and dashboards:

Data Charts

Multi-Page Documents

Automatic page breaks with headers, footers, and consistent formatting:

Multi-Page Documents

🎯 Quick Start

Simple Document

import { writeFile } from 'fs/promises';
import { Document, Txt, Container, Layout, PdfColor } from 'typescript-pdf';

const doc = new Document();
doc.addPage({
    build: () => new Container({
        decoration: {
            color: PdfColor.fromHex('#f0f0f0ff'),
            border: { width: 1, color: PdfColor.black },
            borderRadius: BorderRadiusUtils.circular(4),
        },
        padding: Layout.EdgeInsets.all(20),
        child: new Txt('Hello World!', {
            style: { fontSize: 24, color: PdfColor.fromHex('#1976d2') }
        })
    })
});

const pdfBytes = await doc.save();
console.log('PDF data has been generated.');

// Save the generated PDF data to a file named 'hello-world.pdf'.
await writeFile('hello-world.pdf', pdfBytes);
console.log('✅ Successfully saved PDF to hello-world.pdf');

Business Report with Table

import { Document, MultiPage, Table, Txt, Container, DataUtils, Theme } from 'typescript-pdf';

const doc = new Document();
doc.addPage({
  build: () => new MultiPage({
    header: (pageNum, total) => new Txt(`Page ${pageNum} of ${total}`),
    children: [
      new Container({
        child: new Txt('Q4 Financial Report', {
          style: { fontSize: 28, fontWeight: Theme.FontWeight.Bold }
        })
      }),
      new Table({
        data: [
          ['Product', 'Revenue', 'Growth'],
          ['Product A', '$1.2M', '+15%'],
          ['Product B', '$980K', '+8%'],
          ['Product C', '$750K', '+22%']
        ],
        columnWidths: [
            DataUtils.columnWidths.flex(1),
            DataUtils.columnWidths.flex(1),
            DataUtils.columnWidths.flex(1)
        ],
        borders: DataUtils.borders.all({ width: 1, color: PdfColor.fromHex('#333333') }),
        headerStyle: { fontSize: 14, fontWeight: Theme.FontWeight.Bold, color: PdfColor.white }
      })
    ]
  })
});

const pdfBytes = await doc.save();

Data Visualization Dashboard

import { Document, Column, BarChart, LineChart, DataUtils, LineMarker } from 'typescript-pdf';

const salesData = DataUtils.createSeries('Sales', [
  { x: 'Q1', y: 1200 },
  { x: 'Q2', y: 1450 },
  { x: 'Q3', y: 1100 },
  { x: 'Q4', y: 1680 }
]);

const doc = new Document();
doc.addPage({
  build: () => new Column({
    children: [
      new BarChart({
        title: 'Quarterly Sales Performance',
        series: [salesData],
        width: 400,
        height: 250
      }),
      new LineChart({
        title: 'Growth Trend',
        series: [salesData],
        width: 400,
        height: 200,
        marker: LineMarker.Rectangle
      })
    ]
  })
});

const pdfBytes = await doc.save();

🏗️ Architecture

typescript-pdf uses a sophisticated dual-layer architecture:

High-Level Widget System

┌─────────────────────────────────────────────────────────────┐
│                    Declarative Widget API                   │
│  ┌─────────────┐ ┌───────────────┐  ┌───────────┐           │
│  │   Layout    │ │     Data      │  │   Theme   │           │
│  │   Widgets   │ │ Visualization │  │   System  │           │
│  └─────────────┘ └───────────────┘  └───────────┘           │
└─────────────────────────────────────────────────────────────┘

Low-Level PDF Engine

┌─────────────────────────────────────────────────────────────┐
│                     PDF Generation Core                     │
│  ┌─────────────┐ ┌─────────────┐ ┌─────────────┐            │
│  │    Font     │ │  Graphics   │ │   Document  │            │
│  │   System    │ │   Context   │ │  Management │            │
│  └─────────────┘ └─────────────┘ └─────────────┘            │
└─────────────────────────────────────────────────────────────┘

Key Design Principles

  • Composition over Inheritance: Modular, composable widgets
  • Performance Optimized: Constraint-based layout with intelligent caching
  • Developer Experience: IntelliSense support and comprehensive error messages

📊 Widget Catalog

Layout & Positioning

  • Container - Box model container with padding, margin, decoration
  • Padding - Add spacing inside widgets
  • Margin - Add spacing outside widgets
  • Align - Position child widgets with precise alignment
  • Center - Quick center alignment
  • Stack - Layer widgets with z-index positioning
  • Positioned - Absolute positioning within Stack

Flex Layout System

  • Row - Horizontal flex layout with alignment options
  • Column - Vertical flex layout with distribution control
  • Flexible - Responsive flex children
  • Expanded - Fill available space in flex layouts

Text & Typography

  • Txt - Styled text rendering with font fallbacks
  • RichText - Multi-span text with different styles
  • Text overflow modes: Clip, Ellipsis, Visible
  • Font system with intelligent fallbacks

Data & Visualization

  • Table - Advanced tables with column layouts and borders
  • TableRow - Individual table rows with custom styling
  • BarChart - Horizontal and vertical bar charts
  • LineChart - Line graphs with markers and styling
  • Chart - Base chart class for custom visualizations

Document Structure

  • MultiPage - Automatic page breaks with headers/footers
  • Theme - Consistent styling across documents
  • DefaultTextStyle - Cascading text style inheritance

📚 Documentation

Guides

Examples

🛠️ Development

Modern Development Stack

  • TypeScript 5.0+ with strict type checking (zero any types)
  • Vite for lightning-fast development
  • Vitest for testing with 100% coverage
  • ESLint + Prettier for code quality
  • Rollup for optimized production builds
  • pnpm for efficient package management

Setup

# Clone and setup
git clone https://github.com/nick-we/typescript-pdf.git
cd typescript-pdf
pnpm install

# Development
pnpm dev          # Start development server
pnpm test         # Run test suite (267/267 tests)
pnpm test:ui      # Visual test interface
pnpm build        # Production build
pnpm type-check   # TypeScript validation

Quality Metrics

  • 100% Test Coverage - 267/267 tests passing
  • Zero TypeScript Errors - Complete type safety
  • Perfect Code Quality - ESLint + Prettier compliance
  • Production Ready - Comprehensive error handling

📈 Project Status

Current Phase: Production Ready ✅

Completed Features

  • Phase 1: Foundation & TypeScript Setup
  • Phase 2: Low-Level PDF Engine
  • Phase 3: Widget System (15+ widgets)
  • Phase 4: Advanced Features & Multi-Page Support
  • Phase 5: Type Safety & Perfect Test Coverage

Roadmap - Next Phase

  • 🔄 Image Support: PNG, JPG, WebP, SVG widget implementation
  • 🔄 Form Elements: Interactive PDF forms and input fields
  • 🔄 Plugin System: Extensible architecture for third-party widgets
  • 🔄 Performance: Large document optimization and streaming

🤝 Contributing

We welcome contributions! typescript-pdf has achieved production stability with comprehensive test coverage.

Development Workflow

  1. Fork the repository
  2. Create feature branch: git checkout -b feature/amazing-feature
  3. Make changes with tests: All changes must maintain 100% test coverage
  4. Run validation: pnpm test && pnpm type-check && pnpm lint
  5. Submit PR with detailed description

Contribution Guidelines

  • Type Safety: No any types allowed - maintain complete type safety
  • Test Coverage: All new features must include comprehensive tests
  • Documentation: Update relevant docs and examples
  • Performance: Consider impact on layout and rendering performance

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Inspiration: dart-pdf - The original Dart PDF library
  • Architecture: Flutter widget system for declarative UI patterns
  • Community: TypeScript ecosystem and modern web development practices

📞 Support & Community


Made by Nick Westendorf

typescript-pdf v0.6.1 - PDF Generation for TypeScript