<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[고등어의 팔딱팔딱]]></title><description><![CDATA[Notes from a frontend developer building React, Next.js and NestJS apps. Real bugs, open-source tools like react-html-pdf, and what I learned fixing them.]]></description><link>https://9bfish8.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 22:12:52 GMT</lastBuildDate><atom:link href="https://9bfish8.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[From Broken Korean PDFs to Blank Pages: Why I Built react-html-pdf]]></title><description><![CDATA[Long HTML-to-PDF exports in React can silently turn blank after ~40 pages. Here's why, how react-html-pdf fixes it, and how it compares to react-pdf.]]></description><link>https://9bfish8.hashnode.dev/from-broken-korean-pdfs-to-blank-pages-why-i-built-react-html-pdf</link><guid isPermaLink="true">https://9bfish8.hashnode.dev/from-broken-korean-pdfs-to-blank-pages-why-i-built-react-html-pdf</guid><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[pdf]]></category><category><![CDATA[open source]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Gayeon]]></dc:creator><pubDate>Wed, 02 Dec 2026 12:36:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0fadff40e35a7868b733b3/249715d3-0b42-4cf3-afb2-73bb0595798e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Two years ago I published a small library to npm and then more or less forgot about it. But every time I checked, the download count was quietly ticking up. Apparently it wasn't just me. Somewhere out there, other developers were staring at broken Korean PDFs and blank pages, sighing the same sigh I did.</p>
<p>So today, two years later, I finally rebuilt it from the ground up and gave it a new name. This post is about where that library came from, and what I fixed this time.</p>
<p>It started in the summer of 2024. I was building the frontend for <strong>Jiwoo</strong>, an AI startup assistant. Aspiring founders asked a chatbot questions, and it helped with everything from step-by-step startup guidance to market research, business model analysis and even taxes. The frontend team consisted of me, myself, and I.</p>
<p>Then a new requirement landed: add a <strong>"Save as PDF"</strong> button under every chatbot answer, so users could keep their questions and answers as a document.</p>
<p>Just one button, I thought. That was before I remembered every question and every answer was in Korean.</p>
<h2>How do people usually make Korean PDFs on the web?</h2>
<p>English PDFs come out fine with pretty much any approach. Korean is tricky for one reason: <strong>to put characters into a PDF as real text, the PDF needs to contain a font with those characters' shapes (glyphs).</strong> The fonts PDF libraries ship with (the standard 14 PDF fonts like Helvetica and Times) don't know a single Hangul character. And modern Korean has 11,172 precomposed syllables, so Korean font files are much, much bigger than Latin ones.</p>
<p>So every way of making Korean PDFs on the web comes down to one question: what do you do about that huge font? There are five common answers.</p>
<table>
<thead>
<tr>
<th>Approach</th>
<th>How it handles Korean fonts</th>
<th>Pros</th>
<th>Cons</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Browser print</strong> (<code>window.print()</code> + <code>@media print</code>)</td>
<td>The browser draws with the on-screen font</td>
<td>Real text, no library</td>
<td>The user has to pick "Save as PDF" in a print dialog, results vary by browser, you can't control the file from code</td>
</tr>
<tr>
<td><strong>jsPDF + font registration</strong></td>
<td>Convert a Korean TTF to base64, then <code>addFileToVFS</code> + <code>addFont</code></td>
<td>Real text, saves directly in the browser</td>
<td>Bundle a multi-megabyte font, one file per weight, and calculate line breaks, page breaks and coordinates yourself</td>
</tr>
<tr>
<td><strong>@react-pdf/renderer +</strong> <code>Font.register()</code></td>
<td>Register a font file URL and it gets embedded</td>
<td>Real text, built-in layout engine, also runs on the server</td>
<td>You rebuild the document with its own components</td>
</tr>
<tr>
<td><strong>html2canvas + jsPDF</strong> (html2pdf.js, react-to-pdf)</td>
<td>Takes a picture of what the browser drew</td>
<td>No font files, reuses your existing HTML</td>
<td>Text isn't selectable, larger files, long-document and page-break problems (more on these below)</td>
</tr>
<tr>
<td><strong>Headless Chrome on a server</strong> (Puppeteer, Playwright)</td>
<td>Install Korean fonts on the server, then <code>page.pdf()</code></td>
<td>Real text, full browser CSS, best quality</td>
<td>Needs a server that can run Chrome, plus Korean fonts installed there</td>
</tr>
</tbody></table>
<p>The one you see most on Korean dev blogs is number two: "stuff NanumGothic into jsPDF as base64." It's frontend-only, and it's the first search result. And yes, that's exactly where I started.</p>
<h2>The base64 font era</h2>
<p>jsPDF writes text directly into the PDF, and as we just saw, its built-in fonts can't read Korean. So I bundled a <strong>3.6 MB NanumMyeongjo TTF</strong>, and every time someone clicked the button, I fetched it, converted it to a base64 string, and handed it to jsPDF like, "Here. This is Korean."</p>
<pre><code class="language-js">const loadKoreanFont = async () =&gt; {
  const res = await fetch(koreanFontUrl);          // 3.6 MB TTF
  const buf = await res.arrayBuffer();
  return btoa(
    new Uint8Array(buf).reduce((s, b) =&gt; s + String.fromCharCode(b), '')
  );                                               // base64-encoded on every click
};

