はじめに
この記事では。PDF を生成するライブラリである React-pdf の基本的な使い方について記載します。
開発環境
開発環境は以下の通りです。
- Windows11
- React 18.3.1
- React-pdf 3.4.4
- TypeScript 5.5.3
- Node.js 20.13.1
インストール
まずは React-pdf をインストールします。
npm install @react-pdf/renderer --save
PDF の生成
React-pdf が提供するコンポーネントや API を利用して PDF のスタイルを定義します。
PDFDocument.tsx
import {
Document,
Page,
StyleSheet,
Text,
View,
} from "@react-pdf/renderer";
import { FC } from "react";
const styles = StyleSheet.create({
page: {
flexDirection: "row",
backgroundColor: "#E4E4E4",
},
section: {
margin: 10,
padding: 10,
flexGrow: 1,
},
});
const PDFDocument: FC = () => (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>Section #1</Text>
</View>
<View style={styles.section}>
<Text>Section #2</Text>
</View>
</Page>
</Document>
);
React-pdf が提供するコンポーネント(タグ)を利用しても表示されません。
PDFDocument.tsx
export const PDFDocument: FC = () => (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>Section #1</Text>
<Text>text</Text>
<p>paragraph</p>
</View>
<View style={styles.section}>
<Text>Section #2</Text>
</View>
</Page>
</Document>
);
PDF のレンダリング
先ほど作成した PDF を PDFViewe
というコンポーネントを利用してレンダリングします。
App.tsx
import { PDFViewer } from "@react-pdf/renderer";
import { FC } from "react";
import { PDFDocument } from "../components/PDFDocument";
export const PDF: FC = () => (
<PDFViewer width="100%" height="100%">
<PDFDocument />
</PDFViewer>
);
PDF がレンダリングされます。