tt-pdf-generator
v1.3.1
Published
TT pdf generator - A powerful React-based PDF generation library for creating documents
Maintainers
Readme
TT PDF Generator
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 structuredata(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 cleanDevelopment
# 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
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🆘 Support
🙏 Acknowledgments
- Built with React-PDF
- Powered by esbuild
- Styled with Tailwind CSS
Made with ❤️ by milad-a-kareem