doc.addFileToVFS('NanumMyeongjo-Regular.ttf', koreanFont);
doc.addFont('NanumMyeongjo-Regular.ttf', 'NanumMyeongjo', 'normal');
</code></pre>
<p>Yes, on every click. Gluing 3.6 MB together one byte at a time. Looking back, that wasn't a button. It was a small piece of gym equipment.</p>
<p>The layout was hand-placed coordinates. Title at 10 mm from the top, "Question:" at 20 mm, the question at 30 mm, "Answer:" at 50 mm, the answer at 60 mm. A very optimistic design that assumed questions never run longer than two lines.</p>
<p>And it "worked." Note the quotation marks.</p>
<ul>
<li><strong>Long answers were cut off at the bottom of the first page.</strong> There was no code to start a new page. Whatever the AI wrote after that stayed a mystery forever.</li>
<li><strong>Long questions overlapped the answers.</strong> No matter how long the question was, the answer stubbornly started at 50 mm.</li>
<li><strong>Bold text and lists from the AI's markdown came out as plain text.</strong> On screen, answers were neatly split into headings, example lists and sources. In the PDF, you got the raw markdown string.</li>
</ul>
<p>And then, the grand finale. When I hooked up a tax-advice chatbot and split chat messages into their own component, the PDF started printing <code>undefined</code> where the answer should be. No error. No warning. Just the word <code>undefined</code>, sitting alone in a perfectly valid PDF. In a way, it was the most honest PDF I ever made.</p>
<p>The cause was almost embarrassingly simple. The download function took two arguments, <code>(question, answer)</code>, but the new component called <code>handleDownload(message.text)</code> with only one.</p>
<p>That's when it hit me. The nicely formatted HTML was already right there on the screen, and I was ignoring it to fight jsPDF over coordinates.</p>
<h2>Trying react-pdf</h2>
<p>Next up was <a href="https://www.npmjs.com/package/@react-pdf/renderer"><code>@react-pdf/renderer</code></a>, the first thing anyone mentions for PDFs in React. I tested it with Korean:</p>
<ul>
<li><strong>With the default font</strong>, Korean comes out as alien script like <code>\üm@ üüõTmtä</code>, and the line doesn't even wrap. It escapes off the right edge of the page.</li>
<li><strong>After registering a Korean font</strong> with <code>Font.register()</code>, it's genuinely great. Text wraps between words, it's selectable and searchable, and the file stays small (about 20 KB in my test).</li>
</ul>
<p>So react-pdf <em>can</em> do Korean. My real problem was different: react-pdf doesn't render your HTML. You rebuild the document with its own components (<code>&lt;Document&gt;</code>, <code>&lt;Page&gt;</code>, <code>&lt;View&gt;</code>, <code>&lt;Text&gt;</code>) and its own subset of CSS. I already had the screen I wanted to export, tables and styles included, and I wasn't about to build it twice just for a PDF. When you're a one-person frontend team, "twice" is a luxury. (I compare the two libraries properly, with code, later in this post.)</p>
<h2>The "screenshot" approach</h2>
<p>html2pdf.js and react-to-pdf take a completely different route. They render your existing HTML to a canvas with html2canvas, then place that image into a PDF with jsPDF. Since it's a picture of what the browser drew, Korean (or any language) just works, with no font files. You don't fight the font at all.</p>
<p>That was exactly what I wanted. So I wrapped it in a small React component and published it for Korean developers as <code>ko-pdf-down</code>.</p>
<p>And as soon as I started testing it properly, I discovered that this approach breaks in very quiet, very sneaky ways.</p>
<h2>First, the big picture</h2>
<p>Before we tour the crime scenes, here's how react-html-pdf turns HTML into a PDF. The core is a single function, <code>generatePdf()</code>, at a little over 400 lines.</p>
<ol>
<li><strong>Prepare fonts.</strong> Web fonts listed in the <code>fonts</code> option are loaded with <code>FontFace</code> and added to <code>document.fonts</code>. Each font is cached, so it's only downloaded once. (Dedicated to my past self who base64-encoded 3.6 MB on every click.)</li>
<li><strong>Build the document off-screen.</strong> Create a <code>&lt;div&gt;</code> and park it far off to the left (<code>left: -99999px</code>). Its width matches the PDF page. jsPDF uses <code>pt</code> units and 1 pt = 1 CSS px, so for A4 the div is 595 px wide.</li>
<li><strong>Insert the HTML.</strong> Default document styles, header, body, footer and watermark go into the div. If the body has no block tags, <code>\n</code> becomes <code>&lt;br&gt;</code> (<code>lineBreaks: 'auto'</code>).</li>
<li><strong>Wait for fonts.</strong> Await <code>document.fonts.ready</code>. Fonts declared in CSS (<code>@font-face</code>, Google Fonts) only download when they're actually used, so this has to happen <em>after</em> the div is attached.</li>
<li><strong>Capture in chunks.</strong> Draw the div to a canvas at 2× resolution with html2canvas-pro. Not all at once, though: in chunks that stay under the canvas limit.</li>
<li><strong>Cut into pages.</strong> Slice one page's worth from the chunk canvas, choosing the cut at an empty row between lines of text.</li>
<li><strong>Add to the PDF.</strong> Add each slice to jsPDF as a PNG (default) or JPEG with <code>addImage</code>, then move to the next page.</li>
<li><strong>Clean up.</strong> Save the file if <code>autoDownload</code> is on, and always return a <code>Blob</code>. The off-screen div is removed in <code>finally</code>. A good guest leaves no trace.</li>
</ol>
<p>Most of the problems below happen in steps 5 to 7.</p>
<h2>What I found</h2>
<h3>1. Long documents silently turn blank</h3>
<p>Browsers limit how big a single canvas can be. Chrome caps the height at about 65,000 pixels. At 2× resolution for sharp text, that's roughly <strong>40 A4 pages</strong>. Go past it, and you don't get an error. You get a canvas with nothing on it. Instead of yelling at you, the browser quietly hands you blank paper.</p>
<p>I tested the same long document with each library's default options:</p>
<img src="https://raw.githubusercontent.com/Go-deungeo-Lab/react-html-pdf/main/docs/comparison-long-docs.png" alt="html2pdf.js produces blank pages, react-to-pdf produces black pages, react-html-pdf renders every page" style="display:block;margin:0 auto" />

