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

tt-pdf-generator

v1.3.1

Published

TT pdf generator - A powerful React-based PDF generation library for creating documents

Readme

TT PDF Generator

npm version License: MIT TypeScript

A powerful React-based PDF generation library for creating documents. Built with React-PDF, TypeScript, and modern web technologies.

✨ Features

  • 🚀 Fast PDF Generation - Built with React-PDF for optimal performance
  • 🎨 Template-Driven - JSON-based templates for easy customization
  • 🔧 Component-Based - Modular architecture with reusable components
  • 📱 Browser & Node.js - Works in both environments
  • 🎯 TypeScript Support - Full type definitions included
  • 📦 Multiple Formats - IIFE, ES Modules, and CommonJS support
  • 🎨 Rich Components - Text, Tables, Images, QR Codes, and more
  • 🔒 Secure - No external dependencies bundled

📦 Installation

npm install tt-pdf-generator

🚀 Quick Start

Basic Usage

For Node.js:

import { generatePdf } from 'tt-pdf-generator';

const template = JSON.stringify({
  components: [
    {
      type: 'Text',
      props: {
        children: 'Hello World!',
        style: { fontSize: 24, textAlign: 'center' },
      },
    },
  ],
});

const data = JSON.stringify({ name: 'John Doe' });

try {
  const pdfBuffer = await generatePdf(template, data);
  console.log('PDF generated successfully!');
} catch (error) {
  console.error('PDF generation failed:', error);
}

For Browser:

import { generatePdfBrowser } from 'tt-pdf-generator';

const template = JSON.stringify({
  components: [
    {
      type: 'Text',
      props: {
        children: 'Hello World!',
        style: { fontSize: 24, textAlign: 'center' },
      },
    },
  ],
});

const data = JSON.stringify({ name: 'John Doe' });

