2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React-pdf を使ってみた

Posted at

はじめに

この記事では。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>
);

image.png

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 がレンダリングされます。

image.png

PDF は iframe タグとして描画されます。

image.png

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?