<ul>
<li><strong>html2pdf.js</strong> (60-page document): every page blank. Sixty beautifully clean sheets of A4.</li>
<li><strong>react-to-pdf</strong> (57-page document): every page solid black. This one took dark mode a little too seriously.</li>
<li>And, embarrassingly, my own library had the exact same bug. It went white as a sheet at 43 pages.</li>
</ul>
<p><strong>The fix:</strong> don't cram the whole document onto one canvas. Render it in chunks that each stay under the strictest limit, then stitch the pages together.</p>
<p>There are two limits to respect at the same time: the length of one side (about 65,535 px in Chrome) and the total area (16,777,216 px in iOS Safari). The library caps the height at 16,384 px and the area at 90% of Safari's limit. Satisfy the pickiest browser, and the rest follow.</p>
<pre><code class="language-ts">const RENDER_SCALE = 2;
const MAX_CANVAS_HEIGHT = 16384;
const MAX_CANVAS_AREA = 16777216 * 0.9;

// Height of one chunk (CSS px): as large as the limits allow, but at least one page
const chunkHeight = Math.max(
  Math.ceil(contentHeight) + 1,
  Math.floor(Math.min(MAX_CANVAS_HEIGHT, MAX_CANVAS_AREA / canvasWidthPx) / RENDER_SCALE)
);
</code></pre>
<p>For portrait A4, the canvas is 1,190 px wide, so the area limit kicks in first and each chunk ends up about 6,300 CSS px tall, roughly 7 to 8 pages. html2canvas's <code>y</code> and <code>height</code> options render just that slice of the document:</p>
<pre><code class="language-ts">const canvas = await html2canvas(element, {
  scale: RENDER_SCALE,
  backgroundColor,
  y: start,       // where this chunk starts
  height,         // how tall this chunk is
  useCORS: true,
});
if (!canvas.width || !canvas.height) {
  throw new Error('Failed to create canvas (the browser memory limit may have been exceeded)');
}
</code></pre>
<p>When the next page would run past the end of the current chunk, a new chunk is rendered <strong>starting exactly where that page starts</strong>. Because chunk boundaries line up with page boundaries, you never get a stitching seam in the middle of a page. And instead of quietly handing back a blank canvas, a failed canvas now throws an error. A scream beats silence.</p>
<p>I've tested it up to 160 pages, and every page renders.</p>
<p>Try it yourself. Both buttons get the same ~60-page HTML. On a 2× (Retina) screen, the html2pdf.js one comes out blank.</p>
<p><a class="embed-card" href="https://codepen.io/9bfish8/pen/EamrVBe?default-tab=result">https://codepen.io/9bfish8/pen/EamrVBe?default-tab=result</a></p>

