日本語

Saving React Screen Content as a PDF with jsPDF

​​React​html2canvas,jsPDF,PDF,Playwright,TypeScript

To save the tables and records shown on screen as a PDF, build the PDF with jsPDF and save it with doc.save(). If you want to keep the look of the screen as it is, turn the element into an image with html2canvas and place that image in the PDF. If you want the text in the PDF to be selectable and searchable, register a Japanese font with jsPDF and write the text directly.

I built a React component with a button for each of these two methods, and checked the saved PDFs with pdfinfo and pdftotext.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used jspdf 4.2.1, html2canvas 1.4.1, react / react-dom 19.3.1, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx files with tsc, converted them with esbuild, and ran them in a development build. I pressed the button with Playwright to receive the downloaded file, and examined it with pdfinfo and other tools from poppler-utils 24.02. The Japanese font was IPAGothic (ipag.ttf). I did not test Firefox, Safari, mobile browsers, production builds, or jsPDF's html() method.

Under a "Work Log" heading (the heading is in Japanese), there is an 8-row table with three columns (date, task, time) and a total row. Below the table are two buttons: a light blue one labeled "Make PDF as shown on screen" and a gray one labeled "Make text PDF" (the labels are in Japanese). At the bottom, a message says "Saved report.pdf (1 page)".
Right after pressing the "Make PDF as shown on screen" button (label in Japanese; display width 375px)

Installing jsPDF and html2canvas

bash
npm i jspdf html2canvas

According to the description of optional dependencies in the jsPDF README, html2canvas is an optional dependency used by jsPDF's html() method. When I installed only jspdf 4.2.1 in the test environment, html2canvas, canvg, dompurify, and core-js also ended up in node_modules, but only jspdf was listed in dependencies in package.json. Here I import html2canvas directly, so I installed it explicitly.

Turning the element into an image and placing it on A4 pages

Here is the function that creates a PDF that looks the same as the screen. It draws the element onto a canvas with html2canvas, cuts the canvas into slices as tall as one page, and places each slice on a jsPDF page.

ts
// pdf.ts
import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';

// A4 portrait (mm) and the margins on all four sides
const PAGE_W = 210;
const PAGE_H = 297;
const MARGIN = 10;

export type ImagePdfOptions = {
  scale?: number; // scale used when html2canvas draws
  format?: 'JPEG' | 'PNG'; // image format used in the PDF
  keepSelector?: string; // elements not to split at a page boundary
};

// Turn the element into an image and place it on A4 pages from top to bottom
export async function elementToPdf(
  el: HTMLElement,
  { scale = 2, format = 'JPEG', keepSelector }: ImagePdfOptions = {},
): Promise<jsPDF> {
  const canvas = await html2canvas(el, { scale, backgroundColor: '#ffffff', logging: false });
  const doc = new jsPDF({ unit: 'mm', format: 'a4' });

  const contentW = PAGE_W - MARGIN * 2;
  const pxPerMm = canvas.width / contentW;
  const pagePx = Math.floor((PAGE_H - MARGIN * 2) * pxPerMm);
  const cuts = pageCuts(el, canvas.height, pagePx, canvas.width / el.offsetWidth, keepSelector);

  let top = 0;
  cuts.forEach((bottom, i) => {
    // Cut out one page worth into a separate canvas
    const slice = document.createElement('canvas');
    slice.width = canvas.width;
    slice.height = bottom - top;
    slice
      .getContext('2d')!
      .drawImage(canvas, 0, top, canvas.width, slice.height, 0, 0, canvas.width, slice.height);
    if (i > 0) doc.addPage();
    doc.addImage(slice, format, MARGIN, MARGIN, contentW, slice.height / pxPerMm);
    top = bottom;
  });
  return doc;
}

As shown in the usage example in the jsPDF README, the default for new jsPDF() is A4 portrait with mm units. Here I write unit and format explicitly for clarity. When I checked the saved PDF with pdfinfo, the page size was 595.28 x 841.89 pts (A4).

The image width matches the content width after removing the left and right margins, which is 190mm. By computing how many canvas px correspond to 1mm (pxPerMm), I get the number of canvas px that fit one page's height (277mm). Each slice of that height is cut into a separate canvas and placed with addImage(). You can pass the canvas element directly to addImage().

According to the list of html2canvas configuration options, the default for scale is window.devicePixelRatio. So that the PDF quality does not change with the display's scale factor, I set scale explicitly. The default for logging is true, which prints debug logs to the console, so I set it to false.

html2canvas does not take a real screenshot. According to the README, it reads the DOM and styles and redraws them on a canvas, so the result may not match the actual appearance exactly. The same README also states that the library is still experimental and that its use in production is not recommended.

Not splitting rows at page boundaries

