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 🙏

© 2026 – Pkg Stats / Ryan Hefner

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

Readme

🎨 html-to-media

Convert HTML to PNG, JPG, PDF, WebP, GIF, or Video

npm version License: MIT Downloads

Transform any HTML content into multiple media formats with ease. Perfect for generating reports, screenshots, thumbnails, and more!

InstallationQuick StartExamplesAPI


✨ 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-media

For 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 content
  • outputPath (string) - Output file path
  • options (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!