<h3>2. Page breaks cut lines in half</h3>
<p>Most of these libraries chop the big image at fixed page heights. If a line of text sits on the boundary, its top half ends up on one page and its bottom half on the next. Readers get to enjoy each letter's upper and lower body separately.</p>
<p><strong>The fix:</strong> before cutting a page, scan upward from the bottom edge for a row of pixels that's all one color. That's the gap between two lines, so the page breaks there instead.</p>
<pre><code class="language-ts">const findBreakRow = (canvas, cut, lookBack) =&gt; {
  const top = Math.max(0, cut - lookBack);
  const data = ctx.getImageData(0, top, canvas.width, cut - top).data;
  const rowBytes = canvas.width * 4;

  for (let row = cut - top - 1; row &gt;= 0; row--) {   // bottom to top
    const offset = row * rowBytes;
    const [r, g, b] = [data[offset], data[offset + 1], data[offset + 2]];
    let blank = true;
    for (let x = 4; x &lt; rowBytes; x += 4) {          // is the whole row the same color as its first pixel?
      const o = offset + x;
      if (Math.abs(data[o] - r) &gt; 8 || Math.abs(data[o + 1] - g) &gt; 8 || Math.abs(data[o + 2] - b) &gt; 8) {
        blank = false;
        break;
      }
    }
    if (blank) return top + row + 1;                 // cut just below the empty row
  }
  return cut;                                        // none found: cut at the original position
};
</code></pre>
<p>It looks small, but a few details matter:</p>
<ul>
<li><strong>The background color isn't hard-coded.</strong> It doesn't look for "a white row," but for "a row that's all the same color as its first pixel." So it works with custom backgrounds, and with sections that have a full-width background.</li>
<li><strong>A color difference of up to 8 counts as the same color.</strong> Anti-aliasing and JPEG noise can make pixels differ ever so slightly, and the row still counts as empty. Perfectionism doesn't get to win this one.</li>
<li><strong>It only looks back up to 20% of a page.</strong> In areas with no empty rows, like a big table or an image, it falls back to the original position instead of making the page absurdly short.</li>
<li><strong>If the canvas can't be read, it cuts at the original position.</strong> A cross-origin image without CORS makes <code>getImageData</code> throw, and that shouldn't take down the whole PDF.</li>
</ul>
<p>The next page starts exactly where this one was cut, so nothing is skipped or duplicated.</p>
<h3>3. Korean words break in the middle</h3>
<p>By default, browsers allow a line break between any two Korean syllables, so a word like 국민으로부터 can end up split as 국 / 민으로부터. To a Korean reader, that's like seeing "gover / nment" in English. You notice.</p>
<p><strong>The fix:</strong> the render div gets <code>word-break: keep-all</code> by default, so Korean (and other CJK text) wraps at spaces, the way it's actually written. On its own, <code>keep-all</code> can let a long URL with no spaces run off the page, so <code>overflow-wrap: break-word</code> comes along too.</p>
<pre><code class="language-ts">element.style.wordBreak = 'keep-all';
element.style.overflowWrap = 'break-word';
</code></pre>
<img src="https://raw.githubusercontent.com/Go-deungeo-Lab/react-html-pdf/main/docs/comparison-ko.png" alt="Default line breaking splits Korean words mid-word; keep-all wraps at spaces" style="display:block;margin:0 auto" />