If a table is long, cutting it mechanically at the page height splits rows across pages. So I collected the bottom edges of the elements that must not be split (here, tr and h2), and cut at the lowest of those bottom edges that still fits on the page.

ts
// pdf.ts (continued)
// Decide the bottom edge of each page (in canvas px). Elements matching keepSelector are not cut in the middle
function pageCuts(
  el: HTMLElement,
  totalPx: number,
  pagePx: number,
  ratio: number,
  keepSelector?: string,
): number[] {
  const elTop = el.getBoundingClientRect().top;
  const bottoms = keepSelector
    ? [...el.querySelectorAll(keepSelector)].map((b) =>
        Math.round((b.getBoundingClientRect().bottom - elTop) * ratio),
      )
    : [];
  const cuts: number[] = [];
  let top = 0;
  while (totalPx - top > pagePx) {
    const limit = top + pagePx;
    const fits = bottoms.filter((b) => b > top && b <= limit);
    const cut = fits.length > 0 ? Math.max(...fits) : limit;
    cuts.push(cut);
    top = cut;
  }
  cuts.push(totalPx);
  return cuts;
}

I convert screen coordinates (CSS px) to canvas px by multiplying by ratio (canvas width ÷ element width). If none of the matching elements' bottom edges fall within the range that fits on the page, the cut is made at the page height.

I compared two ways of cutting a table that was 688px wide and 1,741px tall (60 rows). Both produced 2 pages. When I cut only by height, the image on page 1 was 2,006px tall. The upper part of the text in row 35 was left slightly at the bottom of page 1, and page 2 started at row 35 without the top border line. When I cut at the bottom edges of the rows, page 1 was 1,989px tall and ended below row 34, and page 2 started at row 35.

Top: "cut by height only." The upper part of the text in the next row remains slightly at the bottom of page 1, and page 2 starts at the row for November 5 (exporting images, item 35) without the top border line. Bottom: "cut at the bottom edge of the tr." Page 1 ends with the row for November 4 (proofreading, item 34), and page 2 starts at the row for November 5 (exporting images, item 35). The labels are in Japanese.
Bottom edge of page 1 and top edge of page 2 for the 60-row table (labels in Japanese)

The React component

The table is received through a ref, and when a button is pressed, the PDF is created and saved. The second button creates a PDF by writing text, which is explained in the next section.

tsx
// ReportPdf.tsx
import { useRef, useState } from 'react';
import { elementToPdf, textToPdf } from './pdf';

export type Row = { day: string; task: string; hours: number };

export function ReportPdf({ rows }: { rows: Row[] }) {
  const ref = useRef<HTMLDivElement>(null);
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState('');

  async function saveAsImage() {
    if (!ref.current) return;
    setBusy(true);
    try {
      const doc = await elementToPdf(ref.current, { keepSelector: 'tr, h2' });
      doc.save('report.pdf');
      setMessage(`report.pdf を保存しました(${doc.getNumberOfPages()}ページ)`);
    } catch (e) {
      setMessage(`失敗しました:${String(e)}`);
    } finally {
      setBusy(false);
    }
  }

  async function saveAsText() {
    setBusy(true);
    try {
      const lines = rows.map((r) => `${r.day} ${r.task} ${r.hours}時間`);
      const doc = await textToPdf('作業の記録', lines, '/fonts/ipag.ttf');
      doc.save('report-text.pdf');
      setMessage(`report-text.pdf を保存しました(${doc.getNumberOfPages()}ページ)`);
    } catch (e) {
      setMessage(`失敗しました:${String(e)}`);
    } finally {
      setBusy(false);
    }
  }

  const total = rows.reduce((sum, r) => sum + r.hours, 0);

  return (
    <div>
      <div ref={ref} className="report">
        <h2>作業の記録</h2>
        <table>
          <thead>
            <tr><th>日付</th><th>内容</th><th>時間</th></tr>
          </thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={i}><td>{r.day}</td><td>{r.task}</td><td>{r.hours}</td></tr>
            ))}
          </tbody>
          <tfoot>
            <tr><td colSpan={2}>合計</td><td>{total}</td></tr>
          </tfoot>
        </table>
      </div>
      <button disabled={busy} onClick={saveAsImage}>画面のとおり PDF にする</button>
      <button disabled={busy} onClick={saveAsText}>文字の PDF にする</button>
      <p role="status">{message}</p>
    </div>
  );
}

Only the inside of the div with the ref becomes the image, so the buttons and the status message do not appear in the PDF. When I pressed the "Make PDF as shown on screen" button on the 8-row table, the file was saved as report.pdf, and a message saying it was saved with 1 page appeared. The image in the PDF was 1376×674px, exactly twice the size of the table part including the heading (688×337px).

A PDF made from images looks the same as the screen, but it contains no text. When I extracted the text with pdftotext, the only output was one byte, the page-break character (\f). You cannot search or copy text in such a PDF.

