markdown-pdf 中文教程

1. 项目概述

markdown-pdf 是一个基于 Node.js 的工具,用于将 Markdown 文件转换为 PDF 文档。它使用 Marked 解析 Markdown 内容,使用 PhantomJS 渲染 HTML 并生成 PDF。它提供了简单易用的命令行接口和编程 API,允许开发者快速将 Markdown 文档转换为格式精美的 PDF 文件。

2. 核心功能

2.1 基本功能

  • Markdown 转换:将 Markdown 文件转换为 PDF 文档
  • 命令行接口:通过命令行快速转换文件
  • 编程 API:在代码中集成转换功能
  • 默认样式:提供美观的默认样式
  • 输出选项:指定输出文件路径

2.2 高级功能

  • 自定义样式:使用自定义 CSS 样式
  • 自定义模板:使用自定义 HTML 模板
  • 目录生成:自动生成文档目录
  • 代码高亮:支持代码块语法高亮
  • 图片支持:处理 Markdown 中的图片
  • 页眉页脚:添加和设置页眉页脚
  • 页面设置:设置页面大小、边距、方向等

3. 安装与设置

3.1 在 Node.js 环境中安装

npm install -g markdown-pdf  # 全局安装

或者在项目中本地安装:

npm install --save markdown-pdf  # 本地安装

3.2 基本配置

markdown-pdf 不需要额外的配置,但需要注意它依赖于 PhantomJS,安装过程中会自动下载。

4. 基本使用示例

4.1 使用命令行

# 转换单个文件
markdown-pdf input.md -o output.pdf

# 转换多个文件
markdown-pdf input1.md input2.md -o combined.pdf

# 使用管道
cat input.md | markdown-pdf > output.pdf

4.2 在代码中使用

// 导入库
const markdownpdf = require('markdown-pdf');
const fs = require('fs');

// 读取 Markdown 文件
const markdown = fs.readFileSync('input.md', 'utf8');

// 转换并保存为 PDF 文件
markdownpdf().from.string(markdown).to('output.pdf', function () {
  console.log('PDF 文档创建成功!');
});

4.3 流式接口

// 导入库
const markdownpdf = require('markdown-pdf');
const fs = require('fs');

// 使用流式接口
fs.createReadStream('input.md')
  .pipe(markdownpdf())
  .pipe(fs.createWriteStream('output.pdf'))
  .on('finish', function () {
    console.log('PDF 文档创建成功!');
  });

4.4 基本选项

// 导入库
const markdownpdf = require('markdown-pdf');

// 设置选项
const options = {
  format: 'A4',
  orientation: 'portrait',
  border: '10mm',
 phantomPath: require('phantomjs-prebuilt').path // 自定义 PhantomJS 路径
};

// 转换文件
markdownpdf(options)
  .from('input.md')
  .to('output.pdf', function () {
    console.log('PDF 文档创建成功!');
  });

5. 高级用法

5.1 使用自定义样式

// 导入库
const markdownpdf = require('markdown-pdf');

// 设置选项
const options = {
  cssPath: 'style.css', // 自定义 CSS 文件路径
  highlightCssPath: 'highlight.css' // 代码高亮 CSS 文件路径
};

// 转换文件
markdownpdf(options)
  .from('input.md')
  .to('output.pdf', function () {
    console.log('带自定义样式的 PDF 文档创建成功!');
  });

5.2 使用自定义模板

// 导入库
const markdownpdf = require('markdown-pdf');

// 设置选项
const options = {
  templatePath: 'template.html' // 自定义 HTML 模板文件路径
};

// 转换文件
markdownpdf(options)
  .from('input.md')
  .to('output.pdf', function () {
    console.log('带自定义模板的 PDF 文档创建成功!');
  });

5.3 生成目录

// 导入库
const markdownpdf = require('markdown-pdf');

// 设置选项
const options = {
  remarkable: {
    plugins: [
      require('remarkable-contents') // 目录插件
    ]
  }
};

// 转换文件
markdownpdf(options)
  .from('input.md')
  .to('output.pdf', function () {
    console.log('带目录的 PDF 文档创建成功!');
  });

5.4 自定义 PhantomJS 选项

// 导入库
const markdownpdf = require('markdown-pdf');

// 设置选项
const options = {
  phantomArgs: [
    '--ignore-ssl-errors=yes',
    '--local-to-remote-url-access=yes',
    '--ssl-protocol=any'
  ],
  phantomPath: require('phantomjs-prebuilt').path
};

