logo

React (JSX/TSX)

This guide explains how to generate an HTML string using React's JSX/TSX and convert it to PDF by sending it to pdfg's API.

Technical Overview

  1. Create React components using JSX/TSX
  2. Use ReactDOMServer.renderToString() to convert to HTML string
  3. Send the generated HTML string to pdfg's API to convert it to PDF

Sample

Defining the Component

// Invoice.tsx
import React from "react";

interface Props {
  items: { name: string; price: number }[];
  total: number;
}

export const Invoice: React.FC<Props> = ({ items, total }) => (
  <html>
    <head></head>
    <body>
      <div className="invoice">
        <h1>Invoice</h1>
        <table>
          <thead>
            <tr>
              <th>Item</th>
              <th>Amount</th>
            </tr>
          </thead>
          <tbody>
            {items.map((item, i) => (
              <tr key={i}>
                <td>{item.name}</td>
                <td>{item.price} USD</td>
              </tr>
            ))}
          </tbody>
        </table>
        <p className="total">Total: {total} USD</p>
      </div>
    </body>
  </html>
);

Using the Component and Generating PDF

// generatePdf.ts
import ReactDOMServer from "react-dom/server";
import { Invoice } from "./Invoice";
import fs from "fs";

// Prepare data
const items = [
  { name: "商品A", price: 1000 },
  { name: "商品B", price: 2000 },
];

// Convert JSX to HTML string
const html = ReactDOMServer.renderToString(
  <Invoice items={items} total={3000} />
);

// Request to pdfg's API
const response = await fetch("https://api.pdfg.net/v1", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer YOUR_API_KEY",
  },
  body: JSON.stringify({
    html: html,
    pdfOptions: {
      format: "A4",
    },
  }),
});

// Save PDF
if (response.ok) {
  const pdfBuffer = await response.arrayBuffer();
  fs.writeFileSync("invoice.pdf", Buffer.from(pdfBuffer));
}