转换代码
安装markdown-it 和puppeteer
- markdown-it 将md转成html
- puppeteer 将html转换成pdf
代码示例
import MarkdownIt from 'markdown-it';
import puppeteer from 'puppeteer';
const md = MarkdownIt();
const launchOptions = {
headless: true, // 是否启动无头模式,即无界面模式
timeout: 0, // 设置超时时间为无限制,单位毫秒,默认是 30000ms
args: ['--no-sandbox', '--disable-setuid-sandbox'], // 配置浏览器启动参数,解决一些运行问题
};
async function convertMarkdownToPdf(markdownFilePath, pdfOutputPath) {
try {
const markdownContent = fs.readFileSync(markdownFilePath, 'utf-8');
// 将Markdown转换为HTML
const htmlContent = md.render(markdownContent);
// 启动Puppeteer
const browser = await puppeteer.launch(launchOptions);
const page = await browser.newPage();
// 加载HTML内容
await page.setContent(htmlContent);
// 生成PDF
await page.pdf({ path: pdfOutputPath,
format: 'A4',
margin: {left: 30, top:30, right:30, bottom:30},
printBackground: true,
displayHeaderFooter: true });
// 关闭浏览器
await browser.close();
console.log('PDF文件已生成:', pdfOutputPath);
} catch (error) {
console.error(markdownFilePath, '转换Markdown到PDF时出错:', error);
}
}
PDF 配置
官网可查:pptr.nodejs.cn/api/puppete…
属性 | 修饰符 | 类型 | 描述 | 默认 |
|---|---|---|---|---|
| boolean | 是否显示页眉和页脚。 |
| |
| string | 打印页脚的 HTML 模板。对特殊类具有与 PDFOptions.headerTemplate 相同的约束和支持。 | ||
| format |
| 评论: 如果设置,则该选项优先于 |
| |
| headerTemplate |
| string | 打印标题的 HTML 模板。应该是有效的 HTML,其中包含用于向其中注入值的以下类:
| |
| height |
| 字符串| 数字 | 设置纸张的高度。你可以传入一个数字或带有单位的字符串。 | |
| landscape |
| boolean | 是否横向打印。 |
|
| margin |
| 设置 PDF 页边距。 |
| |
| omitBackground |
| boolean | 隐藏默认的白色背景并允许生成具有透明度的 pdf。 |
|
| outline |
| boolean | (实验性)生成文档大纲。 评论: 如果启用此功能,PDF 也将被标记(可访问) 目前仅适用于旧版 Headless(headless = 'shell')Chrom 功能请求 |
|
| pageRanges |
| string | 要打印的纸张范围,例如 | 空字符串,表示打印所有页面。 |
| path |
| string | 文件保存的路径。 评论: 如果路径是相对路径,则相对于当前工作目录进行解析。 |
|
| 首选 CSS 页面大小 |
| boolean | 使页面中声明的任何 CSS |
|
| printBackground |
| boolean | 设置为 |
|
| scale |
| 数字 | 缩放网页的渲染。金额必须介于 |
|
| tagged |
| boolean | (实验性)生成带标签的(可访问的)PDF。 |
|
| timeout |
| 数字 | 超时(以毫秒为单位)。通过 |
|
| width |
| 字符串| 数字 | 设置纸张宽度。你可以传入一个数字或带有单位的字符串。 |