// 转换文件
markdownpdf(options)
  .from('input.md')
  .to('output.pdf', function () {
    console.log('PDF 文档创建成功!');
  });

6. 实际应用场景

6.1 文档生成

将 Markdown 格式的文档转换为 PDF 格式,用于正式发布或打印。

6.2 报告生成

使用 Markdown 编写报告,然后转换为 PDF 格式,便于分享和打印。

6.3 技术文档

将技术文档从 Markdown 转换为 PDF 格式,提供给用户或客户。

6.4 教育内容

为在线课程生成 PDF 格式的教材和讲义。

6.5 简历生成

使用 Markdown 编写简历,然后转换为 PDF 格式,保持格式一致性。

7. 代码优化建议

7.1 模块化设计

将 PDF 生成逻辑拆分为多个模块,提高代码可维护性:

// PDF 生成器模块
class PdfGenerator {
  constructor() {
    this.markdownpdf = require('markdown-pdf');
  }

  createPdf(input, output, options = {}) {
    return new Promise((resolve, reject) => {
      this.markdownpdf(options)
        .from(input)
        .to(output, function (err) {
          if (err) reject(err);
          else resolve();
        });
    });
  }

  createReport(markdownContent, outputPath) {
    const options = {
      format: 'A4',
      border: '10mm',
      cssPath: 'report.css'
    };
    
    return this.createPdf(markdownContent, outputPath, options);
  }
}

// 使用示例
const generator = new PdfGenerator();
generator.createReport('# 销售报告\n\n这是一份销售报告。', 'sales-report.pdf')
  .then(() => {
    console.log('报告生成成功!');
  })
  .catch(err => {
    console.error('生成报告时出错:', err);
  });

7.2 错误处理

添加适当的错误处理,提高代码健壮性:

try {
  const markdownpdf = require('markdown-pdf');
  
  markdownpdf()
    .from('input.md')
    .to('output.pdf', function (err) {
      if (err) {
        console.error('创建 PDF 文档时出错:', err);
        // 处理错误
        return;
      }
      console.log('PDF 文档创建成功!');
    });
} catch (error) {
  console.error('初始化 PDF 生成器时出错:', error);
  // 处理错误
}

7.3 性能优化

对于大型 Markdown 文件,使用流式接口:

const markdownpdf = require('markdown-pdf');
const fs = require('fs');

// 使用流式接口处理大型文件
const inputStream = fs.createReadStream('large-document.md');
const outputStream = fs.createWriteStream('large-document.pdf');

inputStream
  .pipe(markdownpdf())
  .pipe(outputStream)
  .on('finish', function () {
    console.log('大型 PDF 文档创建成功!');
  })
  .on('error', function (err) {
    console.error('创建 PDF 文档时出错:', err);
  });

7.4 内存管理

对于大型 Markdown 文件,注意内存使用:

const markdownpdf = require('markdown-pdf');
const fs = require('fs');

// 避免一次性加载大型 Markdown 文件到内存
function generatePdfFromFile(inputFile, outputFile) {
  const inputStream = fs.createReadStream(inputFile);
  const outputStream = fs.createWriteStream(outputFile);
  
  inputStream
    .pipe(markdownpdf())
    .pipe(outputStream)
    .on('finish', function () {
      console.log('PDF 文档创建成功:', outputFile);
    })
    .on('error', function (err) {
      console.error('创建 PDF 文档时出错:', err);
    });
}

// 使用示例
generatePdfFromFile('large-document.md', 'large-document.pdf');

8. 总结

markdown-pdf 是一个功能强大、灵活易用的工具,为开发者提供了将 Markdown 转换为 PDF 文档的能力。它的主要优势包括:

  • 易于使用:简单的命令行接口和编程 API
  • 功能丰富:支持从基本转换到复杂的自定义样式、模板等
  • 高度可定制:支持多种配置选项和高级功能
  • 稳定可靠:基于成熟的 Marked 和 PhantomJS 技术

通过本教程的学习,您应该已经掌握了 markdown-pdf 的基本用法和一些高级技巧,可以开始在实际项目中应用它来生成 PDF 文档了。

9. 参考资源

« 上一篇 html-pdf 中文教程 下一篇 » pptxgenjs-vite 中文教程