<p>The default font stack is <code>'Noto Sans KR', 'Apple SD Gothic Neo', 'Malgun Gothic', 'Nanum Gothic', sans-serif</code>, so even without specifying a font, Korean is drawn with whatever Korean font the OS has. No more carrying 3.6 MB around.</p>
<p>Below, you can compare the same Korean document with html2pdf.js. Its output breaks words mid-word, like 인 / 권 and 읽힙니 / 다.</p>
<p><a class="embed-card" href="https://codepen.io/9bfish8/pen/ByRMoXz?default-tab=result">https://codepen.io/9bfish8/pen/ByRMoXz?default-tab=result</a></p>

<h3>4. Tailwind v4 colors crash html2canvas</h3>
<p>Tailwind v4 uses <code>oklch()</code> colors everywhere. The original html2canvas, which hasn't had a release since 2022, meets these colors for the first time and throws <code>Attempting to parse an unsupported color function "oklch"</code>. A library frozen in time, meeting colors from the future. Both html2pdf.js (<a href="https://github.com/eKoopmans/html2pdf.js/issues/729">#729</a>) and react-to-pdf (<a href="https://github.com/ivmarcos/react-to-pdf/issues/149">#149</a>) have open issues for this.</p>
<p><strong>The fix:</strong> switch to <a href="https://www.npmjs.com/package/html2canvas-pro">html2canvas-pro</a>, a maintained fork that understands modern color functions.</p>
<h3>5. Web fonts come out with broken spacing</h3>
<p>This one took a while to figure out. html2canvas lays out your page inside a hidden <strong>cloned iframe</strong>. Fonts you load with JavaScript (<code>new FontFace(...)</code>) are registered only on the original document, not the clone. So positions get measured with a fallback font while glyphs are drawn with the real one. It's like measuring with one ruler and cutting with another, so of course the spacing is all over the place.</p>
<p><strong>The fix:</strong> in html2canvas's <code>onclone</code> hook, create the same fonts again using the cloned document's own <code>window.FontFace</code>, and register them there. If <code>onclone</code> returns a Promise, html2canvas waits for it before laying anything out.</p>
<pre><code class="language-ts">const addFontToDocument = async (doc: Document, font: PdfFont) =&gt; {
  const FontFaceCtor = doc.defaultView?.FontFace;   // FontFace from the cloned iframe
  const face = await new FontFaceCtor(font.family, `url("${font.src}")`, {
    weight: String(font.weight ?? 'normal'),
    style: font.style ?? 'normal',
  }).load();
  doc.fonts.add(face);
};

