html-to-media
v1.0.1
Published
Convert HTML to PNG, JPG, PDF, WebP, GIF, or Video - Works with Node.js, Express, Next.js, and React
Maintainers
Readme
🎨 html-to-media
Convert HTML to PNG, JPG, PDF, WebP, GIF, or Video
Transform any HTML content into multiple media formats with ease. Perfect for generating reports, screenshots, thumbnails, and more!
Installation • Quick Start • Examples • API
✨ Features
- 📄 PDF Generation - Create professional PDFs with custom formatting
- 🖼️ Image Export - PNG, JPG, WebP with full customization
- 🎬 Video & GIF - Capture animated content (requires ffmpeg)
- ⚡ Fast & Reliable - Built on Puppeteer for consistent results
- 🎯 Framework Support - Works with Node.js, Express, Next.js, React
- 🔧 Highly Configurable - Control dimensions, quality, margins, and more
- 💪 Production Ready - Error handling, validation, and cleanup built-in
📦 Installation
npm install html-to-mediaFor GIF and Video support, install ffmpeg:
# macOS
brew install ffmpeg
# Ubuntu/Debian
sudo apt install ffmpeg
# Windows
choco install ffmpeg🚀 Quick Start
const { htmlToPdf, htmlToPng, htmlToJpg } = require('html-to-media');
const html = '<h1>Hello World!</h1><p>My first document</p>';
// Generate PDF
await htmlToPdf(html, 'output.pdf');
// Generate PNG
await htmlToPng(html, 'output.png');
// Generate JPG with options
await htmlToJpg(html, 'output.jpg', {
width: 1920,
height: 1080,
quality: 95
});📚 Examples
Basic Usage
const { htmlToPdf, htmlToPng, htmlToJpg, htmlToWebp } = require('html-to-media');
const html = `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial; padding: 20px; }
h1 { color: #333; }
</style>
</head>
<body>
<h1>Professional Document</h1>
<p>Generated with html-to-media</p>
</body>
</html>
`;
// PDF with custom options
await htmlToPdf(html, 'report.pdf', {
format: 'A4',
landscape: false,
margin: { top: '20px', bottom: '20px', left: '20px', right: '20px' },
printBackground: true
});
// PNG with transparent background
await htmlToPng(html, 'thumbnail.png', {
width: 1200,
height: 630,
background: false
});
// High-quality JPG
await htmlToJpg(html, 'preview.jpg', {
quality: 95,
fullPage: true
});
// WebP for web optimization
await htmlToWebp(html, 'image.webp', {
quality: 85
});Object Notation
import htmlToMedia from 'html-to-media';
const html = '<h1>Hello World</h1>';
await htmlToMedia.pdf(html, 'output.pdf');
await htmlToMedia.png(html, 'output.png');
await htmlToMedia.jpg(html, 'output.jpg');GIF & Video (requires ffmpeg)
const { htmlToGif, htmlToVideo } = require('html-to-media');
const animatedHtml = `
<html>
<body>
<h1 id="counter">0</h1>
<script>
let count = 0;
setInterval(() => {
document.getElementById('counter').textContent = count++;
}, 100);
</script>
</body>
</html>
`;
// Generate GIF
await htmlToGif(animatedHtml, 'animation.gif', {
duration: 3000, // 3 seconds
fps: 10,
width: 800,
height: 600
});
// Generate Video
await htmlToVideo(animatedHtml, 'video.mp4', {
duration: 5000, // 5 seconds
fps: 30,
width: 1920,
height: 1080
});⚛️ React & Next.js Integration
Next.js API Route
// pages/api/generate-pdf.js
import { htmlToPdf } from 'html-to-media';
import path from 'path';
export default async function handler(req, res) {
try {
const { html } = req.body;
const outputPath = path.join(process.cwd(), 'public', `output-${Date.now()}.pdf`);
const result = await htmlToPdf(html, outputPath);
res.status(200).json({
success: true,
url: `/output-${Date.now()}.pdf`
});
} catch (error) {
res.status(500).json({ error: error.message });
}
}React Component
import { useState } from 'react';
export default function PdfGenerator() {
const [loading, setLoading] = useState(false);
const [pdfUrl, setPdfUrl] = useState(null);
const generatePdf = async () => {
setLoading(true);
const html = `
<html>
<body>
<h1>My Report</h1>
<p>Generated on ${new Date().toLocaleDateString()}</p>
</body>
</html>
`;
const response = await fetch('/api/generate-pdf', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ html })
});
const data = await response.json();
setPdfUrl(data.url);
setLoading(false);
};
return (
<div>
<button onClick={generatePdf} disabled={loading}>
{loading ? 'Generating...' : 'Generate PDF'}
</button>
{pdfUrl && (
<a href={pdfUrl} download>
Download PDF
</a>
)}
</div>
);
}Next.js Server Actions (App Router)
// app/actions.js
'use server';
import { htmlToPdf } from 'html-to-media';
import path from 'path';
export async function generatePdf(html) {
const filename = `report-${Date.now()}.pdf`;
const outputPath = path.join(process.cwd(), 'public', filename);
await htmlToPdf(html, outputPath);
return `/${filename}`;
}// app/page.jsx
'use client';
import { generatePdf } from './actions';
import { useState } from 'react';
export default function Home() {
const [pdfUrl, setPdfUrl] = useState(null);
const handleGenerate = async () => {
const html = '<h1>Server Action PDF</h1>';
const url = await generatePdf(html);
setPdfUrl(url);
};
return (
<div>
<button onClick={handleGenerate}>Generate PDF</button>
{pdfUrl && <a href={pdfUrl}>Download</a>}
</div>
);
}📖 API Reference
htmlToPdf(html, outputPath, options)
Generate a PDF from HTML.
Parameters:
html(string) - HTML contentoutputPath(string) - Output file pathoptions(object) - Optional configuration
Options:
{
width: 1920, // Viewport width (px)
height: 1080, // Viewport height (px)
format: 'A4', // Paper format: A4, Letter, A3, etc.
landscape: false, // Landscape orientation
margin: { // Page margins
top: '20px',
bottom: '20px',
left: '20px',
right: '20px'
},
printBackground: true // Include background graphics
}Returns: Promise<{ success: boolean, path: string }>
htmlToPng(html, outputPath, options)
Generate a PNG image from HTML.
Options:
{
width: 1920, // Viewport width (px)
height: 1080, // Viewport height (px)
fullPage: true, // Capture full page
background: true // Include background (false for transparent)
}Returns: Promise<{ success: boolean, path: string }>
htmlToJpg(html, outputPath, options)
Generate a JPG image from HTML.
Options:
{
width: 1920, // Viewport width (px)
height: 1080, // Viewport height (px)
quality: 90, // Image quality (1-100)
fullPage: true // Capture full page
}Returns: Promise<{ success: boolean, path: string }>
htmlToWebp(html, outputPath, options)
Generate a WebP image from HTML.
Options:
{
width: 1920, // Viewport width (px)
height: 1080, // Viewport height (px)
quality: 90, // Image quality (1-100)
fullPage: true // Capture full page
}Returns: Promise<{ success: boolean, path: string }>
htmlToGif(html, outputPath, options)
Generate an animated GIF from HTML. Requires ffmpeg.
Options:
{
width: 800, // Viewport width (px)
height: 600, // Viewport height (px)
duration: 3000, // Recording duration (ms)
fps: 10 // Frames per second
}Returns: Promise<{ success: boolean, path: string, frames: number }>
htmlToVideo(html, outputPath, options)
Generate a video from HTML. Requires ffmpeg.
Options:
{
width: 1920, // Viewport width (px)
height: 1080, // Viewport height (px)
duration: 5000, // Recording duration (ms)
fps: 30 // Frames per second
}Returns: Promise<{ success: boolean, path: string, frames: number, duration: number, fps: number }>
🛠️ Use Cases
- 📊 Report Generation - Create PDF reports from HTML templates
- 🖼️ Social Media Images - Generate Open Graph images
- 📸 Website Screenshots - Capture page previews
- 🎨 Thumbnail Creation - Auto-generate video thumbnails
- 📧 Email Attachments - Convert HTML emails to PDF
- 🎬 Animated Content - Create GIFs from dynamic HTML
⚠️ Important Notes
- Server-Side Only: This package uses Puppeteer (headless Chrome) and must run on the server
- ffmpeg Required: GIF and video generation requires ffmpeg to be installed
- Memory Usage: Large pages or long videos may consume significant memory
- Async Operations: All functions return Promises and should be awaited
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📄 License
MIT © Janak Sanjel
🔗 Links
Made with ❤️ by Janak Sanjel
⭐ Star this repo if you find it helpful!
