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

libo-htmltopdf

v1.0.0

Published

A lightweight HTML to PDF conversion plugin for frontend developers

Readme

libo-htmltopdf

一个轻量级的HTML转PDF插件,支持在浏览器环境中将HTML元素转换为PDF文件并提供下载功能。

✨ 特性

  • 🚀 轻量级:基于html2canvas和jsPDF,体积小巧
  • 🎯 易用性:简单的API设计,开箱即用
  • 🔧 可配置:丰富的配置选项,满足不同需求
  • 📱 兼容性:支持现代浏览器,包括移动端
  • 🎨 高质量:支持高分辨率输出和自定义样式
  • 📦 TypeScript:完整的类型定义支持

📦 安装

NPM 安装

npm install libo-htmltopdf

或者使用yarn:

yarn add libo-htmltopdf

浏览器直接使用

如果您想在独立的HTML页面中直接使用该插件,可以通过以下方式:

方式一:CDN 引入(推荐)

<!DOCTYPE html>
<html>
<head>
    <title>HTML转PDF示例</title>
</head>
<body>
    <div id="content">
        <h1>这是要转换的内容</h1>
        <p>这里是一些文本内容...</p>
    </div>
    
    <button onclick="convertToPdf()">下载PDF</button>
    
    <!-- 引入插件 -->
    <script src="https://unpkg.com/libo-htmltopdf@latest/dist/libo-htmltopdf.umd.js"></script>
    
    <script>
        async function convertToPdf() {
            try {
                // 使用全局变量 LiboHtmlToPdf
                await LiboHtmlToPdf.downloadPdf('#content', 'my-document.pdf', {
                    format: 'a4',
                    quality: 1.0,
                    margin: { top: 20, right: 20, bottom: 20, left: 20 }
                });
            } catch (error) {
                console.error('PDF生成失败:', error);
            }
        }
    </script>
</body>
</html>

方式二:本地文件引入

如果您已经下载了插件文件,可以直接引入:

<!DOCTYPE html>
<html>
<head>
    <title>HTML转PDF示例</title>
</head>
<body>
    <div id="content">
        <h1>标题</h1>
        <p>内容...</p>
    </div>
    
    <button onclick="handleDownload()">下载PDF</button>
    
    <!-- 引入本地文件 -->
    <script src="./path/to/libo-htmltopdf.umd.js"></script>
    
    <script>
        // 配置默认选项
        LiboHtmlToPdf.configure({
            quality: 0.9,
            format: 'a4'
        });
        
        async function handleDownload() {
            // 下载PDF
            await LiboHtmlToPdf.downloadPdf('#content', 'document.pdf');
        }
        
        async function handlePreview() {
            // 预览PDF
            await LiboHtmlToPdf.previewPdf('#content');
        }
    </script>
</body>
</html>

完整示例

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML转PDF完整示例</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .content {
            border: 1px solid #ddd;
            padding: 20px;
            margin: 20px 0;
        }
        .buttons {
            text-align: center;
            margin: 20px 0;
        }
        button {
            padding: 10px 20px;
            margin: 0 10px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background: #0056b3;
        }
    </style>
</head>
<body>
    <h1>HTML转PDF插件示例</h1>
    
    <div class="buttons">
        <button onclick="downloadPdf()">下载PDF</button>
        <button onclick="previewPdf()">预览PDF</button>
        <button onclick="downloadHighQuality()">高质量下载</button>
    </div>
    
    <div id="pdf-content" class="content">
        <h2>这是要转换为PDF的内容</h2>
        <p>这是一个段落,包含一些文本内容。</p>
        
        <h3>列表示例</h3>
        <ul>
            <li>列表项目 1</li>
            <li>列表项目 2</li>
            <li>列表项目 3</li>
        </ul>
        
        <h3>表格示例</h3>
        <table border="1" style="width: 100%; border-collapse: collapse;">
            <tr>
                <th>姓名</th>
                <th>年龄</th>
                <th>城市</th>
            </tr>
            <tr>
                <td>张三</td>
                <td>25</td>
                <td>北京</td>
            </tr>
            <tr>
                <td>李四</td>
                <td>30</td>
                <td>上海</td>
            </tr>
        </table>
    </div>
    
    <!-- 引入插件 -->
    <script src="https://unpkg.com/libo-htmltopdf@latest/dist/libo-htmltopdf.umd.js"></script>
    
    <script>
        // 基础下载
        async function downloadPdf() {
            try {
                await LiboHtmlToPdf.downloadPdf('#pdf-content', 'example.pdf');
            } catch (error) {
                alert('PDF生成失败: ' + error.message);
            }
        }
        
        // 预览PDF
        async function previewPdf() {
            try {
                await LiboHtmlToPdf.previewPdf('#pdf-content');
            } catch (error) {
                alert('PDF预览失败: ' + error.message);
            }
        }
        
        // 高质量下载
        async function downloadHighQuality() {
            try {
                await LiboHtmlToPdf.downloadPdf('#pdf-content', 'high-quality.pdf', {
                    format: 'a4',
                    orientation: 'portrait',
                    quality: 1.0,
                    scale: 2.0,
                    margin: {
                        top: 20,
                        right: 20,
                        bottom: 20,
                        left: 20
                    }
                });
            } catch (error) {
                alert('PDF生成失败: ' + error.message);
            }
        }
    </script>