await html2canvas(element, {
  // ...
  onclone: async (clonedDoc) =&gt; {
    await Promise.all(fonts.map((font) =&gt; addFontToDocument(clonedDoc, font)));
  },
});
</code></pre>
<p>On the main document, fonts are cached by <code>family | weight | style | unicodeRange | src</code>, so clicking the button again doesn't download them again. If a load fails, it's removed from the cache and retried on the next click. <code>unicodeRange</code> is supported too, so fonts split into Korean and Latin subsets work.</p>
<p>On your side, you just list your fonts once:</p>
<pre><code class="language-tsx">&lt;PdfDownloadButton
  content={html}
  style={{
    fonts: [
      { family: 'Merriweather', src: '/fonts/Merriweather-Regular.woff2' },
      { family: 'Bebas Neue', src: '/fonts/BebasNeue-Regular.woff2' }
    ],
    fontFamily: "'Merriweather', serif"
  }}
/&gt;
</code></pre>
<h3>6. CSS resets flatten your headings</h3>
<p>If your app uses Tailwind's preflight (or any CSS reset), <code>&lt;h1&gt;</code> is the same size as body text, lists lose their bullets, and tables lose their borders. That CSS applies to the PDF too. Your proud headline quietly blends into the paragraph below it.</p>
<p><strong>The fix:</strong> add a small set of default document styles that apply only inside the PDF render area, at the lowest possible priority. Your own classes and inline styles still win, but headings, lists and tables look like a document again.</p>
<p>The trick is CSS specificity. Each render gets a unique class (<code>rhp-doc-…</code>), wrapped in <code>:where()</code>. Selectors inside <code>:where()</code> count as zero specificity, so each rule below ends up at <code>(0,0,1)</code>, the same as a single tag selector.</p>
<pre><code class="language-css">:where(.rhp-doc-abc123) h1 { font-size: 2em; font-weight: 700; margin: .67em 0 }
:where(.rhp-doc-abc123) ul { list-style: disc outside }
:where(.rhp-doc-abc123) table { border-collapse: collapse; margin: 1em 0 }
</code></pre>
<ul>
<li>Tailwind preflight's <code>h1 { font-size: inherit }</code> is also <code>(0,0,1)</code>. With equal specificity the later rule wins, and this <code>&lt;style&gt;</code> sits inside the render div at the very end of the document, so it beats the reset.</li>
<li>A class like <code>class="text-sm"</code> is <code>(0,1,0)</code>, so it always beats these defaults. Inline styles, even more so.</li>
<li>The unique class scopes everything, so while the PDF is being made, the <code>h1</code>s on your actual page act like nothing happened.</li>
</ul>
<p>You can turn it off with <code>defaultStyles: false</code>.</p>
<h2>So I renamed it</h2>
<p>Looking at that list, I realized none of these problems are specific to Korean. Blank pages don't discriminate. So <code>ko-pdf-down</code> became <a href="https://www.npmjs.com/package/react-html-pdf"><strong>react-html-pdf</strong></a>, with Korean/CJK support kept as one of its defaults rather than its whole identity.</p>
<pre><code class="language-bash">npm install react-html-pdf
</code></pre>
<pre><code class="language-tsx">import { PdfDownloadButton } from 'react-html-pdf';

&lt;PdfDownloadButton
  fileName="report.pdf"
  content="&lt;h1&gt;Quarterly report&lt;/h1&gt;&lt;p&gt;Hello, PDF!&lt;/p&gt;"
/&gt;
</code></pre>
<p>Or call it directly. Pass <code>autoDownload: false</code> to get a <code>Blob</code> for previews or uploads:</p>
<pre><code class="language-ts">import { generatePdf } from 'react-html-pdf';