Writing Japanese as text requires registering a font

Writing with doc.text() lets you select and search the text in the PDF. However, as explained in jsPDF's README section on UTF-8 characters, the 14 standard PDF fonts only support ASCII characters. To write Japanese, you need to register a TTF font that contains Japanese glyphs.

ts
// pdf.ts (continued)
// Read the TTF file and turn it into a string (binary string) that jsPDF accepts
let fontData: Promise<string> | null = null;
function loadFont(url: string): Promise<string> {
  fontData ??= fetch(url)
    .then((res) => {
      if (!res.ok) throw new Error(`フォントを読み込めません(${res.status})`);
      return res.arrayBuffer();
    })
    .then((buf) => {
      const bytes = new Uint8Array(buf);
      let s = '';
      for (let i = 0; i < bytes.length; i += 0x8000) {
        s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
      }
      return s;
    })
    .catch((e) => {
      fontData = null; // On failure, reset so the next call loads it again
      throw e;
    });
  return fontData;
}

// Write text as PDF text. Without fontUrl, the jsPDF standard font is used
export async function textToPdf(
  title: string,
  lines: string[],
  fontUrl?: string,
): Promise<jsPDF> {
  const doc = new jsPDF({ unit: 'mm', format: 'a4' });
  if (fontUrl) {
    doc.addFileToVFS('ipag.ttf', await loadFont(fontUrl));
    doc.addFont('ipag.ttf', 'IPAGothic', 'normal');
    doc.setFont('IPAGothic');
  }
  doc.setFontSize(16);
  doc.text(title, MARGIN, 20);
  doc.setFontSize(11);
  let y = 32;
  for (const line of lines) {
    if (y > PAGE_H - MARGIN) {
      doc.addPage();
      y = 20;
    }
    doc.text(line, MARGIN, y);
    y += 7;
  }
  return doc;
}

The README has an example that reads the contents of a TTF file as a "binary string," for example with fetch, and registers it with addFileToVFS() and addFont(). The code above follows that approach and converts the bytes received from fetch into a string one byte at a time. The font file is 6,235,344 bytes, so once it has been loaded, I keep it in fontData and avoid loading it again on later calls.

As described in the MDN documentation for fetch(), the Promise from fetch is not rejected when the server returns a 404. So the code checks res.ok, and if loading fails, it resets fontData to null. When I passed a nonexistent URL, an error saying the font could not be loaded (404) appeared. When I then passed the correct URL, the font loaded again and the PDF was created. Note that fontData is not kept separately for each URL. If you switch between multiple fonts, change it to store the data per URL.

When I wrote Japanese without registering a font, the PDF contained meaningless symbol sequences such as O\im0nГ2. pdffonts showed that the font in use was Helvetica, which was not embedded. After I registered IPAGothic and then wrote the text, the Japanese displayed correctly in the PDF, and pdftotext extracted the heading and the first line correctly. pdffonts showed that IPAGothic was embedded (emb was yes).

Top: a PDF written with the standard font via text(). The heading and each line show symbol sequences such as "O\im0nŠ“2" and "11g1eå0ŠN‹0n…". Bottom: a PDF written after registering IPAGothic. The heading "Work Log" and lines such as "Nov 1, drafting an article (item 1), 1 hour" are displayed correctly. The text in the image is in Japanese.
Top of a PDF without a registered font, and top of a PDF with the font registered (labels in Japanese)

text() only writes one line at each position you specify. It does not draw table borders, and you handle page breaks yourself. In the code above, when the writing position reaches the bottom margin, addPage() is called to move to the next page. The 60-row table came out as 2 pages. If you want the PDF to match the screen's look, use the image method. If you want the text to be searchable or copyable, use this method.

File sizes

These are the sizes of the PDFs made from the 8-row table (including the heading, 688px wide and 337px tall). The unit is bytes.

How it was made PDF size
Image (scale: 1, JPEG) 100,707
Image (scale: 2, JPEG) 262,365
Image (scale: 3, JPEG) 424,394
Image (scale: 1, PNG) 698,913
Image (scale: 2, PNG) 2,785,620
Text (no font) 4,232
Text (IPAGothic registered) 477,436

For images, the JPEG output was much smaller than the PNG output. At scale: 2, the PNG was a little over 10 times the size of the JPEG. The higher the scale, the larger the PDF. When I checked the images in the scale: 2 PDF with pdfimages, the resolution was 184ppi. When I made the 60-row table as images, the 2-page PDF was about 1.5MB.

For text, registering a font increased the size by about 470,000 bytes. The 60-row, 2-page version was 487,481 bytes, which is only about 10,000 bytes more than the 8-row version. Even as the number of rows grows, the increase in size is small.

​Posted by 86