导出 PDF
将文档页面导出为 PDF 文件
概览
🌐 Overview
总体而言,我们强烈建议你下载整个网站(HTML 文件等)以供离线浏览。
🌐 In general, we strongly recommend you to download the entire website (HTML files, etc) for offline browsing.
如果你想将页面导出为 PDF,可以参考本指南。
🌐 In case if you want to export the page as a PDF, you can follow this guide.
安装
🌐 Setup
使用 Puppeteer 导出 PDF 文件。
🌐 Use Puppeteer to export PDF files.
import puppeteer from 'puppeteer';
import fs from 'node:fs/promises';
import path from 'node:path';
const browser = await puppeteer.launch();
const outDir = 'pdfs';
// update this
const urls = ['/docs/ui', '/docs/ui/customisations'];
async function exportPdf(pathname: string) {
const page = await browser.newPage();
await page.goto('http://localhost:3000' + pathname, {
waitUntil: 'networkidle2',
});
await page.pdf({
path: path.join(outDir, pathname.slice(1).replaceAll('/', '-') + '.pdf'),
width: 950,
printBackground: true,
});
console.log(`PDF generated successfully for ${pathname}`);
await page.close();
}
await fs.mkdir(outDir, { recursive: true });
await Promise.all(urls.map(exportPdf));
await browser.close();将以下内容添加到你的 Tailwind CSS 文件中,以在打印时禁用导航元素:
🌐 Add the following to your Tailwind CSS file to disable navigation elements when printing:
@media print {
#nd-docs-layout {
--fd-sidebar-width: 0px !important;
}
#nd-sidebar {
display: none;
}
}你现在可以运行脚本了:
🌐 You can now run the script:
bun ./scripts/export-pdf.ts隐形内容
🌐 Invisible Contents
对于手风琴/标签中的不可见内容,你可能需要暂时覆盖 MDX 组件。例如:
🌐 For invisible contents in accordions/tabs, you may need to temporarily override the MDX components. For example:
import defaultMdxComponents from 'fumadocs-ui/mdx';
import type { MDXComponents } from 'mdx/types';
import { Accordion, Accordions } from 'fumadocs-ui/components/accordion';
// you may use environment variable here
const isPrinting = true;
export function getMDXComponents(components?: MDXComponents) {
const PrintingAccordion: typeof Accordion = (props) => (
<div>
<h3>{props.title}</h3>
{props.children}
</div>
);
return {
...defaultMdxComponents,
// updated accordions:
Accordion: isPrinting ? PrintingAccordion : Accordion,
Accordions: isPrinting ? 'div' : Accordions,
...components,
} satisfies MDXComponents;
}Last updated on