const blob = await generatePdf({ content, fileName: 'report.pdf', autoDownload: false });
</code></pre>
<p>These are the options you'll reach for most:</p>
<table>
<thead>
<tr>
<th>Option</th>
<th>Default</th>
<th>What it does</th>
</tr>
</thead>
<tbody><tr>
<td><code>pageSize</code> / <code>orientation</code></td>
<td><code>'a4'</code> / <code>'portrait'</code></td>
<td>Also supports <code>a3</code>, <code>letter</code>, <code>legal</code>, and landscape</td>
</tr>
<tr>
<td><code>margin</code></td>
<td><code>20</code></td>
<td>Top and bottom margin (pt)</td>
</tr>
<tr>
<td><code>imageFormat</code></td>
<td><code>'png'</code></td>
<td>PNG is sharper for text-heavy documents; <code>'jpeg'</code> is smaller for photo-heavy ones (<code>imageQuality</code> defaults to 0.92)</td>
</tr>
<tr>
<td><code>lineBreaks</code></td>
<td><code>'auto'</code></td>
<td>Turns <code>\n</code> into <code>&lt;br&gt;</code> when there are no block tags. <code>'preserve'</code> always does, <code>'html'</code> never does</td>
</tr>
<tr>
<td><code>columns</code></td>
<td><code>1</code></td>
<td><code>2</code> for a two-column layout</td>
</tr>
<tr>
<td><code>headerText</code> / <code>footerText</code> / <code>watermark</code></td>
<td>none</td>
<td>Rendered as plain text (HTML-escaped)</td>
</tr>
<tr>
<td><code>defaultStyles</code></td>
<td><code>true</code></td>
<td>The default document styles described above</td>
</tr>
</tbody></table>
<p>One thing to keep in mind: <code>content</code> is rendered as HTML, so if you're passing in user input, escape it first. The header, footer and watermark are escaped for you.</p>
<p>The button component comes with <code>onDownloadStart</code>, <code>onDownloadComplete</code> and <code>onError</code> callbacks plus a loading spinner, and <code>generatePdf</code> throws when something fails. Instead of quietly handing you <code>undefined</code> or a stack of blank paper like in my Jiwoo days, it tells you clearly that it failed. Honestly, that's the sentence I most wanted to hear back in 2024.</p>
<h2>How is this different from react-pdf?</h2>
<p>The names are close enough to be confusing, but the two libraries make PDFs in fundamentally different ways.</p>
<p><strong>@react-pdf/renderer typesets the PDF itself.</strong> No browser involved. It takes a tree of its own components, calculates positions with its own (Flexbox-based) layout engine, embeds the fonts you registered, and writes characters as real text. That's why it also runs on a Node.js server with no browser at all.</p>
<p><strong>react-html-pdf copies what the browser drew.</strong> The browser does the layout, and the library captures the result on a canvas and splits it into pages. Anything the browser can draw comes out, but it does need a browser (a DOM).</p>
<p>Think of react-pdf as a print shop setting the type from scratch, and react-html-pdf as a really good photocopier for a page that's already finished. Building the same document both ways makes the difference obvious:</p>
<pre><code class="language-tsx">// @react-pdf/renderer: rebuild the document with its own components
import { Document, Page, Text, View, Font, StyleSheet } from '@react-pdf/renderer';

Font.register({ family: 'NanumGothic', src: '/fonts/NanumGothic-Regular.ttf' });
const styles = StyleSheet.create({
  page: { padding: 40, fontFamily: 'NanumGothic' },
  title: { fontSize: 24, marginBottom: 12 },
});

const Report = () =&gt; (
  &lt;Document&gt;
    &lt;Page size="A4" style={styles.page}&gt;
      &lt;Text style={styles.title}&gt;분기 보고서&lt;/Text&gt;{/* "Quarterly report" */}
      &lt;View&gt;&lt;Text&gt;매출이 지난 분기보다 늘었습니다.&lt;/Text&gt;&lt;/View&gt;{/* "Revenue grew from last quarter." */}
    &lt;/Page&gt;
  &lt;/Document&gt;
);
</code></pre>
<pre><code class="language-tsx">// react-html-pdf: pass the HTML you already have
import { PdfDownloadButton } from 'react-html-pdf';