try {
  const pdfArrayBuffer = await generatePdfBrowser(template, data);

  // Convert to blob and download
  const blob = new Blob([pdfArrayBuffer], { type: 'application/pdf' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'document.pdf';
  a.click();
  URL.revokeObjectURL(url);
} catch (error) {
  console.error('PDF generation failed:', error);
}

⚠️ Important: Use generatePdfBrowser() for browser environments and generatePdf() for Node.js environments to avoid compatibility issues.

Advanced Template

const template = JSON.stringify({
  fonts: [
    {
      family: 'Helvetica',
      fonts: [
        {
          src: 'https://fonts.gstatic.com/s/helveticaneue/v70/1Ptsg8zYS_SKggPNyC0IT4ttDfA.ttf',
          fontWeight: 400,
        },
      ],
    },
  ],
  components: [
    {
      type: 'Text',
      props: {
        children: '{{companyName}}',
        style: { fontSize: 24, fontWeight: 'bold', textAlign: 'center' },
      },
    },
    {
      type: 'Table',
      props: {
        data: [
          ['Name', 'Policy Number', 'Date'],
          ['{{customerName}}', '{{policyNumber}}', '{{date}}'],
        ],
        style: { width: '100%', marginTop: 20 },
      },
    },
    {
      type: 'QrCode',
      props: {
        value: '{{qrCodeData}}',
        style: { width: 100, height: 100, marginTop: 20 },
      },
    },
  ],
});

🔧 Usage Examples

Browser Usage

<!DOCTYPE html>
<html>
  <head>
    <title>PDF Generator</title>
  </head>
  <body>
    <!-- Include React and React-PDF dependencies first -->
    <script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/@react-pdf/[email protected]/dist/react-pdf-renderer.umd.js"></script>

    <!-- Include the PDF generator library -->
    <script src="node_modules/tt-pdf-generator/dist/pdf-generator.browser.js"></script>

    <script>
      const { generatePdf } = PolicyPdfGenerator;

      async function createPDF() {
        const template = JSON.stringify({
          components: [
            {
              type: 'Text',
              props: {
                children: 'Hello World',
                style: { fontSize: 16 },
              },
            },
          ],
        });

        const data = JSON.stringify({ name: 'John' });

        try {
          const pdfBuffer = await generatePdf(template, data);

          // Download the PDF
          const blob = new Blob([pdfBuffer], { type: 'application/pdf' });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = 'document.pdf';
          a.click();
          URL.revokeObjectURL(url);
        } catch (error) {
          console.error('PDF generation failed:', error);
        }
      }

      createPDF();
    </script>
  </body>
</html>

Node.js Usage

const { generatePdf } = require('tt-pdf-generator');
const fs = require('fs');

async function createPDF() {
  const template = JSON.stringify({
    components: [
      {
        type: 'Text',
        props: {
          children: 'Hello World',
          style: { fontSize: 16 },
        },
      },
    ],
  });

  const data = JSON.stringify({ name: 'John' });

  try {
    const pdfBuffer = await generatePdf(template, data);

    // Save to file
    fs.writeFileSync('output.pdf', pdfBuffer);
    console.log('PDF generated successfully!');
  } catch (error) {
    console.error('PDF generation failed:', error);
  }
}

createPDF();

ES Modules

import { generatePdf } from 'tt-pdf-generator';

const template = JSON.stringify({
  components: [
    {
      type: 'Text',
      props: {
        children: 'Hello World',
        style: { fontSize: 16 },
      },
    },
  ],
});

const data = JSON.stringify({ name: 'John' });

const pdfBuffer = await generatePdf(template, data);

📚 API Reference

generatePdf(template, data)

Generates a PDF document based on the provided template and data.

Parameters:

  • template (string): JSON string containing the PDF template structure
  • data (string): JSON string containing the data to populate the template

Returns:

  • Promise<Buffer>: PDF buffer that can be saved to file or sent to browser

Template Structure:

interface Template {
  fonts?: Font[];
  components: Component[];
  images?: Record<string, string>;
}

interface Component {
  type: string;
  props: Record<string, any>;
}

🎨 Available Components

Text Component

{
  "type": "Text",
  "props": {
    "children": "Your text here",
    "style": {
      "fontSize": 16,
      "fontWeight": "bold",
      "color": "#000000",
      "textAlign": "center"
    }
  }
}

Table Component

{
  "type": "Table",
  "props": {
    "data": [
      ["Header 1", "Header 2"],
      ["Row 1 Col 1", "Row 1 Col 2"]
    ],
    "style": {
      "width": "100%"
    }
  }
}

Image Component

{
  "type": "Image",
  "props": {
    "src": "https://example.com/image.png",
    "style": {
      "width": 200,
      "height": 100
    }
  }
}

QR Code Component

{
  "type": "QrCode",
  "props": {
    "value": "https://example.com",
    "style": {
      "width": 100,
      "height": 100
    }
  }
}

🔧 Build & Development

Build Commands

# Build all versions
npm run build:all

# Build browser version only
npm run build:browser

# Build ES module version only
npm run build:esm

# Build CLI version
npm run build:cli

# Clean build directory
npm run clean

Development

# Install dependencies
npm install

# Start development server
npm run dev

# Type checking
npm run type-check

# Linting
npm run lint

# Format code
npm run format

📋 Requirements

Peer Dependencies

  • React >= 18.0.0
  • ReactDOM >= 18.0.0
  • @react-pdf/renderer >= 4.0.0

Browser Support

  • Modern browsers with ES2020+ support
  • ES Modules: Chrome 61+, Firefox 60+, Safari 10.1+
  • IIFE: All browsers supporting ES5+

🚨 Browser Compatibility

Critical: Use the Right Function!

The library provides different functions for different environments:

  • generatePdfBrowser() - For browser environments (returns ArrayBuffer)
  • generatePdf() - For Node.js environments (returns Buffer)
  • generatePdfNode() - Explicitly for Node.js (returns Buffer)

Browser Usage Example:

import { generatePdfBrowser } from 'tt-pdf-generator';

const pdfArrayBuffer = await generatePdfBrowser(template, data);
const blob = new Blob([pdfArrayBuffer], { type: 'application/pdf' });

Node.js Usage Example:

import { generatePdf } from 'tt-pdf-generator';

const pdfBuffer = await generatePdf(template, data);
fs.writeFileSync('output.pdf', pdfBuffer);

If you see the error "renderToBuffer is a Node specific API", you need to use generatePdfBrowser() instead of generatePdf() in your browser code.

For detailed browser compatibility information, see BROWSER_COMPATIBILITY.md.

🚀 Performance

  • Bundle Size: ~55KB minified
  • Memory Usage: Optimized for large documents
  • Rendering Speed: Fast PDF generation with React-PDF
  • Caching: Built-in component caching for repeated elements

🤝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

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

🆘 Support

🙏 Acknowledgments


Made with ❤️ by milad-a-kareem