</body>
</html>

🚀 快速开始

基础用法

import { downloadPdf } from 'libo-htmltopdf';

// 下载整个页面为PDF
await downloadPdf(document.body, 'my-document.pdf');

// 下载指定元素为PDF
await downloadPdf('#content', 'content.pdf');

高级用法

import { htmlToPdf, downloadPdf, configure, presets } from 'libo-htmltopdf';

// 配置默认选项
configure({
  quality: 1.0,
  format: 'a4',
  margin: { top: 20, right: 20, bottom: 20, left: 20 }
});

// 生成PDF Blob对象
const pdfBlob = await htmlToPdf('#content', {
  quality: 0.9,
  scale: 2.0
});

// 使用预设配置
await downloadPdf('#content', 'document.pdf', presets.highQuality);

📚 API 文档

核心方法

htmlToPdf(element, options?)

将HTML元素转换为PDF Blob对象。

参数:

  • element (HTMLElement | string): HTML元素或CSS选择器
  • options (PdfOptions): 可选的配置选项

返回: Promise<Blob>

const pdfBlob = await htmlToPdf('#content', {
  format: 'a4',
  quality: 1.0
});

downloadPdf(element, filename?, options?)

直接下载PDF文件。

参数:

  • element (HTMLElement | string): HTML元素或CSS选择器
  • filename (string): 文件名,默认为'document.pdf'
  • options (PdfOptions): 可选的配置选项

返回: Promise<void>

await downloadPdf('#content', 'my-report.pdf', {
  orientation: 'landscape',
  margin: { top: 10, right: 10, bottom: 10, left: 10 }
});

previewPdf(element, options?)

在新窗口中预览PDF。

参数:

  • element (HTMLElement | string): HTML元素或CSS选择器
  • options (PdfOptions): 可选的配置选项

返回: Promise<void>

await previewPdf('#content');

配置方法

configure(options)

设置全局默认配置。

configure({
  quality: 0.9,
  format: 'a4',
  orientation: 'portrait'
});

getConfig()

获取当前配置。

resetConfig()

重置为默认配置。

setDebug(enabled)

启用或禁用调试模式。

配置选项 (PdfOptions)

interface PdfOptions {
  format?: PdfFormat;           // PDF格式:'a4', 'a3', 'letter' 等
  orientation?: 'portrait' | 'landscape'; // 页面方向
  quality?: number;             // 图像质量 (0-1)
  scale?: number;               // 缩放比例
  margin?: MarginConfig;        // 页边距配置
  backgroundColor?: string;     // 背景颜色
  allowTaint?: boolean;         // 允许跨域图像
  useCORS?: boolean;           // 使用CORS
  width?: number;              // 自定义宽度
  height?: number;             // 自定义高度
}

interface MarginConfig {
  top?: number;
  right?: number;
  bottom?: number;
  left?: number;
}

预设配置

插件提供了几种预设配置:

import { presets } from 'libo-htmltopdf';

// 高质量配置(适用于打印)
presets.highQuality

// 快速配置(适用于预览)
presets.fast

// 移动端配置
presets.mobile

// 横向配置
presets.landscape

🎯 使用场景

1. 报告生成

// 生成数据报告
await downloadPdf('.report-container', 'monthly-report.pdf', {
  format: 'a4',
  quality: 1.0,
  margin: { top: 20, right: 20, bottom: 20, left: 20 }
});

2. 发票/收据

// 下载发票
await downloadPdf('#invoice', `invoice-${invoiceNumber}.pdf`, presets.highQuality);

3. 证书/文档

// 生成证书
await downloadPdf('.certificate', 'certificate.pdf', {
  format: 'a4',
  orientation: 'landscape',
  quality: 1.0
});

4. 网页截图

// 保存网页为PDF
await downloadPdf(document.body, 'webpage-snapshot.pdf');

⚠️ 注意事项

  1. 浏览器兼容性:需要现代浏览器支持(IE11+)
  2. 跨域图像:如果页面包含跨域图像,需要设置allowTaint: trueuseCORS: true
  3. 性能考虑:大型页面转换可能需要较长时间,建议显示加载提示
  4. 样式限制:某些CSS样式可能无法完美转换,建议测试关键样式

🔧 开发

# 克隆项目
git clone <repository-url>
cd libo-htmltopdf

# 安装依赖
npm install

# 开发模式
npm run dev

# 构建
npm run build

# 测试
npm test

# 发布
npm publish

📄 许可证

MIT License

🤝 贡献

欢迎提交Issue和Pull Request!

📞 支持

如果您在使用过程中遇到问题,请:

  1. 查看示例文件
  2. 提交Issue
  3. 查看文档

Made with ❤️ by Libo