&lt;PdfDownloadButton
  fileName="report.pdf"
  content="&lt;h1&gt;분기 보고서&lt;/h1&gt;&lt;p&gt;매출이 지난 분기보다 늘었습니다.&lt;/p&gt;"
/&gt;
</code></pre>
<table>
<thead>
<tr>
<th></th>
<th>@react-pdf/renderer</th>
<th>react-html-pdf</th>
</tr>
</thead>
<tbody><tr>
<td>How it works</td>
<td>Typesets the PDF with its own layout engine</td>
<td>Captures the browser's rendering on a canvas and splits it into pages</td>
</tr>
<tr>
<td>Best for</td>
<td>Designing a PDF from scratch (invoices, contracts)</td>
<td>Exporting HTML or a screen you already have</td>
</tr>
<tr>
<td>Input</td>
<td>Its own components (<code>&lt;Page&gt;</code>, <code>&lt;View&gt;</code>, <code>&lt;Text&gt;</code>)</td>
<td>Any HTML string</td>
</tr>
<tr>
<td>CSS</td>
<td>Only the styles it supports</td>
<td>Whatever the browser renders (Tailwind included)</td>
</tr>
<tr>
<td>Korean / CJK</td>
<td>Works after registering a font file per weight</td>
<td>Works out of the box (uses system Korean fonts)</td>
</tr>
<tr>
<td>Text in the PDF</td>
<td>Real text: selectable, searchable, copyable</td>
<td>An image: not selectable or searchable</td>
</tr>
<tr>
<td>File size</td>
<td>Small (about 20 KB in my test)</td>
<td>Larger (an image per page)</td>
</tr>
<tr>
<td>Runs on</td>
<td>Browser and Node.js server</td>
<td>Browser only</td>
</tr>
<tr>
<td>Page breaks</td>
<td>Calculated per element by the engine</td>
<td>Cut at empty rows between lines</td>
</tr>
</tbody></table>
<p>The "quarterly report" code above is wired up to buttons below. Download both PDFs and try selecting the text. You'll feel the difference at your fingertips.</p>
<p><a class="embed-card" href="https://codepen.io/9bfish8/pen/XJROmvY?default-tab=result">https://codepen.io/9bfish8/pen/XJROmvY?default-tab=result</a></p>

<p>To be fair, the image-based approach has real trade-offs. Text in the PDF can't be selected, files are bigger, and accessibility tools like screen readers can't read the content. If you're designing a document from scratch, or generating lots of them on a server, react-pdf is a great choice. If you need "what's on the screen, as a PDF," that's exactly what react-html-pdf is for.</p>
<h2>Try it</h2>
<ul>
<li><strong>Live playground</strong> (no install): <a href="https://go-deungeo-lab.github.io/react-html-pdf/iframe.html?id=playground-pdf-test--playground&amp;viewMode=story">react-html-pdf demo</a>. Do try the "Very long (~50 pages)" preset. I never knew <em>not</em> getting 60 blank pages could feel this satisfying.</li>
<li><strong>GitHub:</strong> <a href="https://github.com/Go-deungeo-Lab/react-html-pdf">Go-deungeo-Lab/react-html-pdf</a></li>
<li><strong>npm:</strong> <a href="https://www.npmjs.com/package/react-html-pdf">react-html-pdf</a></li>
</ul>
<p>Have you ever shipped a PDF export that worked perfectly in testing and came back blank in production? I'd love to hear how you dealt with it. Fellow survivors, please come forward.</p>
<p>If you made it through this whole long post, thank you. I'll keep writing posts like this, even if not on a regular schedule. If you'd like to chat, feel free to reach out anytime.</p>
]]></content:encoded></item></channel></rss>