コンテンツへスキップ
Fumadocs

PDF エクスポート

ドキュメントページを PDF としてエクスポートします

概要

オフラインで閲覧する場合は、基本的にWebサイト全体 (HTMLファイルなど) をダウンロードすることを強くおすすめします。

ページをPDFとしてエクスポートしたい場合は、このガイドを参照してください。

セットアップ

Puppeteer を使用して PDF ファイルをエクスポートします。

scripts/export-pdf.ts
import puppeteer from 'puppeteer';
import fs from 'node:fs/promises';
import path from 'node:path';

const browser = await puppeteer.launch();
const outDir = 'pdfs';
// ここを更新してください
const urls = ['/docs/ui', '/docs/ui/customizations'];

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 ファイルに以下を追加してください。

@media print {
  #nd-docs-layout {
    --fd-sidebar-width: 0px !important;
  }

  #nd-sidebar {
    display: none;
  }
}

これでスクリプトを実行できます。

bun ./scripts/export-pdf.ts

非表示のコンテンツ

アコーディオンやタブ内の非表示のコンテンツについては、MDX コンポーネントを一時的にオーバーライドする必要がある場合があります。例えば次のようにします。

components/mdx.tsx
import defaultMdxComponents from 'fumadocs-ui/mdx';
import type { MDXComponents } from 'mdx/types';
import { Accordion, Accordions } from 'fumadocs-ui/components/accordion';

// ここで環境変数を使うこともできます
const isPrinting = true;

function PrintingAccordion(props: React.ComponentProps<typeof Accordion>) {
  return (
    <div>
      <h3>{props.title}</h3>
      {props.children}
    </div>
  );
}

function PrintingAccordions(props: React.ComponentProps<typeof Accordions>) {
  return <div>{props.children}</div>;
}

export function getMDXComponents(components?: MDXComponents) {
  return {
    ...defaultMdxComponents,
    // 差し替えたアコーディオン:
    Accordion: isPrinting ? PrintingAccordion : Accordion,
    Accordions: isPrinting ? PrintingAccordions : Accordions,
    ...components,
  } satisfies MDXComponents;
}

How is this guide?

最終更新日