<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kittisak Ma on Medium]]></title>
        <description><![CDATA[Stories by Kittisak Ma on Medium]]></description>
        <link>https://medium.com/@9haroon_dev?source=rss-b001e6e0fc89------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EOv1A9w_MfovotlxPlJsAg.jpeg</url>
            <title>Stories by Kittisak Ma on Medium</title>
            <link>https://medium.com/@9haroon_dev?source=rss-b001e6e0fc89------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 01:19:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@9haroon_dev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How We Know Which Bank Your Statement Comes From]]></title>
            <link>https://medium.com/@9haroon_dev/how-we-know-which-bank-your-statement-comes-from-9b32fbeab59e?source=rss-b001e6e0fc89------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b32fbeab59e</guid>
            <category><![CDATA[transform-statement]]></category>
            <category><![CDATA[pdf-converter]]></category>
            <category><![CDATA[bank-statement]]></category>
            <category><![CDATA[convert-statement]]></category>
            <category><![CDATA[us-bank-statement]]></category>
            <dc:creator><![CDATA[Kittisak Ma]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 13:21:01 GMT</pubDate>
            <atom:updated>2026-09-23T13:21:01.318Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>And why the list that decides it is written by hand</strong></p><p>Every bank prints its statement differently. Wells Fargo puts money in and money out in two separate columns. Citizens Bank prints one column with a minus sign. Barclays prints the money-out column first. So before Docubrew can pull a single transaction out of a PDF, it has to answer one question: which bank printed this?</p><p>Two of those layouts, side by side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nTdyX8V_AaH_TV6ogPbEhg.png" /><figcaption>Wells Fargo prints Deposits and Withdrawals as two columns; Citizens Bank prints one Amount column with a minus sign.</figcaption></figure><p>Wells Fargo tells you the direction by which column a number sits in. Citizens tells you with a minus sign in a single column. Nothing else on either page says which is which.</p><p>Our parser is rule-based, so the wrong bank means the wrong column: deposits come back as withdrawals, in a CSV that looks perfectly normal.</p><p>So this post is about the routing step: how Docubrew picks a parser, what keeps two look-alike banks apart, and what happens when none of the 34 match. You may be wondering is why any of this is hand-written when a model would read the statement without it.</p><h3>The whole decision is one loop</h3><p>There are 34 bank parsers in convert_pdf_core today, plus a catch-all. They sit in a Python list, in a fixed order, and this loop in router.py walks it:</p><pre>for parser in PARSER_REGISTRY:<br>  if any(parser.detect(text) for text in page_texts):<br>    logger.info(f&quot;Parser matched: {parser.name}&quot;)<br>    return parser.parse(pdf_bytes)</pre><p>page_texts holds the text of the first three pages (_MAX_DETECT_PAGES = 3). We look past page one because plenty of statements open with a cover page or a marketing insert, and the bank&#39;s name only shows up after it.</p><p>That is the entire method. Go down the list, ask each parser “is this yours?”, and the first one that says yes gets the file. No scoring, no ranking, no tie-break. Thirty-five checks against three pages of text is too fast to measure. If that list ever reaches 300, it will be slow enough to care about, and I will deal with it then.</p><p>The list itself is exactly what it sounds like:</p><pre>PARSER_REGISTRY: list[BankParser] = [<br>  WellsFargoCheckingParser(),<br>  # …<br>  TD2025ConvenienceCheckingParser(),<br>  TD2024ConvenienceCheckingParser(),<br>  # …<br>  # First Citizens Bank - before the Citizens Bank parsers: &quot;First Citizens<br>  # Bank&quot; contains &quot;Citizens Bank&quot; as a substring.<br>  FirstCitizensParser(),<br>  CitizensBankParser(),<br>  # …<br>  GenericFallbackParser(),<br>]</pre><p>Adding a bank means editing that list and opening a pull request. Someone reads it. That is the point.</p><h3>Two banks, one name</h3><p>A parser says “this is mine” by looking for words on the page. Bank statements are printed documents with stable branding, so the words are reliable, and a list of words is something a person can check. A trained model is not.</p><p>The catch is that the words overlap. Here is the Citizens Bank check, cut down to the part that matters:</p><pre>_POSITIVE_MARKERS = [&quot;CITIZENS BANK&quot;, &quot;CIRCLE&quot;, &quot;MEMBER FDIC&quot;, &quot;CIRCLE CHECKING&quot;]<br>_EXCLUDE_MARKERS  = [&quot;FSP46669&quot;, &quot;NCRCP13&quot;, &quot;GLOBAL ONE&quot;,<br>                     &quot;MONEY IN (R)&quot;, &quot;NAVY FEDERAL&quot;, &quot;COMERICA&quot;]<br><br>def detect(self, first_page_text: str) -&gt; bool:<br>    text = first_page_text.upper()<br>    if any(ex in text for ex in _EXCLUDE_MARKERS):<br>        return False<br>    if &quot;CITIZENS BANK&quot; not in text:<br>        return False<br>    hits = sum(1 for m in _POSITIVE_MARKERS if m in text)<br>    return hits &gt;= 2</pre><p>Now look at what a First Citizens Bank statement puts on page one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X0nMWc_D9MY0d1TK.png" /><figcaption>Two statement headers. Both say Citizens Bank.</figcaption></figure><p>“First Citizens Bank” contains “Citizens Bank”. The check above has no idea those are two different banks. On the First Citizens statements in my test files, it survives on a technicality. They hit only one word from the list, and the rule needs two. Any First Citizens statement that also printed “Member FDIC”, which most US statements do somewhere, would hit two and get claimed by the wrong parser.</p><p>And these two banks lay out their tables nothing alike.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*93IJsOKLXj_9SvPx.png" /><figcaption>First Citizens uses two amount columns; Citizens uses one signed column.</figcaption></figure><p>First Citizens splits money into Deposits/Additions and Withdrawals/Subtractions. Citizens prints a single Amount column where the minus sign carries the direction. A parser built for one, pointed at the other, does not crash. It reads the columns it expects to find, in the positions it expects them, and writes out numbers.</p><p>One line of ordering was all that stood between me and that. FirstCitizensParser() sits above CitizensBankParser(), so it gets asked first, and it says yes.</p><p>That is a guarantee about position, not about meaning, and writing this post is what pushed me to fix it properly. The obvious patch is to add “FIRST CITIZENS” to the exclude list, and it is wrong: a real Citizens statement with a line like TRANSFER TO FIRST CITIZENS BANK would then reject its own parser. The fix that holds is to ask the other detector, which needs the anchor &quot;FIRST CITIZENS&quot; plus two of nine supporting phrases and so cannot be fooled by a payee name:</p><pre>if detect_first_citizens(first_page_text):<br>    return False</pre><p>The order still stands. It is just no longer the only thing standing.</p><p>The same pattern shows up all over the list. The 2025 TD layout is checked before the 2024 one, because the newer check is stricter and the older one is loose. Bank of America credit cards are checked before Bank of America checking, because a credit card statement is also a Bank of America statement, and only one of those parsers knows what a minimum payment is.</p><h3>The time I let code choose the order</h3><p>I wrote register_parser() so a parser could be added without editing the file. My first version took a before argument, and when it could not find the parser you named, it quietly stuck yours on the end of the list instead.</p><p>The last entry in the list is the catch-all, and the catch-all says yes to every PDF. So “on the end” means “never”.</p><p>Nothing failed. No error, no warning. The new parser was correct, its own tests passed, and it never ran once on a real file. The fix was to stop being quiet:</p><pre>target_idx = next(<br>    (i for i, p in enumerate(PARSER_REGISTRY) if isinstance(p, before)),<br>    None,<br>)<br>if target_idx is None:<br>    raise ValueError(<br>        f&quot;register_parser: &#39;{before.__name__}&#39; not found in &quot;<br>        f&quot;PARSER_REGISTRY; cannot insert before unknown parser&quot;<br>    )<br>PARSER_REGISTRY.insert(target_idx, parser)</pre><p>That bug is the entire argument against letting the software build the list for itself, and I am the one who wrote it. Plugin systems that scan for installed parsers hand you an order that depends on what got installed, in what sequence, on which machine. When the order <em>is</em> the rule, an order nobody chose is an answer nobody can predict. A list in a file shows up in a diff, and a reviewer can see that your new parser landed under the catch-all.</p><h3>When we do not know the bank</h3><p>GenericFallbackParser is last parser in the order. If your bank is not one of the 34, it looks for ruled tables first, and if there are none, it scans the page for date-shaped text with amount-shaped text nearby. In most cases, this works well. But since it does not know your bank&#39;s layout, it can sometimes get things wrong. To show you what that looks like, we took a Wells Fargo statement and ran it through the fallback parser and its own parser.</p><p>Here is the table we are about to hand it, five rows off page 2 of a Wells Fargo statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z2YgxzEUEvV0L2oF.png" /><figcaption>Wells Fargo transaction table: Deposits/Additions and Withdrawals/Subtractions are separate columns, and not one amount carries a sign.</figcaption></figure><p>Read by the Wells Fargo parser:</p><pre>Date,Check Number,Description,Deposits,Withdrawals,Balance<br>09/09/2025,,&quot;WT Fed#05809 Td Bank, NA &lt;redacted&gt;&quot;,8200.00,,<br>09/09/2025,,Online Transfer From &lt;redacted&gt; Way2Save Checking,500.00,,<br>09/09/2025,,Wire Trans Svc Charge - Sequence: &lt;redacted&gt;,,15.00,8694.01<br>09/11/2025,,Withdrawal Made In A Branch/Store,,8000.00,<br>09/11/2025,,Zelle to &lt;redacted&gt; on 09/11 Ref #&lt;redacted&gt;,,80.00,614.01</pre><p>And the same five rows of the same PDF, read by the catch-all:</p><pre>Date,Description,Deposits,Withdrawals,Balance<br>9/9,&quot;WT Fed#05809 Td Bank, NA &lt;redacted&gt;&quot;,8200.00,,<br>9/9,Online Transfer From &lt;redacted&gt; Way2Save Checking,500.00,,<br>9/9,Wire Trans Svc Charge - Sequence: &lt;redacted&gt;,15.00,,8694.01<br>9/11,Withdrawal Made In A Branch/Store,8000.00,,<br>9/11,Zelle to &lt;redacted&gt; on Ref #&lt;redacted&gt;,80.00,,614.01</pre><p>It found the right rows, but only the two deposits were classified correctly. All three withdrawals were treated as deposits.</p><p>The reason is simple: this statement uses columns, not minus signs, to tell deposits from withdrawals. The fallback parser does not understand those column headers. It only sees the amount, so a negative number becomes a Withdrawal, while everything else becomes a Deposit. Even a row with “Withdrawal” in its description can therefore be classified as a deposit.</p><p>Just to let you know, behind every parsed row, we also keep a confidence score based on how much evidence supports the result. For statements we do not recognize, the fallback parser intentionally keeps this confidence lower. This does not mean the result is wrong, we are simply being cautious. The score stays internal to avoid confusing users and it also helps us see which bank need their own parser next.</p><p>Currently, we are exploring a more practical solution: letting you mark the transaction area, columns, and headers directly in the PDF viewer. This could turn an unrecognized statement into a format you define clearly.</p><p>Until then, if a statement does not convert correctly, use the Report feature in the app and we will convert it for you for free.</p><h3>Why not point a model at it</h3><p>The obvious question is why I wrote 34 hand-written parsers at all, when an AI model would read any statement without a single one of them. Two reasons: I need the same PDF to produce the same CSV every time, down to the byte, and I need a missing amount to stay blank rather than be guessed at. A model gives me neither, and we mentioned about this topic in <a href="https://www.docubrew.com/blog/chatgpt-vs-bank-statement-converter?utm_medium=blog&amp;utm_source=medium.com&amp;utm_content=how-we-know-which-bank-">ChatGPT vs a bank statement converter</a>.</p><p>That is not a permanent no. I’m currently exploring different methods at recognizing a bank nobody has written a specific parser for with privacy in mind. I’ll share more details once it’s more clear. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b32fbeab59e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PDFium vs PDF.js: Choosing a React PDF Engine (2026)]]></title>
            <link>https://medium.com/@9haroon_dev/pdfium-vs-pdf-js-choosing-a-react-pdf-engine-2026-2c05c0ed55e7?source=rss-b001e6e0fc89------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c05c0ed55e7</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[pdf-viewer]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Kittisak Ma]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 14:05:49 GMT</pubDate>
            <atom:updated>2026-08-18T14:20:20.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*auPn4fVXRucMmsuUbRo2gQ.jpeg" /></figure><p>A few months ago, I opened an architecture layout in a PDF.js-based viewer. It loaded fine. Then I zoomed in, and the re-render lagged. Zoom out, lag again. The page held thousands of vector strokes, and every zoom step seemed to redraw all of them. That’s the kind of thing that starts a PDFium vs PDF.js argument in your own head.</p><p>Chrome’s built-in viewer renders with PDFium, so I opened the same file there to check whether the engine was the difference. It re-rendered smoothly. Later, while researching what PDFium can actually do in a browser, I came across EmbedPDF, which runs PDFium through WebAssembly, and tried the file in that too. Also smooth. That’s when I started taking the engine question seriously. And as I dug in, I found the lag traced to viewer zoom strategy more than to the engine itself (more on that below).</p><blockquote><em>Quick disclosure: I work on React PDF Kit, which runs on PDF.js. So I have a side, and that’s exactly why I tested PDFium fairly before writing this. If anything, I’ve overcorrected in its favor.</em></blockquote><p>Most content on this topic is either marketing from companies selling a PDFium-based SDK, or a <a href="https://groups.google.com/g/emscripten-discuss/c/nO0MvRpeJLg/m/wakkMPqNX_oJ">2014 benchmark</a> of an early PDFium-to-JS port that beat PDF.js with the text layer switched off. There’s no current take from a React developer’s point of view. The belief that PDFium just renders better leans on <a href="https://dropbox.tech/infrastructure/improving-document-preview-performance">Dropbox’s 2017 migration writeup</a> and vendor blog posts, with no neutral in-browser benchmark behind it.</p><p>So this isn’t a horse race, it’s an architecture decision. PDFium’s strongest arguments come first here, so don’t read the running order as a verdict. The one edge people reliably hand PDFium is color. It turns out PDF.js can match it, through color management that ships but sits off by default behind a setting almost nobody flips on. So PDFium’s real advantage is narrower than its reputation: it gets color right with nothing to configure. PDF.js’s clean wins are the text layer and bundle size. I’ll show you what’s verifiable and flag what you should prototype yourself.</p><h3>What PDFium and PDF.js actually are</h3><p>You probably know PDF.js already. It’s Mozilla’s JavaScript PDF renderer, and it parses and rasterizes PDFs in pure JavaScript onto an HTML5 canvas. Nearly every React PDF library sits on top of it: wojtekmaj/react-pdf, @anaralabs/lector, @mikecousins/react-pdf, the archived react-pdf-viewer (phuocng), and the one I work on, React PDF Kit. As of late July 2026, pdfjs-dist is at 6.1.200 (published June 27, 2026), with around 15M weekly npm downloads and 53K GitHub stars. It’s the default substrate for React PDF work.</p><p>PDFium needs more of an intro, because most React devs have used it without knowing. It’s Google’s C++ PDF engine, originally Foxit’s commercial SDK before Google open-sourced it, and it’s the engine inside Chrome, Edge, and Android’s PDF viewer. Every time you open a PDF in Chrome, that’s PDFium doing the work. It’s versioned by Chromium milestone, around 150.x right now, not by npm.</p><iframe src="https://flo.uri.sh/visualisation/29999481/embed" width="700" height="575" frameborder="0" scrolling="no"><a href="https://medium.com/media/02542fca36ca0fc9ef4f7b1dfb92ab65/href">https://medium.com/media/02542fca36ca0fc9ef4f7b1dfb92ab65/href</a></iframe><p>The catch is that PDFium is C++. To run in a browser it has to be compiled to WebAssembly. That one fact is the whole story: one engine is JavaScript that ships as JavaScript, the other is C++ that ships as a WASM binary. Most of the tradeoffs in this piece fall straight out of it.</p><h3>The library landscape: which engine is under your viewer</h3><p>Most of the time you don’t pick an engine directly. You pick a React library, and it picks the engine. Here’s the map.</p><iframe src="https://flo.uri.sh/visualisation/29999570/embed" width="700" height="575" frameborder="0" scrolling="no"><a href="https://medium.com/media/382d77096e9f32922cd3c2254cdc67fe/href">https://medium.com/media/382d77096e9f32922cd3c2254cdc67fe/href</a></iframe><p>The PDF.js column is crowded because PDF.js is the default substrate for React PDF work. If you want a PDF.js alternative in React at the engine level, EmbedPDF is effectively the production-ready option today, with low-level wrappers like @embedpdf/pdfium and @hyzyla/pdfium underneath it.</p><p>Two caveats before you use that table. EmbedPDF is one PDFium-in-React viewer, not PDFium itself, so don’t treat “embedpdf react” and “PDFium” as synonyms. And the commercial SDKs sit in their own tier. Nutrient (formerly PSPDFKit) actually runs a PDFium-derived fork, while Apryse (formerly PDFTron) runs its own engine, so “commercial means custom engine” is only half true. I couldn’t confirm Syncfusion’s engine lineage, so I left it out rather than guess.</p><p>For the full feature-by-feature comparison of the React libraries themselves, see <a href="https://www.react-pdf-kit.dev/blog/how-to-build-a-pdf-viewer-in-react-with-pdf-js-ai-wojtekmaj-react-pdf-anaralabs-lector-and-react-pdf-kit-2026?utm_source=medium&amp;utm_medium=referral&amp;utm_content=pdfium-vs-pdfjs-choosing-a-react-pdf-engine-2026">our React PDF library comparison</a> on the blog.</p><h3>Rendering fidelity: fonts, color, and complex graphics</h3><p>This is the number one reason a team looks at PDFium. It’s the engine Chrome ships, so its output matches what users see when they open the file natively, and it tends to match Acrobat on the weird stuff. PDF.js does its parsing and font work in JavaScript, and that’s where the gaps show up.</p><h3>Color and CMYK</h3><p>Start here, because it’s the claim people are surest about, and the one that turns out to be backwards. A quick note on terms, since not everyone works in print. CMYK is the four-ink color model print uses, screens use RGB, and an ICC profile carries a document’s instructions for how its colors should map between the two. The reputation says PDF.js can’t manage color: it renders in RGB, ignores embedded ICC profiles, and converts CMYK through a rough built-in fallback. That stopped being true in 5.0, when PDF.js bundled QCMS, Mozilla’s own color engine, as a WebAssembly module, together with a CGATS001 DeviceCMYK reference profile. That is real ICC color management. It’s just off by default.</p><p>Two getDocument options switch it on. wasmUrl turns on the ICC path for embedded profiles, so ICCBased streams run through QCMS instead of the old alternate-colorspace fallback, the embedded-profile gap that <a href="https://github.com/mozilla/pdf.js/issues/2856">issue #2856</a> tracked for years. iccUrl goes further and routes DeviceCMYK through an ICC transform against the CGATS001 profile rather than a polynomial approximation, which is the imperfect default conversion a Mozilla maintainer described in <a href="https://github.com/mozilla/pdf.js/issues/8500">issue #8500</a>. Both of those long-standing complaints describe the default path, and the ICC path is what closes them.</p><p>The gap is easy to measure and easy to see. Open a CMYK-heavy file in a stock PDF.js viewer next to Chrome’s native one, and the colors are visibly off. On a DeviceCMYK swatch file, default PDF.js on 5.4.530 (the build tested here) is off from Chrome’s PDFium by as much as 60 out of 255 on a single channel. Turn the ICC options on and the same build comes within 3 out of 255, down at the level of screenshot sampling noise. So the color difference people blame on the engine is really a config default, not an engine limit. For marketing collateral, print proofs, packaging, or spot-color design files, that drift is the kind of error that surfaces only when the printed piece comes back wrong. And the fix is a few lines of config.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GpDmlKT-nRmbkW4jxpMoaw.png" /></figure><p>PDFium’s color story is narrower than its reputation too, and it’s worth stating fairly. It matches Chrome because it is Chrome’s engine, through an internal C++ CMYK-to-RGB path rather than app-layer color management. The browser viewers built on it pass that output straight through, so there’s no separate ICC pipeline doing the work. What PDFium gives you is correct color with nothing to set up. That’s a real convenience, but it’s parity by default, not something PDF.js can’t do.</p><h3>Turning it on, and the trap</h3><p>Setting wasmUrl and iccUrl does nothing on its own. The ICC path only activates when PDF.js is cleared to fetch worker assets, and that clearance turns on only if cMapUrl, standardFontDataUrl, and wasmUrl are all set and all resolve to valid fetch URLs against your document base. Leave out standardFontDataUrl and the color options are ignored in silence, no error, and no warning unless you&#39;ve raised the verbosity level. A working call passes all of them:</p><pre>pdfjsLib.getDocument({<br>  url,<br>  cMapUrl: &#39;/pdfjs/cmaps/&#39;,<br>  standardFontDataUrl: &#39;/pdfjs/standard_fonts/&#39;,<br>  wasmUrl: &#39;/pdfjs/wasm/&#39;,<br>  iccUrl: &#39;/pdfjs/iccs/&#39;,<br>})</pre><p>One last catch: those paths resolve inside the worker (the background thread PDF.js does its parsing in), not on the page. A relative URL there is taken relative to the worker script, not your page, so it quietly points at the wrong place. Pass absolute URLs instead. None of this is documented, so you only find it by reading the source, and it’s easy to get half-right. That is the real reason so few PDF.js viewers turn color management on, not any missing capability.</p><h3>Fonts and CJK</h3><p>PDF.js converts and sanitizes embedded fonts in JavaScript, which is where its edge cases live: missing glyphs in Source Han Sans (<a href="https://github.com/mozilla/pdf.js/issues/5377">#5377</a>), type3 font bugs (<a href="https://github.com/mozilla/pdf.js/issues/19634">#19634</a>), a CJK glyph regression (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1146106">Bugzilla 1146106</a>). If your documents are CJK-heavy, PDFium lands closer to Acrobat more often.</p><p>But most everyday PDFs render fine in PDF.js. <a href="https://hacks.mozilla.org/2014/05/how-fast-is-pdf-js/">Mozilla’s own benchmark</a> treats the badly-broken cases as unusual files. And not every difference is the engine’s fault. <a href="https://github.com/mozilla/pdf.js/issues/19221">Issue #19221</a> is a font error that also breaks in Adobe Reader, because the PDF itself is malformed.</p><h3>The gap is a moving target</h3><p>One more thing on fidelity, and it cuts against my own anchor. PDF.js 6.0 shipped on May 30, 2026, and it landed work in exactly the areas where PDFium historically led: CID and CJK font recovery, Adobe-parity hinting, and knockout and soft-mask transparency fixes. Those are the CJK and obscure-feature gaps, narrowing in a single release.</p><p>So the gap is real today, but it’s a trajectory, not a constant. PDFium moves too, with every Chromium milestone, so “date your comparison” cuts both ways. The full v6 rendering story deserves its own write-up, and that one’s coming.</p><h3>Rendering performance on heavy and complex PDFs</h3><p>The first question is usually which engine is faster. It depends on your documents, and I’ll get to why the public evidence can’t settle it. What you feel right away is how each one copes with a heavy document, and it doesn’t take an exotic file. An ordinary layout-heavy PDF with many elements and text runs is enough to make any renderer sweat. Past that sit the hard cases: CAD and architectural exports with huge path-operator counts (<a href="https://github.com/mozilla/pdf.js/issues/14652">PDF.js #14652</a>), large-format pages with dense vector linework, files with many optional-content layers that cost parse time even when hidden, and multi-hundred-page scans.</p><p>Here’s the correction to my own first take. I’d assumed PDF.js re-renders the canvas on every zoom step and therefore lags. That’s an oversimplification. Zoom smoothness depends on the <strong>viewer’s zoom strategy</strong> more than on the engine.</p><p>Some PDF.js viewers apply a cheap visual scale during the gesture and defer the sharp re-render until you let go, which feels smooth even on dense pages at the cost of a moment of blur. Others re-raster at every step, staying sharp throughout but lagging on complex documents. PDFium viewers pair native or WASM rasterization with virtual scrolling and tiling, which reads as responsive, but they pay the same cost re-rasterizing dense vector content at high zoom.</p><p>That’s what I was actually seeing in my architecture layout. It painted fine, then lagged on every scale change in one PDF.js viewer. The same file zoomed smoothly in Chrome’s native PDFium, in EmbedPDF, and in the hosted PDF.js demo. The demo isn’t getting that for free from the engine. It CSS-scales the existing canvas during the gesture and defers the sharp re-render until about 400 ms after you stop zooming, while the viewer I started in re-rasterizes on every step. Same engine, opposite feel. What I hit was a viewer-configuration gap, not the PDF.js engine failing to keep up.</p><p>The strain underneath is still real. Canvas trouble on complex pages is a known PDF.js limit (<a href="https://github.com/mozilla/pdf.js/issues/7265">issue #7265</a>). Teams used to reach for the SVG backend as an escape hatch, but it never really worked and has since been removed. <a href="https://apryse.com/blog/pdf-js/pdf-js-reliability-benchmark">Apryse’s 2019 benchmark</a>, from a vendor selling a competing engine, found CAD exports from GrabCAD failing to open or crashing the browser as often as 1 in 10. That’s a limit on what’s practical in a browser without careful viewer engineering, whichever engine you pick.</p><p>And this is where the evidence gets thinnest. Dropbox’s famous result, halving 75th-percentile Time to Interactive, was server-side PDFium-to-PNG in 2017, not in-browser WASM. The 2014 microbenchmarks disabled the text layer. So I won’t tell you PDFium is faster. On heavy PDFs the lag comes from how the viewer is built, not the engine underneath.</p><p>Test what matters to you instead:</p><ul><li>Gather your heaviest files: CAD and architectural exports, large scans, layer-heavy documents.</li><li>Open each one in every viewer you’re considering, and zoom in and out repeatedly on the densest areas.</li><li>Time how long it takes to get from the gesture to a sharp render, and watch memory on long scrolls.</li><li>Check it on real target hardware, not just your dev machine.</li></ul><h3>Forms and form fidelity</h3><p>The assumption going in is usually “PDFium does forms better.” It’s mostly a wash, with one persistent myth worth clearing up.</p><p>AcroForms work on both. PDF.js added AcroForm rendering in Firefox 84 and form JavaScript in 88. PDFium renders and fills them with Chrome and Acrobat fidelity, plus signatures. For the forms you’ll actually run into, there’s no real gap.</p><p>XFA is the part people get wrong. The naive line, “PDFium can’t do XFA,” is false. PDF.js renders XFA out of the box at the viewer layer (Firefox 93). On the PDFium side it’s a build-flag and implementation choice. Chrome’s shipped PDFium disables XFA, but the engine has the module and EmbedPDF’s own WASM compiles it in. I checked: FPDF_LoadXFA and the XFA packet functions are exported in EmbedPDF&#39;s pdfium.wasm. Its plugin just doesn&#39;t surface XFA in the UI. So PDF.js gives you XFA rendering for free, and on PDFium the engine has it but you&#39;d wire it up yourself. Not &quot;PDFium can&#39;t.&quot;</p><blockquote><em>One note on React PDF Kit. The library ships AcroForm only and skips XFA, even though PDF.js the engine could render it. Don’t read “PDF.js renders XFA” as “React PDF Kit renders XFA.”</em></blockquote><p>But XFA barely comes up anymore. It’s deprecated, removed from the PDF 2.0 spec and excluded from PDF/A, surviving only in legacy government, banking, and legal forms. If you don’t have XFA, none of this matters. If you do, PDF.js is the lower-effort path. Neither engine is a form-authoring SDK. That’s Nutrient, Apryse, or Syncfusion.</p><h3>Where PDF.js pulls ahead: bundle size, text, and accessibility</h3><p>The last few sections leaned PDFium’s way or came out even. This one doesn’t. PDF.js leads on the pieces a viewer is actually made of.</p><h3>Bundle size and load model</h3><p>PDF.js is the lighter default, and more of its weight is deferrable. You ship the display layer plus a worker. Reported sizes put the minified display layer around 299 KB (<a href="https://github.com/mozilla/pdf.js/issues/9087">issue #9087</a>), and a source-map breakdown puts it near 840 KB display plus 699 KB worker uncompressed, so roughly 1 to 1.5 MB before gzip, and less over the wire. The CJK cmaps and standard fonts load on demand through cMapUrl and standardFontDataUrl. You don&#39;t pay for them unless a document needs them.</p><p>PDFium is a fixed cost. It’s one WASM binary, fetched and instantiated up front, the same size no matter how simple the document. I measured EmbedPDF’s pdfium.wasm at 4.63 MB uncompressed, around 2.1 MB gzipped over the wire, fetched from a CDN by default, plus a one-time instantiation cost on cold start. There&#39;s no on-demand splitting of the engine itself. It caches after first load and stays constant, which is the upside, but the up-front number is real. If first paint matters in your app, PDF.js starts lighter.</p><h3>Text, search, and accessibility</h3><p>This is the quiet, decisive one. PDF.js builds a transparent text layer of positioned spans over the canvas. That gives you real selectable text, in-document search that maps to actual glyphs, and tagged-PDF accessibility for screen readers, which landed in Firefox 89. Those are the features you build a viewer around.</p><p>PDFium hands you none of that in the browser. Dropbox noted that text extraction and positioning were trickier with PDFium than with PDF.js. <a href="https://groups.google.com/g/pdfium-bugs/c/yt0WJ5h-GcU">pdfium-bugs #1523</a> is a screen-reader user flagging missing selection support. EmbedPDF rebuilds its own text and selection layer on top of PDFium to fill the hole, which works, but it’s work the viewer has to redo that PDF.js gives you for free. If you want to understand how this layer actually works, we covered <a href="https://www.react-pdf-kit.dev/blog/understanding-pdfjs-layers-and-how-to-use-them-in-reactjs">PDF.js layers</a> in a separate article on the React PDF Kit blog.</p><h3>A smaller security surface</h3><p>PDF.js runs as ordinary JavaScript using only normal web APIs, so its attack surface is small and browser-standard. PDFium is C++, with the usual memory-safety bug class and historically a larger surface, mitigated by Google’s continuous updates, sandboxing, and the browser’s WASM sandbox. Both engines restrict the Acrobat JavaScript APIs, and both run client-side now, so files don’t have to leave the device.</p><h3>What this means in a React project</h3><p>Engine choice eventually becomes a setup choice. This is what each one actually looks like in React and Next.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RsRCh250t8fhqmgb.png" /><figcaption>Rendering engine architecture of PDF.js and PDFium</figcaption></figure><p>On the PDF.js side, you need pdfjs-dist and a configured worker. React PDF Kit handles the worker for you. It sets GlobalWorkerOptions.workerSrc to a bundled worker file behind a window guard, and lets you override it:</p><pre>import * as pdfjs from &#39;pdfjs-dist&#39;<br><br>if (typeof window !== &#39;undefined&#39;) {<br>  const defaultWorkerUrl = new URL(<br>    &#39;pdfjs-dist/build/pdf.worker.min.mjs&#39;,<br>    import.meta.url<br>  ).href<br>  pdfjs.GlobalWorkerOptions.workerSrc = workerUrl || defaultWorkerUrl<br>}</pre><p>The viewer’s entry components are marked &#39;use client&#39;, so in Next.js App Router you load it as a client component. When something breaks, you debug it with normal JavaScript stack traces in devtools. That&#39;s underrated.</p><p>On the PDFium side, EmbedPDF boots the engine through a hook. usePdfiumEngine() fetches and initializes the PDFium WASM (from a CDN by default, with a worker: true option), and you hand the engine to a provider:</p><pre>import { EmbedPDF } from &#39;@embedpdf/core/react&#39;<br>import { usePdfiumEngine } from &#39;@embedpdf/engines/react&#39;<br><br>function App() {<br>  const { engine, isLoading, error } = usePdfiumEngine()<br>  // register plugins: viewport, scroll, render, tiling, search, selection<br>  return (<br>    &lt;EmbedPDF engine={engine} plugins={plugins}&gt;<br>      {/* Viewport with render, search, and selection layers */}<br>    &lt;/EmbedPDF&gt;<br>  )<br>}</pre><p>The manual C-style memory model PDFium is known for (malloc/free, FPDF_LoadMemDocument, FPDF_GetLastError) is real, but it lives inside the library. App developers use usePdfiumEngine, not raw memory.</p><p>One misconception to clear up: both of these are client-only in Next.js, but the mechanism differs. React PDF Kit uses &#39;use client&#39;. EmbedPDF uses typeof window guards plus dynamic imports. SSR-skipping isn&#39;t a PDF.js-only tax. The real difference is a worker file to resolve versus a WASM binary to fetch, which is a different problem, not a harder one in absolute terms.</p><p>If you’re on PDF.js and don’t want to reimplement worker config and the client-only wrapper for the hundredth time, that’s the gap React PDF Kit fills. It’s tailored for React, and it’s built to save you the weeks that the worker setup and the surrounding viewer features usually cost.</p><h3>PDFium vs PDF.js: how to choose</h3><p><strong>Pick PDFium when:</strong></p><ul><li>You need Chrome and Acrobat color parity with nothing to configure. PDF.js can match it, but only once you wire up its ICC options, so if you don’t control the viewer’s config, PDFium gets you there by default.</li><li>Your documents are CJK-heavy, or lean toward construction, large-format, or technical drawings where Acrobat parity is the explicit bar.</li><li>You’re shipping a document-review tool where a wrong color or a dropped glyph is a real problem. PDFium earns its WASM payload here.</li></ul><p><strong>Pick PDF.js when:</strong></p><ul><li>You want the broader ecosystem and JavaScript-native debugging, the path nearly every React PDF library already takes.</li><li>The mature text, search, and accessibility layer matters more to you than fidelity on the cases above.</li><li>Color-critical work doesn’t force you off PDF.js by itself. The ICC path ships in 5.x, so you can turn on color-managed CMYK when you need it, as long as you clear the config trap above.</li></ul><p><strong>Two honest footnotes:</strong></p><ul><li>v6 isn’t a free upgrade. PDF.js 6 raises the minimum supported browser versions even in its legacy build, so staying on the 5.x line is a real fidelity-versus-browser-support tradeoff.</li><li>The comparison dates fast in both directions. Even Dropbox, whose 2017 migration anchors a lot of the received wisdom here, has since <a href="https://gubello.me/blog/pdf-viewers-xss-and-pdf-files/">moved its previews off PDFium to a commercial SDK</a>.</li></ul><p>One honest caveat before you commit: Forms are a nuance, not a clean win for either engine, and even color, the one edge this piece let PDFium keep, turns out to be a PDF.js setting that ships off by default rather than a missing capability. The “PDFium just renders better and faster” reputation rests on dated and vendor evidence with no current neutral benchmark behind it. So don’t take my word for it or theirs: prototype both engines on your trickiest documents and see what actually differs.</p><p>If you’re staying on PDF.js and want the viewer layer handled instead of rebuilt, React PDF Kit’s docs and live demos are at <a href="https://www.react-pdf-kit.dev/?utm_source=medium&amp;utm_medium=referral&amp;utm_content=pdfium-vs-pdfjs-choosing-a-react-pdf-engine-2026">react-pdf-kit.dev</a>.</p><p>And put a date on whatever you decide. PDF.js ships roughly once a month and PDFium tracks Chromium, so there’s no permanent answer here, only the right one for your documents on today’s builds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c05c0ed55e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Add PDF Annotations in Vue.js:]]></title>
            <link>https://medium.com/@9haroon_dev/how-to-add-pdf-annotations-in-vue-js-bfdd1297c656?source=rss-b001e6e0fc89------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfdd1297c656</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pdf-viewer]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[webpdf]]></category>
            <category><![CDATA[pdf-annotation]]></category>
            <dc:creator><![CDATA[Kittisak Ma]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 14:59:36 GMT</pubDate>
            <atom:updated>2026-08-04T14:59:36.683Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Add PDF Annotations in Vue.js: PDF.js, vue-pdf-embed, @tato30/vue-pdf, and Vue PDF Viewer (2026)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGhXlO4U3Tz7Ka9LDEovKQ.png" /></figure><p>Vue PDF Viewer didn’t start as an annotation tool. It started as a viewer. Render a PDF, give it a toolbar, let people zoom and search and print. That’s what people asked for first, and for its first year that was the whole product.</p><p>Then, our users wanted to mark up the documents they were reading. So we added the first annotation tools in September 2025: highlight, free text, and image. The requests didn’t stop there, because a highlighter alone can’t say everything people need to say on a document. A highlight means “pay attention here,” an underline marks a reference, a strikethrough means “cut this.” Force all three through one yellow highlight and you lose the distinction, so underline and strikethrough followed in February 2026. I worked on that plugin. That’s the disclosure, and it’s also why I can tell you where each option’s seams are, ours included.</p><p>Here’s the part worth knowing before you write any code. Vue PDF Viewer renders with PDF.js, like most of the Vue ecosystem, so PDF.js’s own annotation editor was the obvious place to start on the creation side. It creates free text, ink, and stamps, and it has a highlight tool. It has no underline tool and no strikethrough tool. That gap has held for years. And the highlight it does give you is free-form rather than snapping cleanly to a text selection. So the text-selection toolkit ended up being something we built ourselves.</p><p>“Annotations” sounds like one feature. It’s really three separate jobs. This walks through how to add PDF annotations in Vue.js across four approaches (PDF.js directly, vue-pdf-embed, @tato30/vue-pdf, and Vue PDF Viewer), plus a couple of escape hatches for when none of them fit.</p><p><em>Versions tested: Vue 3.5.x, pdfjs-dist 5.4.530, vue-pdf-embed 2.1.4, @tato30/vue-pdf 2.1.0, @vue-pdf-viewer/viewer 4.3.0 with @vue-pdf-viewer/annotation 1.6.0, on Chrome and macOS.</em></p><h3>Rendering, creating, and persisting are three different jobs</h3><p>There are three problems hiding inside the word “annotation,” and conflating them is the most expensive mistake you can make. Someone drops a marked-up PDF into each demo, sees every highlight render perfectly, picks the smallest library, and finds out two sprints later that it can’t create a highlight at all.</p><p>The first is <strong>rendering</strong>: a PDF may already contain annotations (highlights, notes, stamps someone added in Acrobat), and your viewer has to display them. This is the easy problem. Every library here handles it, because PDF.js handles it.</p><p>The second is <strong>creating</strong>: your user selects a sentence and highlights it, draws on the page, leaves a comment. Different problem. It needs editing tools, a toolbar, state, and a way to turn a drag of the mouse into an annotation the PDF format understands. This is where the libraries split apart, and where most of them stop.</p><p>The third is <strong>persisting</strong>: the highlight your user just made has to survive a reload, a round-trip to your backend, and ideally open correctly in someone else’s PDF reader. Teams tend to find this one last, usually after shipping, when it’s too late to change the first two choices.</p><p>A library can render annotations perfectly and still create none of its own, or let users create them and then save them where no other reader can read them. Decide which of the three you need before you evaluate anything:</p><iframe src="https://flo.uri.sh/visualisation/29879546/embed" width="700" height="575" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8f21a073949987ec1aa1234070160b1/href">https://medium.com/media/f8f21a073949987ec1aa1234070160b1/href</a></iframe><p>We’ll take them one problem at a time, starting with the easy one.</p><h3>Rendering existing PDF annotations costs you one prop</h3><p>Someone marks up a contract in Acrobat. Three highlights, a strikethrough through a clause they want gone, an ink scribble in the margin, one sticky note. They email you the file and your Vue app has to show all of it.</p><p>That’s one prop.</p><p>PDF.js ships an annotation layer that walks the annotation objects already stored in the file and draws them over the rendered page. Both lightweight Vue libraries expose it the same way, as a boolean.</p><p>vue-pdf-embed (hrynko’s package on npm, not vue-pdf by FranckFreiburger, which is Vue 2 only and abandoned since 2021):</p><pre>&lt;script setup&gt;<br>import VuePdfEmbed from &#39;vue-pdf-embed&#39;<br>import &#39;vue-pdf-embed/dist/styles/annotationLayer.css&#39;<br>&lt;/script&gt;<br>&lt;template&gt;<br>  &lt;VuePdfEmbed source=&quot;/marked-up.pdf&quot; annotation-layer /&gt;<br>&lt;/template&gt;</pre><p>@tato30/vue-pdf does the same job with a per-page API:</p><pre>&lt;script setup&gt;<br>import { VuePDF, usePDF } from &#39;@tato30/vue-pdf&#39;<br>import &#39;@tato30/vue-pdf/style.css&#39;<br>const { pdf } = usePDF(&#39;/marked-up.pdf&#39;)<br>&lt;/script&gt;<br>&lt;template&gt;<br>  &lt;VuePDF :pdf=&quot;pdf&quot; annotation-layer /&gt;<br>&lt;/template&gt;<br></pre><p>If you forget the stylesheet, the layer mounts invisibly, which is the one catch here and costs an afternoon the first time. Otherwise you get the whole subtype set: link, text, highlight, underline, strikeout, squiggly, ink, stamp, free text. Underline and strikeout included, which matters shortly.</p><p>Our own changelog puts a date on just how far rendering ran ahead of creating. Vue PDF Viewer v1.5.0 shipped on 29 October 2024 and rendered highlight, strikeout, underline, squiggly, ink and free text. The first annotation a user of ours could <em>create</em> shipped in September 2025, eleven months later, and it was highlight, free text and image only. Underline and strikethrough creation didn’t release until February 2026, sixteen months after we could already draw them on a page.</p><h3>Creating PDF annotations is where the libraries come apart</h3><p>Four ways to let a user make a mark, ordered by how much ships versus how much you build.</p><h3>The PDF.js annotation editor</h3><p>Everything below except pdf-lib is standing on this, so start here. PDF.js has an editor layer, the same one behind the markup tools in Firefox’s built-in viewer. You turn it on and set a mode:</p><pre>import { AnnotationEditorType } from &#39;pdfjs-dist&#39;<br>// on a PDFViewer instance you&#39;ve already set up yourself<br>pdfViewer.annotationEditorMode = { mode: AnnotationEditorType.HIGHLIGHT }<br>// FREETEXT | HIGHLIGHT | INK | STAMP, plus a signature editor in recent builds.<br>// There is no AnnotationEditorType.UNDERLINE.<br>// There is no AnnotationEditorType.STRIKEOUT.</pre><p>That enum is the entire story. Free text, highlight, ink, stamp, and a signature editor built on top of stamp in recent builds. No underline tool. No strikethrough tool. Not on any version, including Mozilla’s unreleased development code. This isn’t a “not yet,” it’s the shape the project has had for years, and the annotations it refuses to author are the same ones it renders without complaint if they’re already in the file.</p><p>On versions: if you’re building straight on PDF.js, 6.1.200 is the current release, and none of the above changes. We test against the 5.x line ourselves, because Vue PDF Viewer’s peer range (^5.4.530) excludes 6.x by construction.</p><p>The highlight tool you do get is free-form. There’s a text-selection mode in there, and on a clean single-column page it behaves. Give it a two-column layout with a table in the middle, though, and the snapping gets too unreliable to put in front of users. That’s our experience building on it rather than a documented limitation, so weigh it as such. What you can promise is “highlight a region,” not “highlight that sentence.”</p><p>Two more things fall on you. The marks the editor makes are HTML overlays on top of the page, not part of the PDF itself. Draw a highlight in <a href="https://mozilla.github.io/pdf.js/web/viewer.html">Mozilla’s demo viewer</a>, open DevTools, and here is what you actually made:</p><pre>&lt;div class=&quot;annotationEditorLayer highlightEditing&quot;&gt;<br>  &lt;div id=&quot;pdfjs_internal_editor_0&quot; class=&quot;highlightEditor selectedEditor&quot;<br>       role=&quot;mark&quot; aria-label=&quot;Highlight editor&quot;<br>       style=&quot;left: 51.69%; top: 49.9%; width: 39.36%; height: 3.99%;&quot;&gt;<br>    &lt;div class=&quot;internal&quot; style=&quot;clip-path: url(#clip_path_0);&quot;&gt;&lt;/div&gt;<br>    &lt;div class=&quot;editToolbar&quot; role=&quot;toolbar&quot;&gt;…&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>A percentage-positioned &lt;div&gt; with a clip-path, sitting in a sibling layer above canvasWrapper and textLayer. Note the id: pdfjs_internal_editor_0. Internal, as the name says. It&#39;s a DOM node in your app, not a byte in the PDF. Saving it into the file where another reader can see it is a separate job (that&#39;s Section 4&#39;s problem). And the toolbar is yours to build. All of it: the tool picker, the colour swatches, the delete button, and the state that tracks which tool is active.</p><h3>@tato30/vue-pdf’s editor-layer is that same editor in Vue clothing</h3><p>This is not a second, separate approach. It’s the PDF.js editor from above, wrapped in a Vue component so you’re setting a prop instead of managing a viewer instance. That wrapping earns @tato30 a distinction worth naming: it’s the only lightweight Vue PDF library that creates annotations at all.</p><pre>&lt;template&gt;<br>  &lt;VuePDF :pdf=&quot;pdf&quot; :page=&quot;page&quot; editor-layer /&gt;<br>&lt;/template&gt;</pre><p>You get the primitives in Vue components: free text, highlight, ink, stamp, plus comments. If drawing is what you need, ink is the primitive here, and it works.</p><p>Two limits worth knowing before you commit. It’s beta-stage, and interactions are limited to single pages, which matters the moment your review UI scrolls. A contract clause that starts at the bottom of page 4 and finishes at the top of page 5 becomes two separate annotations on two &lt;VuePDF&gt; instances, and stitching them back into one highlight is your code. TaTo30&#39;s release notes are unusually straight about the ceiling: other annotation types won&#39;t be supported as long as pdf.js doesn&#39;t support them. That&#39;s the honest answer, and it&#39;s also exactly the problem. The library inherits PDF.js&#39;s gaps along with its primitives, so underline and strikethrough aren&#39;t here either.</p><p>You still build the UX. What you save is the wiring, not the toolbar.</p><h3>pdf-lib, for when you just need it burned in</h3><p>Different shape entirely. pdf-lib has no viewer and no UI. It’s a framework-agnostic library that opens a PDF, draws into it, and hands you back bytes. Useful server-side, or as a pre-render step before the document ever reaches your Vue component.</p><pre>import { PDFDocument, rgb } from &#39;pdf-lib&#39;<br>const pdfDoc = await PDFDocument.load(existingBytes)<br>const page = pdfDoc.getPages()[0]<br>page.drawText(&#39;APPROVED&#39;, { x: 50, y: 700, size: 24, color: rgb(0.8, 0, 0) })<br>const stamped = await pdfDoc.save()j</pre><p>The catch is what those marks are. They’re content drawn into the page, not standard PDF annotation objects, so they won’t appear in Acrobat’s or Preview’s annotation panel and nobody can select, edit or delete them afterward. That’s the point if you’re stamping an approval watermark. It’s the wrong tool if a human needs to take the mark back off.</p><p>Maintenance, honestly: v1.17.1 is the latest, released November 2021. Nothing since. It still works, and plenty of production pipelines run on it, but you’re adopting a frozen dependency.</p><h3>The Vue PDF Viewer annotation plugin</h3><p>Our option, and the disclosure from the top of this article applies. Activation is one prop:</p><pre>&lt;script setup&gt;<br>import { VPdfViewer } from &#39;@vue-pdf-viewer/viewer&#39;<br>import VPdfAnnotationPlugin from &#39;@vue-pdf-viewer/annotation&#39;<br>&lt;/script&gt;<br>&lt;template&gt;<br>  &lt;VPdfViewer src=&quot;/marked-up.pdf&quot; :plugins=&quot;[VPdfAnnotationPlugin()]&quot; /&gt;<br>&lt;/template&gt;</pre><p>That gets you a create UI for highlight, underline, strikethrough, free text and image (the docs call the image one Image Overlay). Underline and strikethrough are in there because we wrote the text-selection toolkit ourselves rather than inheriting PDF.js’s editor, which is the whole reason this article exists. Highlight, free text and image came first in September 2025; underline and strikethrough followed by request in February 2026.</p><p>Now the edges, because you’ll find them anyway. Comments are view-only today: the panel displays comment threads already in the file, and there’s no create button. Drawing, shapes and a stamp palette aren’t in the plugin today (the image tool covers arbitrary user-supplied images, not preset approval stamps), and e-signatures and form-field authoring aren’t either; I won’t even tell you those two are planned, because they aren’t. If ink drawing is your core requirement today, the honest answer is @tato30’s editor-layer or raw PDF.js, not this plugin.</p><h3>Persisting PDF annotations is the part that bites you later</h3><p>Your user highlights a clause and closes the tab. Now what? That question decides more than rendering and creating combined. There are three sub-questions inside it. Where does the annotation data live, how is it serialized (as XFDF, the XML standard other readers can import, or as JSON only your own app understands), and can anything besides your app read it back?</p><p><strong>PDF.js editor.</strong> You save the annotations yourself and store them somewhere. Then there’s the problem Section 3 handed forward: those editor overlays are DOM nodes, and getting them into the file is a job PDF.js won’t do for you. Your highlights work in your app. Open the same file in Preview and they were never there.</p><p><strong>@tato30/vue-pdf.</strong> Same editor, same problem, plus the single-page caveat shaping how you batch what you save.</p><p><strong>pdf-lib.</strong> The marks are drawn straight into the page, which is the point: there’s no separate save step, they’re just part of the file pdf-lib hands back. No round-trip either. They’re page content now, not annotations, so there’s nothing to export, edit or remove.</p><p><strong>Vue PDF Viewer.</strong> Save, print and download with annotations baked in, plus XFDF export and import through the XFDF Controller in the Instance API. That shipped on 3 July 2026 in annotation v1.6.0 and viewer v4.3.0.</p><pre>// `viewer` is a template ref on the &lt;VPdfViewer&gt; component<br>// export the current annotations as an XFDF string, store it wherever you like<br>const xfdf = await viewer.value.annotationXfdfControl.exportToXfdf()<br>// later, on a fresh mount of the same document (importFromXfdf is synchronous)<br>const { annotations, skipped, errors } = viewer.value.annotationXfdfControl.importFromXfdf(xfdf)</pre><p>What comes back is a document, not a private blob. A single highlight serializes to something like this:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;xfdf xmlns=&quot;http://ns.adobe.com/xfdf/&quot; xml:space=&quot;preserve&quot;&gt;<br>  &lt;f href=&quot;contract.pdf&quot;/&gt;<br>  &lt;annots&gt;<br>    &lt;highlight page=&quot;0&quot; rect=&quot;72.0000,690.2000,331.5000,704.8000&quot;<br>               color=&quot;#FFE066&quot; opacity=&quot;0.4&quot;<br>               name=&quot;6f1c…&quot; title=&quot;Vue PDF Viewer&quot;<br>               date=&quot;D:20260703T101500&quot; creationdate=&quot;D:20260703T101500&quot;<br>               flags=&quot;print&quot;<br>               coords=&quot;72.0000,704.8000,331.5000,704.8000,72.0000,690.2000,331.5000,690.2000&quot;/&gt;<br>  &lt;/annots&gt;<br>&lt;/xfdf&gt;</pre><p>A zero-based page index, the colour, and the quad points of the highlighted text, in a schema Acrobat and Preview already parse. The &lt;f href&gt; names the document the marks belong to; coords is an attribute, not a child element, because that&#39;s the one spelling Acrobat actually reads. That&#39;s why the string is worth storing in your own database: it&#39;s readable by things that aren&#39;t your app.</p><p>One precision, because I’d rather you hear it here than in a support ticket: this is programmatic, not a button. There’s no end-user Export XFDF item in the toolbar. You call it from the Instance API and you decide when. If what you want is a file on the user’s disk rather than a string, exportToXfdf({ download: true }) does that.</p><p>And it’s not only the marks your users made. Export walks the whole document and merges what’s in the editor with the annotations already in the file when it loaded, so a PDF that arrives with ink from someone’s tablet and squares from a reviewer’s Acrobat round-trips those too. Thirteen annotation types survive the trip, not just the five the toolbar can create.</p><p>The reason XFDF matters isn’t that it’s ours. It’s that a standards-based round-trip is the exact thing PDF.js’s overlays can’t do and the exact thing pdf-lib gives up by drawing straight into the page. A highlight your reviewer makes in your Vue app opens in their lawyer’s Acrobat. That’s the whole argument, and it’s a format argument rather than a product one.</p><p><strong>Signatures deserve a mention</strong>, since for many people they’re the whole reason for using annotations. Free-text and image annotations can serve as lightweight signatures, and persistence is what makes one stick: an image that vanishes on reload isn’t a signature. But none of these lightweight Vue options is a real e-signature <em>workflow</em> product.</p><h3>When you actually need the enterprise tier</h3><p>Two options sit above everything discussed so far, and it would be dishonest to leave them out.</p><p><strong>Syncfusion</strong>’s EJ2 Vue PDF Viewer ships text markup, shapes, stamps, ink, free text, sticky notes, measurement tools, form filling, e-signatures and redaction. <strong>Nutrient</strong> (formerly PSPDFKit) covers 17+ annotation types with create, edit and remove available through the UI or programmatically, XFDF and JSON round-trips, and real-time collaboration sync.</p><p>Both are commercial, both are priced accordingly, and both are genuinely more capable than anything else on this page. Reach for them when annotation breadth, compliance or multi-user collaboration is the product. Not when markup is a supporting feature rather than the core of the product or system.</p><h3>Picking a path</h3><p>Match the tool to what you’re actually building, not to the shortest README.</p><p><strong>Displaying markup that already exists.</strong> vue-pdf-embed, or @tato30/vue-pdf if you want per-page control. One prop, MIT, done this afternoon. Reaching past this tier for a read-only viewer is how projects acquire dependencies they regret.</p><p><strong>Lightweight DIY markup, and you’re willing to build the UI.</strong> The PDF.js editor layer directly, or @tato30’s editor-layer for the Vue wrapping. You get free text, highlight, ink and stamp. You write the toolbar, the state, and the persistence. Budget real time for the last one.</p><p><strong>Server-side or pre-render stamping, no UI at all.</strong> pdf-lib. Frozen since 2021 and fine for the job, as long as the job is burning marks in permanently.</p><p><strong>Shipping a review or markup feature without building the toolbar.</strong> Vue PDF Viewer, and here the disclosure at the top applies: it’s the only option that ships underline and strikethrough creation, because PDF.js has no tool to create them and everything downstream inherits that gap. Add the XFDF round-trip and the toolbar you’d otherwise be writing, and the trade is a commercial licence against the weeks in Section 3. If your project can’t take a paid licence, that trade doesn’t exist and @tato30’s editor-layer is your answer.</p><p><strong>Compliance, collaboration, or 17+ annotation types.</strong> Syncfusion or Nutrient.</p><p>Here’s the full picture, pdf-lib included:</p><iframe src="https://flo.uri.sh/visualisation/29879906/embed" width="700" height="575" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c7e3338d59208cdfd3154ba37c53a52/href">https://medium.com/media/4c7e3338d59208cdfd3154ba37c53a52/href</a></iframe><p><em>Versions verified 16 July 2026. Releases move. Re-check before you commit to any of this.</em></p><h3>What to decide before you install anything</h3><p>Rendering is one prop. Creating is where the libraries come apart, and the gap runs deeper than any of them advertise: PDF.js has no underline or strikethrough tool, so nothing built on PDF.js has one either unless someone sat down and wrote it. Persisting is the one that surfaces after launch, when someone opens your reviewed contract in Acrobat and finds a clean page.</p><p>So the useful question isn’t which library is best. When you ask how to add PDF annotations in Vue, you’re asking about three jobs, and the one that matters is whichever you’re actually signing up for. Answer that first and most of this page collapses into one row of the table.</p><p>If it turns out you need the create UI and the round-trip, the <a href="https://www.vue-pdf-viewer.dev/docs/?utm_source=medium&amp;utm_medium=referral&amp;utm_content=how-to-add-pdf-annotations-in-vuejs-pdfjs-vue-pdf-embed-tato30vue-pdf-and-vue-pdf-viewer">annotation plugin docs</a> and live demo are the fastest way to check whether it fits, including the parts it doesn’t do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfdd1297c656" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a React PDF Viewer for Next.js in Minutes]]></title>
            <link>https://javascript.plainenglish.io/how-to-build-a-react-pdf-viewer-for-next-js-in-minutes-4be5f631a84c?source=rss-b001e6e0fc89------2</link>
            <guid isPermaLink="false">https://medium.com/p/4be5f631a84c</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Kittisak Ma]]></dc:creator>
            <pubDate>Tue, 17 Jun 2025 12:01:40 GMT</pubDate>
            <atom:updated>2025-09-16T15:42:15.480Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*5ik6avd2DKV9LsbWp4QDwg.jpeg" /></figure><p>Since my last post on <a href="https://blog.react-pdf.dev/best-4-methods-to-build-a-pdf-viewer-in-reactjs-pdfjs-react-pdf-and-more-2024-guide">Best 4 Methods to Build a PDF Viewer in React.js: PDF.js, react-pdf, and More</a>, my team and I launched React PDF in March 2025, a library that help React developers easily add a React PDF viewer to their Next.js apps.</p><p>In this article, I’ll show you how to display the default PDF Viewer in Next.js in just a few steps. I’ll also share a few use cases to help you make the most out of React PDF in your own projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*-VAz9GKXnIROz0RH.gif" /></figure><h3>Why React PDF?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*6UZUQbFoeIqKgsyR.png" /></figure><p>If you’re building a PDF viewer in a Next.js app, you need a component that just works. <a href="https://www.react-pdf.dev/?utm_source=medium&amp;utm_medium=referral&amp;utm_content=how-to-build-a-react-pdf-viewer-for-nextjs-in-minutes">React PDF</a> stands out for its balance of powerful features and simple setup. You can drop it into your Next.js project with little work and handles most of what React devs expect. Its API feels natural if you know React, so no relearning is required.</p><p>React PDF offers everything most apps need right out of the box. Here’s what you get:</p><ol><li><strong>React-First</strong>: Designed specifically for React.js developers, React PDF uses familiar component-based patterns, and hooks fit right in with your Next.js app’s structure.</li><li><strong>Customizable</strong>: You can style or customize easily. From changing icons and colors to match your branding or customize your toolbar layout with React Context APIs to fit your app’s needs.</li><li><strong>Responsive Design</strong>: Fits devices big or small, so mobile users can scroll, zoom, and interact with ease.</li><li><strong>High Performance</strong>: Optimized for handling large PDFs without sacrificing speed or performance.</li><li><strong>No surprises</strong>: The documentation is clear, and support is strong. Bugs get addressed fast. Most developers will find everything they need quickly.</li></ol><h3>Step 1: Set up a Next.js Project</h3><p>In this tutorial, I’ll use StackBlitz to demonstrate how to build a React PDF Viewer in a Next.js project. Here’s how to get started.</p><h3>1.1 Visit StackBlitz &amp; Create a New Project</h3><p>Go to <a href="https://stackblitz.com/">https://stackblitz.com</a>. Assuming you already have an account and are logged in, click “New Project” in the top-right corner. You’ll see a list of available frameworks — select Next.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*xHCCI9i9NBVOceuy.png" /></figure><h3>1.2 Wait for StackBlitz to Set Things Up</h3><p>StackBlitz will automatically install the necessary dependencies and launch your Next.js project in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*LINenCa4joU7Ldgh.png" /></figure><p>That’s it! You’re now ready to integrate React PDF Viewer into your StackBlitz-based Next.js project.</p><h3>Step 2: Integrate React PDF into a Next.js Project</h3><h3>2.1 Install React PDF</h3><p>First, install the @pdf-viewer/react package in your project.<br>In the StackBlitz terminal, press Ctrl + C to stop the current process, then run the following command:</p><pre>npm install @pdf-viewer/react</pre><p>Wait for the installation to complete. This should only take a few seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*SWI7mq5ocq2Ut1Vy.png" /></figure><p>If you’re installing this library in your own Next.js project, check out the <a href="https://docs.react-pdf.dev/introduction/getting-started#installation?utm_source=medium&amp;utm_medium=referral&amp;utm_content=how-to-build-a-react-pdf-viewer-for-nextjs-in-minutes">installation guide</a> for more details.</p><h3>2.2 Set Up the Viewer</h3><p>After installing, follow these steps to set up the PDF viewer:</p><p>💡 <strong>Pro Tip</strong>: Always use client-side rendering for these components using dynamic imports to prevent hydration mismatches and SSR-related issues with PDF rendering.</p><h4>Add RPConfig at the Root Level</h4><p>The RPConfig component provides the global configuration for React PDF and should wrap your entire app.</p><p>Place the RPConfig component at the root of your application (e.g., in _app.tsx or a root layout component). Make sure it only runs on the client side.</p><p><em>components/AppProviders.tsx</em></p><pre>&#39;use client&#39;;<br>import { RPConfig, RPConfigProps } from &#39;@pdf-viewer/react&#39;;<br>import { type PropsWithChildren } from &#39;react&#39;;<br><br>function AppProviders({<br>  children,<br>  ...props<br>}: PropsWithChildren&lt;RPConfigProps&gt;) {<br>  return &lt;RPConfig {...props}&gt;{children}&lt;/RPConfig&gt;;<br>}<br>export default AppProviders;</pre><p><em>components/LazyAppProviders.tsx</em></p><pre>&#39;use client&#39;;<br>import dynamic from &#39;next/dynamic&#39;;<br><br>const LazyAppProviders = dynamic(() =&gt; import(&#39;./AppProviders&#39;), {<br>  ssr: false,<br>});<br>export default LazyAppProviders;</pre><p><em>app/layout.tsx</em></p><pre>import { type PropsWithChildren } from &#39;react&#39;<br>import LazyAppProviders from &#39;./components/LazyAppProviders&#39;<br><br>export default function RootLayout({ children }: PropsWithChildren) {<br> return (<br>   &lt;html lang=&quot;en&quot;&gt;<br>     &lt;body&gt;<br>      &lt;LazyAppProviders licenseKey=&quot;your-license-key&quot;&gt;<br>        &lt;main&gt;<br>          { children }<br>        &lt;/main&gt;<br>      &lt;/LazyAppProviders&gt;<br>    &lt;/body&gt;<br>   &lt;/html&gt;<br> )<br>}</pre><h3>Step 3: Create a Reusable PDF Viewer Component</h3><p>To keep your code clean and reusable, it’s a good practice to wrap the viewer in its own component. This also makes it easier to customize or extend the viewer later as your app grows.</p><p><strong>Build</strong> <strong>the</strong> AppPdfViewer <strong>component</strong></p><p><em>components/AppPdfViewer.tsx</em></p><pre>&#39;use client&#39;<br>import { RPProvider, RPDefaultLayout, RPPages } from &#39;@pdf-viewer/react&#39;<br><br>interface OwnProps {<br> src: string<br>}<br>const AppPdfViewer = (props: OwnProps) =&gt; {<br> const { src } = props<br>   return (<br>     &lt;RPProvider src={ src }&gt;<br>       &lt;RPDefaultLayout&gt;<br>         &lt;RPPages /&gt;<br>       &lt;/RPDefaultLayout&gt;<br>     &lt;/RPProvider&gt;<br>   )<br>}<br>export default AppPdfViewer</pre><h3>Create a Lazy-Loaded Wrapper Component</h3><p>Since React PDF is client-side only, we’ll also create a lazy wrapper to prevent SSR issues and hydration errors in Next.js.</p><p><em>components/LazyAppPdfViewer.tsx</em></p><pre>&#39;use client&#39;<br>import dynamic from &#39;next/dynamic&#39;<br><br>const LazyAppPdfViewer = dynamic(() =&gt; import(&#39;./AppPdfViewer&#39;), {<br> ssr: false<br>})<br>export default LazyAppPdfViewer</pre><h3>Use the PDF Viewer in Your App</h3><p>You can now use LazyAppPdfViewer anywhere in your Next.js application.</p><p>Here’s an example of how to use it on the index page:</p><p><em>app/index.tsx</em></p><pre>import LazyAppPdfViewer from &#39;../components/LazyAppPdfViewer&#39;;<br><br>export default function Home() {<br>  const pdfUrl = &quot;https://cdn.codewithmosh.com/image/upload/v1721763853/guides/web-roadmap.pdf&quot;<br>  return (<br>   ...<br>   &lt;div className=&quot;pdf-viewer mb-3 w-[500px] lg:w-[992px]&quot;&gt;<br>    &lt;LazyAppPdfViewer src={ pdfUrl } /&gt;<br>   &lt;/div&gt;<br>   ...<br>  )<br>}</pre><p>That’s it! You should now see your PDF in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*fReEBVTkq2hiBzdZ.png" /></figure><p><em>Note: At the moment, </em><em>Hot Module Reload (HMR) does not apply css style automatically to a component that dynamically import with </em><em>ssr: false. It is recommended to refresh the page after changing the component.</em></p><h3>Looking for a Faster Setup?</h3><p>If you want to skip boilerplate and get straight to building, check out the <a href="https://docs.react-pdf.dev/usage-guide/starter-toolkit?utm_source=medium&amp;utm_medium=referral&amp;utm_content=how-to-build-a-react-pdf-viewer-for-nextjs-in-minutes">React PDF Starter Toolkit</a>.</p><p>It includes ready-to-use templates for:</p><ul><li><strong>React (Vite / Webpack)</strong></li><li><strong>Next.js (JavaScript / TypeScript)</strong></li></ul><p>Each template comes with a clean folder structure and sample code so you can build a PDF viewer quickly without spending hours configuring dependencies. Just clone, customize, and go. 🚀</p><h3>Common Use Cases</h3><h3>Customize the PDF Viewer to Match Your Branding</h3><p>Every project has its own look and feel. @pdf-viewer/react makes it easy to tailor the PDF viewer’s appearance so it fits right into your app — whether it’s light mode, dark mode, or a custom color palette.</p><p>With the customVariables prop in the RPTheme component, you can quickly apply brand colors to the viewer without digging into complex CSS overrides.</p><p>Here’s a simple example of applying a custom background color:</p><pre>...<br>const AppPdfViewer = (props: OwnProps) =&gt; {<br> const { src } = props<br>   return (<br>     &lt;RPProvider src={ src }&gt;<br>       &lt;RPTheme<br>          customVariables={{ &#39;--rp-toolbar-background&#39;: &#39;#F7E3D5&#39; }}<br>          customDarkVariables={{ &#39;--rp-toolbar-background&#39;: &#39;#874707&#39; }}<br>        &gt;<br>         &lt;RPDefaultLayout&gt;<br>           &lt;RPPages /&gt;<br>         &lt;/RPDefaultLayout&gt;<br>       &lt;/RPTheme&gt;<br>     &lt;/RPProvider&gt;<br>   )<br>}<br><br>export default AppPdfViewer</pre><p><em>Light Mode</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*3lXsf_IU77UMlgeP.png" /></figure><p><em>Dark Mode</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*HDhOl6dyz_A-D1Yn.png" /></figure><p>Why this is useful:</p><ul><li>Provides a consistent branded experience</li><li>Works out of the box with theme switching (light/dark mode)</li><li>Saves time styling PDF viewers for modern UIs</li></ul><p>Curious about more CSS variables you can override? Check out <a href="https://docs.react-pdf.dev/usage-guide/overriding-style?utm_source=medium&amp;utm_medium=referral&amp;utm_content=how-to-build-a-react-pdf-viewer-for-nextjs-in-minutes">Overriding Style</a> for details.</p><h3>Customize Any Toolbar Icon</h3><p>The @pdf-viewer/react component offers flexibility in customizing the user interface. You can easily replace any default icons with your own, allowing you to maintain brand consistency or match with the rest of your application’s UI.</p><p>Here’s an example of how to replace the default toolbar icons in @pdf-viewer/react with <a href="https://lucide.dev/">Lucide Icons</a>, allowing for a more customized and consistent user interface.</p><p>To get started, install the Lucide Icons package:</p><pre>npm install lucide-react</pre><p>Once installed, you can import and use Lucide icons to replace the default icons in @pdf-viewer/react.</p><pre>...<br>const AppPdfViewer = (props: OwnProps) =&gt; {<br>  const { src } = props;<br>  const defaultIconDimension = { width: 20, height: 20 };<br>  return (<br>   ...<br>    &lt;RPDefaultLayout<br>      icons={{<br>        zoomInIcon: &lt;ZoomInIcon {...defaultIconDimension} /&gt;,<br>        zoomOutIcon: &lt;ZoomOutIcon {...defaultIconDimension} /&gt;,<br>        downloadIcon: &lt;DownloadIcon {...defaultIconDimension} /&gt;,<br>        searchIcon: &lt;SearchIcon {...defaultIconDimension} /&gt;,<br>        // ...<br>      }}<br>    &gt;<br>      &lt;RPPages /&gt;<br>    &lt;/RPDefaultLayout&gt;<br>   ...<br>  )<br>}<br>...</pre><p>At this point, all of the viewer’s toolbar icons have been successfully replaced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*PiCeo0EI2kINCRCk.png" /></figure><p>If you’d like to see the example code in action, check out my <a href="https://stackblitz.com/edit/stackblitz-starters-wure37ms?file=components%2FAppPdfViewer.tsx">StackBlitz</a> for this article.</p><h3>Conclusion</h3><p>Adding a PDF viewer to your Next.js app is simple with <a href="https://www.react-pdf.dev/?utm_source=medium&amp;utm_medium=referral&amp;utm_content=how-to-build-a-react-pdf-viewer-for-nextjs-in-minutes">React PDF</a> viewer. The setup takes just a few steps, and you instantly get a flexible, fast and robust tool. The viewer works responsively across different devices and screen sizes. You can easily style it to match your app’s look or let users zoom in and jump to pages without any hassle.</p><p>React PDF is a great choice for:</p><ul><li>Simple PDF reading experiences</li><li>Document workflows and approval systems</li><li>AI-powered tools that need to display PDFs</li><li>Business and productivity apps with embedded documents</li></ul><p>It takes care of PDF rendering behind the scenes — so you can focus on building great features your users want.</p><p>Try it out and see how easy it is to upgrade your project’s PDF viewing experience! 🚀</p><p>👉 Want to explore more? Check out the full <a href="https://docs.react-pdf.dev/?utm_source=medium&amp;utm_medium=referral&amp;utm_content=how-to-build-a-react-pdf-viewer-for-nextjs-in-minutes">React PDF documentation</a> to see what else you can build.</p><p><em>If you found this helpful, let me know! And if you build something cool with React PDF, I’d love to hear about it.</em></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4be5f631a84c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-build-a-react-pdf-viewer-for-next-js-in-minutes-4be5f631a84c">How to Build a React PDF Viewer for Next.js in Minutes</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Understanding PDF.js Layers and How to Use them in React.js]]></title>
            <link>https://javascript.plainenglish.io/understanding-pdf-js-layers-and-how-to-use-them-in-react-js-6e761d796c2f?source=rss-b001e6e0fc89------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e761d796c2f</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Kittisak Ma]]></dc:creator>
            <pubDate>Tue, 20 May 2025 12:02:34 GMT</pubDate>
            <atom:updated>2025-08-26T05:24:41.430Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WkdUVyUX-cArxznF4Ya_Bg.jpeg" /></figure><p>PDF files are everywhere but working with PDFs in a React.js project can be frustrating. You might run into clunky plugins, awkward iframes, or glitches that break the user experience. PDF.js gives you a powerful, open-source JavaScript library to display and interact with PDF files right in the browser.</p><p>Now, figuring out how to use PDF.js in your React project can be daunting at first. To leverage PDF.js’s capabilities, it’s important to understand how its layered structure works.</p><p>If you’ve ever wondered, “How do I highlight text selection?” or “How do I interact with links inside the PDF?” or even “How do I build advanced features like annotations?”, the answer usually lies in understanding these layers.</p><p>In this guide, you’ll see how PDF.js splits content into layers, what those layers do, and how you can use them in your next React project. Let’s get going!</p><h3>React PDF: Flexible and Powerful React PDF Viewer</h3><p>Before diving into the technical side of things, let me introduce you to React PDF — a library I’ve been working on: <a href="https://www.react-pdf.dev/?utm_source=medium&amp;utm_medium=referral&amp;utm_content=layers-of-pdfjs-and-how-you-can-use-them-in-reactjs">React PDF</a> is a handy PDF Viewer that renders PDFs right within your React.js or Next.js app. It packs over 20 features, including out-of-the-box default toolbar, customization and responsive design, so your users never have to leave your site to interact with your documents.</p><p>React PDF can integrated into various applications whether it’s for a Document Management System, Workflow Management System, AI tool or simply as a PDF reader.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*FeiwMP0U04ZxPeLV.png" /></figure><p>If that sounds interesting, I’d love for you to give <a href="https://www.react-pdf.dev/?utm_source=medium&amp;utm_medium=referral&amp;utm_content=layers-of-pdfjs-and-how-you-can-use-them-in-reactjs">React PDF</a> a try. Your support helps me keep creating awesome tools and tutorials like this one. ❤️</p><h3>Overview of PDF.js Layers</h3><p>Before we dive in, Here’s a quick overview of the four main layers in PDF.js. Each layer handles a specific aspect of rendering or user interaction:</p><ol><li><strong>Canvas Layer</strong>: This layer draws the core visuals of your PDF — shapes, images, and text as graphics. It forms the base of your PDF Viewer.</li><li><strong>Text Layer</strong>: Placed above the canvas, this layer lets users select and search text.</li><li><strong>Annotation Layer</strong>: This layer manages interactive items like links, form fields, and highlights, so users can click, enter information, or move around the document.</li><li><strong>Structural Layer</strong>: This layer keeps everything in order, handling layout, alignment, and scaling for all other layers.</li></ol><p>By separating these roles into different layers, PDF.js stays organized and easy to update when you need to adjust or add features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*FjtWEMCngvyBOl_V.png" /></figure><p>Let’s start by creating a fresh React project to integrate PDF.js.</p><h3>Step 1: Set up React.js Project</h3><p>In this article, I use Codepen as a code editor. If you want to follow along, feel free to follow along the steps below.</p><ol><li>Create a new Pen on CodePen.</li><li>Click the Settings button (top-right corner of the editor).</li><li>In the Pen Settings dialog:</li></ol><ul><li>Go to the JavaScript tab.</li><li>Set the JavaScript Preprocessor to ‘Babel’.</li><li>Under ‘Add External Scripts / Pens’, search for and add: react &amp; react-dom</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*lyqtIMgRVz8g-zMz.png" /></figure><p>4. Click <strong>Save &amp; Close</strong>.</p><p>5. Now you can write React code using JSX in the JavaScript editor like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*N0i52st408TqBNYh.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*lGqmqigKwRJ4igDU.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*p9MPsEFJqEXOJFHi.png" /></figure><h3>Step 2: Integrate PDF.js into a React project</h3><p>First, let’s configure your React project to use the pdfjs-dist library.</p><ul><li><strong>Open Pen Settings</strong>: Click on the Settings button at the top of your Pen.</li><li><strong>Go to JavaScript Tab</strong>: In the popup, switch to the JS tab.</li><li><strong>Add Packages</strong> In the Add Packages box, search for and add pdfjs-dist.</li><li><strong>Save and Close</strong>: Click the button to apply changes</li><li><strong>Update Import Statement</strong> CodePen might auto-generate an import that doesn’t work correctly. Replace it like so</li></ul><pre>// ❌ Wrong (auto-generated)<br>// import pdfjsDist from &quot;https://esm.sh/pdfjs-dist&quot;;<br>// ✅ Correct<br>  import * as PDFJS from &quot;https://esm.sh/pdfjs-dist&quot;;</pre><ul><li><strong>Add PDF.js Worker and Configure It</strong> You’ll need to explicitly import and configure the worker. Here’s the complete setup</li></ul><pre>import React from &quot;https://esm.sh/react&quot;;<br>import ReactDOM from &quot;https://esm.sh/react-dom/client&quot;;<br>import * as PDFJS from &quot;https://esm.sh/pdfjs-dist&quot;;<br>import * as PDFWorker from &quot;https://esm.sh/pdfjs-dist/build/pdf.worker.min&quot;;<br><br>try {<br>  PDFJS.GlobalWorkerOptions.workerSrc = PDFWorker;<br>} catch (e) {<br>  window.pdfjsWorker = PDFWorker;<br>}</pre><p><strong>Explanation</strong><br>Before loading the PDF, we need to configure the PDF worker. The worker is responsible for processing the PDF in a separate thread, improving performance.</p><p>That’s it! You’re now set up to start experimenting with PDF.js layers within a React environment. So let’s get to the layers.</p><h3>1. Canvas Layer</h3><h3>Purpose</h3><p>The <strong>Canvas Layer</strong> is the foundation — it’s where PDF.js draws the visual elements such as images, shapes, and text (as graphics). Essentially, what you see on-screen is coming from this layer.</p><h3>How It Works</h3><ul><li>PDF.js uses the HTML &lt;canvas&gt; element to display the PDF&#39;s visual content</li><li>It utilizes the browser’s <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">2D canvas API</a> for high-performance rendering.</li><li>This means your PDF content will look consistent and accurate across various screen sizes and devices.</li></ul><h3>Use Cases</h3><ul><li>Ideal for <strong>non-interactive</strong> or <strong>static</strong> PDF content.</li><li>It renders the document as an image, ensuring PDF’s fonts, colors, and layouts are consistent across all devices.</li></ul><h3>Example of Canvas Layer Code with React</h3><p>Here’s a quick CodePen demo showcasing a minimal Canvas Layer setup in React.js.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2F9haroon%2Fembed%2Fpreview%2FjEOppVz%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DjEOppVz&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2F9haroon%2Fpen%2FjEOppVz&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FjEOppVz-512.jpg%3Fversion%3D1746607132&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/29371d6a4fec2b49e700241dc71b240d/href">https://medium.com/media/29371d6a4fec2b49e700241dc71b240d/href</a></iframe><h3>📜 How the Code Works</h3><p>Below, I’ll walk through the major steps for rendering a PDF page onto the canvas.</p><h4>(1) Fetching and Loading the PDF</h4><pre>const PDF_SRC = &quot;https://pdfobject.com/pdf/pdf_open_parameters_acro8.pdf&quot;<br>...<br>React.useEffect(() =&gt; {<br>  processLoadingTask(PDF_SRC)<br>}, [])<br>function processLoadingTask(source) {<br>    const loadingTask = PDFJS.getDocument(source);<br>    loadingTask.promise<br>     .then((docProxy) =&gt; { ... })<br>     .then((page) =&gt; {<br>        ...<br>        canvasLayer.current.width = width;<br>        canvasLayer.current.height = height;<br>        const context = canvasLayer.current.getContext(&quot;2d&quot;);<br>        const renderContext = {<br>            canvasContext: context,<br>            viewport: viewport<br>        };<br>        return page.render(renderContext);<br>     })<br> }</pre><p><strong>Explanation</strong>:</p><ul><li>The processLoadingTask method starts the PDF loading process using PDFJS.getDocument(source) from pdfjs-dist.</li><li>Once the PDF is loaded from PDF_SRC, we obtain a docProxy—a PDF document instance that contains all pages of the PDF.</li><li>In this example, only the <strong>first page</strong> is used for rendering.</li><li>The total number of pages is retrieved from docProxy.numPages and stored in the totalPages state.</li></ul><h4>(2) Rendering the Canvas Layer</h4><pre>...<br> const canvasLayer = React.useRef()<br> const [pdfDimension, setPdfDimension] = React.useState({<br>   width: 0,<br>   height: 0<br> });<br> ...<br> return ( <br>     ...<br>      &lt;div<br>        class=&quot;pdf__canvas-layer&quot;<br>        style={{<br>         height: `${pdfDimension.height}px`,<br>         width: `${pdfDimension.width}px`,<br>         border: &#39;1px solid #dfdfdf&#39;,<br>         margin: &#39;0 auto&#39;<br>        }}<br>      &gt;<br>       &lt;canvas ref={canvasLayer} /&gt;<br>      &lt;/div&gt;<br>     ... <br> )</pre><p><strong>Explanation</strong></p><p>After the PDF is loaded and we have the first page object then:</p><ul><li>Scales the canvas to match the PDF page dimensions by updating pdfDimension.</li><li>A &lt;canvas&gt; element (canvasLayer) is used to render the PDF page as an image.</li><li>The rendering process is handled by page.render(renderContext), where canvasContext paints the page content onto the canvas.</li></ul><p>This ensures the final output accurately matches the original PDF’s appearance.</p><h3>2. Text Layer</h3><h3>Purpose</h3><p>The <strong>Text Layer</strong> ensures that the text in your PDF is <strong>selectable, searchable, and accessible</strong>. While the Canvas Layer does the heavy lifting of rendering visuals, the Text Layer is what lets you highlight and copy actual text.</p><h3>How It Works</h3><ul><li>PDF.js extracts the <strong>text content</strong> separately from the PDF.</li><li>It positions each piece of text exactly over the underlying canvas, using absolutely positioned &lt;div&gt; elements.</li><li>Even though you might not see these text &lt;div&gt; visually (they’re often transparent), they’re there to support <strong>selection</strong> and <strong>searching</strong>.</li></ul><h3>Use Cases</h3><ul><li>Enable <strong>text selection</strong> and <strong>copying</strong> from the PDF.</li><li>Text layer is crucial for <strong>accessibility</strong>, as it enables screen readers to interpret the content.</li><li>Provide text searching and highlighting within the PDF viewer.</li><li>Keep the text aligned with the rendered PDF page</li></ul><h3>Text layer Code Example</h3><p>Here’s a React.js CodePen example that demonstrates a Text Layer in action:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2F9haroon%2Fembed%2Fpreview%2FNPPyMQm%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DNPPyMQm&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2F9haroon%2Fpen%2FNPPyMQm&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FNPPyMQm-512.jpg%3Fversion%3D1746156403&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/82f6e7649b90f3882a8deaab340c0e61/href">https://medium.com/media/82f6e7649b90f3882a8deaab340c0e61/href</a></iframe><p><em>With this text layer, you can use your mouse to select text directly on the PDF.</em></p><h3>📜 How the Code Works</h3><h4>(1) Fetching and Loading the PDF</h4><p>Identical to the steps in the <strong>Canvas Layer</strong> — we load the PDF document first.</p><h4>(2) Structuring the Layers</h4><pre>return (<br>  ...<br>  &lt;div class=&quot;pdf-layers&quot; style={{ ... }} &gt;<br>    &lt;div class=&quot;pdf-layer__canvas&quot;&gt;<br>       &lt;canvas ref={canvasLayer} /&gt;<br>    &lt;/div&gt;<br>    &lt;div ref={textLayer} class=&quot;pdf-layer__text&quot; /&gt;<br>  &lt;/div&gt;<br>)</pre><p><strong>Explanation:</strong></p><ul><li>The pdf-layers is a container that holds both the <strong>Canvas Layer</strong> and the <strong>Text Layer</strong>.</li><li>The <strong>Canvas Layer</strong> (canvasLayer) displays the PDF page visually.</li><li>The <strong>Text Layer</strong> (textLayer) is styled to sit on top of the canvas, enabling text selection.</li></ul><h4>(3) Rendering the Text Layer</h4><pre>function renderTextLayer(page) {<br>   const viewport = page.getViewport({ scale: 1 });<br>   const { scale } = viewport;<br>   textLayer.current.style.setProperty(&quot;--total-scale-factor&quot;, `${scale}`);<br>    page.getTextContent().then((content) =&gt; {<br>      const renderTask = new PDFJS.TextLayer({<br>        container: textLayer.current,<br>        textContentSource: content,<br>        viewport: viewport.clone({ dontFlip: true })<br>      });<br>      return renderTask.render();<br>    });<br>  }</pre><p><strong>Explanation:</strong></p><ul><li>Render the text layer with renderTextLayer(page) function.</li><li>page.getTextContent() retrieves the text data from the PDF page.</li><li>This data is passed into a new PDFJS.TextLayer, specifying:<br> — container: The DOM element where the text will be rendered.<br> — textContentSource: Extracted text data from the PDF page.<br> — viewport: Define text positioning and scaling.</li><li>renderTask.render() overlays invisible but selectable text &lt;div&gt; over the canvas.</li><li>Check the CSS panel in CodePen to understand how the canvas and text layers are stacked together.</li></ul><h3>3. Annotation Layer</h3><h3>Purpose</h3><p>The <strong>Annotation Layer</strong> handles <strong>interactive elements</strong> like hyperlinks, highlights, form fields, and comments. If you need your PDF viewer to support internal linking (jumping to different pages), or if your PDFs have fillable forms, this layer is for you.</p><h3>How It Works</h3><ul><li>PDF.js extracts annotation data (links, form fields, etc.) from the PDF.</li><li>It overlays these data as <strong>interactive HTML elements</strong> (e.g. &lt;a&gt;, &lt;input&gt;, &lt;textarea&gt;), which sit above the <strong>Canvas Layer</strong> and <strong>Text Layer</strong> positioned using CSS.</li><li>This layer ensures that users can click, type, and interact without altering the PDF’s static visuals.</li></ul><h3>Use Cases</h3><ul><li>Clicking on links within PDF to navigate between pages.</li><li>Rendering highlights, underlines, and notes from PDF annotations.</li><li>Displaying interactive form fields within a PDF.</li></ul><h3>Annotation layer Code Example</h3><p>Check out this CodePen example on the <strong>Annotation Layer</strong> for React.js:</p><p><em>You can click the links inside the Codepen to change the PDF’s page.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2F9haroon%2Fembed%2Fpreview%2FoggEyma%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DoggEyma&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2F9haroon%2Fpen%2FoggEyma&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FoggEyma-512.jpg%3Fversion%3D1746161255&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/6aea9a045d62fdd89d964d656eef57ba/href">https://medium.com/media/6aea9a045d62fdd89d964d656eef57ba/href</a></iframe><h3>📜 How the Code Works</h3><h4>(1) Fetching and Loading the PDF</h4><p>Again, the same initial PDF loading steps as before.</p><h4>(2) Structuring the Layers</h4><pre>return (<br>  ...<br>  &lt;div class=&quot;pdf-layers&quot; style={{ ... }} &gt;<br>    &lt;div class=&quot;pdf-layer__canvas&quot;&gt;<br>       &lt;canvas ref={canvasLayer} /&gt;<br>    &lt;/div&gt;<br>    &lt;div ref={textLayer} class=&quot;pdf-layer__text&quot; /&gt;<br>    &lt;div ref={annotationLayer} class=&quot;pdf-layer__annotation&quot; /&gt;<br>  &lt;/div&gt;<br>)</pre><p><strong>Explanation:</strong></p><ul><li>We add another &lt;div&gt; for the <strong>Annotation Layer</strong> within pdf-layers.</li><li>The <strong>Annotation Layer</strong> is positioned on top of the <strong>Canvas Layer</strong> and <strong>Text Layer</strong>.</li></ul><h4>(3) Rendering the Annotation Layer</h4><pre>....<br> const annotationLayer = React.useRef();<br> ...<br> function getAnnotationsAsync(page) {<br>    return page.getAnnotations({ intent: &quot;display&quot; });<br> }<br> function renderAnnotationLayer(page) {<br>    const viewport = page.getViewport({ scale: 1 });<br>    annotationLayer.current.replaceChildren();<br>    getAnnotationsAsync(page).then((annotations) =&gt; {<br>      annotations.current = annotations;<br>      const pdfAnnotationLayer = new PDFJS.AnnotationLayer({<br>        div: annotationLayer.current,<br>        ...<br>      });<br>      return pdfAnnotationLayer.render({<br>        ...<br>        annotations,<br>        ...<br>      });<br>    });<br> }</pre><p><strong>Explanation:</strong></p><ul><li>getAnnotationsAsync() retrieves all annotation data from the PDF page—such as links, form fields, and highlights.</li><li>The viewport is cloned using viewport.clone({ dontFlip: true }) to ensure correct positioning and scaling for the annotation layer.</li><li>renderAnnotationLayer(page) handles rendering by:</li><li>Clearing or replacing any existing annotation elements inside the annotationLayer.current.</li><li>Creating a new PDFJS.AnnotationLayer instance to manage rendering.</li><li>Calling pdfAnnotationLayer.render({ ... }) with: The annotations retrieved from the page, the cloned viewport, the container where annotations should appear, and so on.</li></ul><p>This ensures that annotations are accurately rendered on top of the PDF page.</p><h4>(4) Handling Internal Link Clicks</h4><pre>...<br>const annotationEventAbortCtrl = React.useRef();<br>...<br>function bindAnnotationLayerEvent(page) {<br>    if (annotationEventAbortCtrl.current) {<br>      // Already binded<br>      return;<br>    }<br>    annotationEventAbortCtrl.current = new AbortController();<br>    const { signal } = annotationEventAbortCtrl.current;<br>    annotationLayer.current.addEventListener(<br>      &quot;click&quot;,<br>      async (event) =&gt; {<br>        let annotationTarget = event.target.parentNode;<br>        if (!annotationTarget) {<br>          return;<br>        }<br>        const id = annotationTarget.dataset.annotationId;<br>        if (!id) {<br>          return;<br>        }<br>        const annotationLinkId = (await getAnnotationsAsync(page)).find(<br>          (ele) =&gt; ele.id === id<br>        );<br>        if (!annotationLinkId) {<br>          return;<br>        }<br>        const pageIndex = await pdfDocProxy.current.getPageIndex(<br>          annotationLinkId.dest[0]<br>        );<br>        setCurrentPage(pageIndex + 1);<br>      },<br>      { signal }<br>    );<br>  }</pre><p><strong>Explanation:</strong></p><ul><li>This function listens for clicks on internal links (annotations) in the PDF.</li><li>When a user clicks a link, it checks if the clicked target has an associated annotationId.</li><li>If found, it looks up the annotation to get its destination using getAnnotationsAsync(page).</li><li>Then it uses getPageIndex() to find which page the link points to.</li><li>Finally, it updates the current page with setCurrentPage() to navigate to the target page.</li></ul><h4>(5) Handling Page Navigation</h4><p>A simple navigation bar lets users switch between pages.</p><pre>...<br>const [currentPage, setCurrentPage] = React.useState(3);<br>const [totalPages, setTotalPages] = React.useState(0);<br>...<br>React.useEffect(() =&gt; {<br>  processRenderPdfLayers(PDF_SRC);<br>}, [currentPage]);<br>...<br>return (<br> &lt;div class=&quot;page-navigation&quot;&gt;<br>    &lt;button<br>       disabled={currentPage &lt;= 1}<br>       onClick={() =&gt; setCurrentPage(currentPage - 1)}<br>    &gt;<br>     &amp;larr;<br>    &lt;/button&gt;<br>    &lt;span&gt;<br>     {currentPage} / {totalPages}<br>    &lt;/span&gt;<br>    &lt;button<br>        disabled={currentPage &gt;= totalPages}<br>        onClick={() =&gt; setCurrentPage(currentPage + 1)}<br>    &gt;<br>     &amp;rarr;<br>    &lt;/button&gt;<br>  &lt;/div&gt;<br>)</pre><p><strong>Explanation:</strong></p><ul><li>The currentPage value updates when navigation buttons are clicked.</li><li>The useEffect with currentPage dependency ensures that all layers are re-rendered when the page changes.</li><li>This ensures all layers — Canvas, Text, and Annotation — stay in sync.</li></ul><h3>4. Structural Layer</h3><h3>Purpose</h3><p>Think of the <strong>Structural Layer</strong> as the master layout manager. It keeps the Canvas, Text, and Annotation layers correctly aligned, scaled, and positioned when users zoom in or out, or when the window is resized.</p><p>This layer is a must-have when creating a <strong>PDF viewer</strong> as it serves as the <strong>foundation</strong> that glues all other layers together.</p><h3>How It Works</h3><ul><li>The <strong>Structural Layer</strong> is typically implemented by a container element (&lt;div&gt;) that wraps all other layers.</li><li>Maintain consistent positioning among layers so they don’t drift apart during zooms or scrolls.</li><li>Act as the foundation that ties everything together, so your PDF viewer remains cohesive.</li></ul><h3>Use Cases</h3><ul><li>Ensure a <strong>consistent user experience</strong> across different screen sizes and resolutions.</li><li>Enable <strong>smooth zooming</strong> by scaling all layers proportionally.</li><li>Centralize navigation and layout logic (e.g. controlling how the viewer scrolls from one page to another.)</li></ul><p>In our code examples, the &lt;div ref=&quot;pdfLayersWrapper&quot; class=&quot;pdf__layers&quot;&gt; element serves as the Structural Layer, wrapping for other layers:</p><pre>&lt;div ref=&quot;pdfLayersWrapper&quot; class=&quot;pdf__layers&quot;&gt;<br>  &lt;div class=&quot;pdf__canvas-layer&quot;&gt;<br>    &lt;canvas ref=&quot;canvasLayer&quot; /&gt;<br>  &lt;/div&gt;<br>  &lt;div ref=&quot;textLayer&quot; class=&quot;pdf__text-layer&quot;&gt;&lt;/div&gt;<br>  &lt;div ref=&quot;annotationLayer&quot; class=&quot;pdf__annotation-layer&quot;&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><h3>Why is this important?</h3><ul><li>The <strong>Structural Layer</strong> wrapper ensures the Canvas, Text, and Annotation Layers all stay in sync, even when you zoom or flip through pages.</li><li>You can customize the wrapper to handle special behaviors like lazy-loading pages, scroll snapping and other performance optimizations.</li></ul><h3>How Layers Work Together</h3><p>Here’s how all four layers in PDF.js work together in harmony:</p><ol><li><strong>Rendering Process</strong>:<br>Each page is first drawn onto the <strong>Canvas Layer</strong> (visual content). Next, the <strong>Text Layer</strong> is layered on top to enable selection and searching. Finally, the <strong>Annotation Layer</strong> is placed at the very top, providing interactive elements like links and form fields.</li><li><strong>Interactivity</strong>:<br>The <strong>Annotation Layer</strong> handles user events (like clicking on links or typing into form fields), while the Text Layer ensures text can be highlighted, copied, or searched.</li><li><strong>PDF Viewer</strong>:<br>The <strong>Structural Layer</strong> wraps everything up, ensuring that zooming, resizing, and navigation across pages remain consistent. It keeps all layers aligned and responsive, so users get a polished viewing experience.</li></ol><h3>Beyond the Fundamentals</h3><p>PDF.js gives you the basics for working with PDFs in JavaScript, but plugging it into a React project means you’ll want more control.</p><ul><li><strong>Customize UI:</strong> Use React hooks and state to create a smooth, custom viewer that fits right into your app.</li><li><strong>Handling Large PDFs:</strong> For large PDFs, skip loading the whole file up front. Choose lazy loading or virtualization to keep your app feeling quick, even with hundreds of pages.</li><li><strong>Adding Toolbar Control:</strong> Build your own toolbar with features like zoom, page jumps, and download options, so users get a great experience.</li></ul><p>With the right setup, PDF.js and React work together to handle big files and let you shape the viewer to fit your project.</p><h3>Conclusion</h3><p>I’ve worked with PDF.js across many React.js projects, from straightforward file previews to detailed, interactive document tools. Its layered structure is always the foundation.</p><p>This setup matters because you get <strong>full control</strong> over each part of the PDF viewer. You can tune specific layers to <strong>boost performance</strong> or improve the user interface. It’s easy to <strong>refine how your viewer</strong> responds to things like search, form input, or user actions.</p><p>By understanding these layers, you will be able to optimize PDF.js implementations, customize features, and deliver a better user experience. Whether you’re building a simple React PDF Viewer or a complex Document Processing System, leveraging these layers effectively will set your project up for success.</p><h3>React PDF: The PDF Viewer Built for React.js Developers 🚀</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ugBq0iwq_Po5dSO1.png" /></figure><p>If you enjoyed this article, I’d love for you to check out <a href="https://www.react-pdf.dev/?utm_source=medium&amp;utm_medium=referral&amp;utm_content=layers-of-pdfjs-and-how-you-can-use-them-in-reactjs">React PDF</a>. It’s a PDF Viewer built from the ground up for React and Next.js applications. Whether you’re just starting out or already running a large-scale app, React PDF got you covered.</p><p>Designed with developers in mind, React PDF offers:</p><ul><li>Out-of-the-box features — Check out the <a href="https://docs.react-pdf.dev/introduction/getting-started?utm_source=medium&amp;utm_medium=referral&amp;utm_content=layers-of-pdfjs-and-how-you-can-use-them-in-reactjs"><strong>Getting Started</strong></a> guide</li><li>Customizable look and feel — Learn how to <a href="https://docs.react-pdf.dev/tutorial/customizing-toolbar?utm_source=medium&amp;utm_medium=referral&amp;utm_content=layers-of-pdfjs-and-how-you-can-use-them-in-reactjs"><strong>customize components</strong></a></li><li>Web Responsive layouts — See how the React PDF Viewer renders on <a href="https://docs.react-pdf.dev/usage-guide/mobile-view?utm_source=medium&amp;utm_medium=referral&amp;utm_content=layers-of-pdfjs-and-how-you-can-use-them-in-reactjs"><strong>mobile view</strong></a></li><li>Developer-friendly APIs — Explore the full <a href="https://docs.react-pdf.dev/hooks/overview?utm_source=medium&amp;utm_medium=referral&amp;utm_content=layers-of-pdfjs-and-how-you-can-use-them-in-reactjs"><strong>API documentation</strong></a> for more information</li></ul><p>Your support encourages me to keep building tools and publish content for the React community. Thank you for checking out React PDF in advance! 🙏</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e761d796c2f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/understanding-pdf-js-layers-and-how-to-use-them-in-react-js-6e761d796c2f">🔥 Understanding PDF.js Layers and How to Use them in React.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Launch a PDF Viewer in Nuxt Using @vue-pdf-viewer [Guide for 2025] ]]></title>
            <link>https://javascript.plainenglish.io/launch-a-pdf-viewer-in-nuxt-using-vue-pdf-viewer-guide-for-2025-54f0c3c8f6fc?source=rss-b001e6e0fc89------2</link>
            <guid isPermaLink="false">https://medium.com/p/54f0c3c8f6fc</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <dc:creator><![CDATA[Kittisak Ma]]></dc:creator>
            <pubDate>Wed, 07 May 2025 03:42:59 GMT</pubDate>
            <atom:updated>2025-10-20T04:11:04.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Mc6uqrlTiRmQcEslMhMP-g.jpeg" /></figure><p>PDF viewing is now a must-have for modern web apps, from online contracts to digital classrooms. If you’re building with Nuxt, you want tools that fit right in and work fast. That’s where <a href="https://www.npmjs.com/package/@vue-pdf-viewer/viewer">@vue-pdf-viewer</a> shines 🌟</p><p>@vue-pdf-viewer lets you open, zoom, and interact with PDFs right inside your Vue or Nuxt project. The setup is quick, with features like keyboard controls, responsive layouts, and even advanced document options ready to go. For developers and teams, it’s a straightforward, reliable way to add rich PDF support to any Nuxt-powered app.</p><p><em>Disclaimer: I work at Vue PDF Viewer.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*kB_fFCe-suLVmiXBT4ikQQ.gif" /></figure><h3>Why Choose @vue-pdf-viewer for Nuxt Applications</h3><p>If you want smooth PDF handling in your Nuxt project, you need a component that just works. Vue PDF Viewer stands out for its balance of powerful features and simple setup. You can add the library into almost any Nuxt page or component with minimal setup. It’s built for Nuxt and Vue, so you avoid heavy solutions or flaky workarounds.</p><h3>Key Features that Set @vue-pdf-viewer Apart</h3><p>Vue PDF Viewer offers everything most apps need right out of the box. Here’s what you get:</p><ul><li><strong>Smooth zoom and rotation:</strong> Users can view their PDFs up close, rotate pages, and not miss a detail.</li><li><strong>Keyboard navigation:</strong> Move through documents without leaving the keyboard.</li><li><strong>Responsive layouts:</strong> Fits devices big or small, so mobile users can scroll, zoom, and interact with ease.</li><li><strong>PDF layers support:</strong> Support for text, canvas and annotation layers.</li><li><strong>Search and text selection:</strong> Users find what they need fast, selecting and copying text directly from the PDF.</li><li><strong>Easy customization:</strong> Vue PDF Viewer’s toolbar or theme can be configured easily to fit your business needs.</li></ul><p>If you want the full list, check the official documentation’s <a href="https://docs.vue-pdf-viewer.dev/?utm_medium=referral&amp;utm_source=medium&amp;utm_content=launch-a-pdf-viewer-in-nuxt-using-@vue-pdf-viewer">Feature Overview</a>. You’ll see plenty of advanced options, but the defaults work for most projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*n2TLE25FmTSTDyeC.png" /></figure><h3>Comparing @vue-pdf-viewer to Other Popular Alternatives</h3><p>Several tools such as Apryse and Syncfusion compete in this space, but Vue PDF Viewer stands out for its simplicity and Vue-first design:</p><ul><li><strong>Vue-native</strong>: Compared to other PDF.js wrappers, Vue PDF Viewer is written entirely in Vue, which means fewer compatibility headaches.</li><li><strong>Lightweight footprint</strong>: It’s lighter than some heavyweight tools like Apryse or Syncfusion.</li><li><strong>Feature-rich yet accessible</strong>: While many open-source options lack advanced controls or built-in Nuxt support, Vue PDF Viewer gives you both out-of-the-box.</li></ul><h3>Where @vue-pdf-viewer Shines in Nuxt</h3><p>You’ll see it in action everywhere — from simple PDF previews to interactive AI-powered PDF tools and full-fledged document management systems. It’s a great fit for projects where:</p><p>✅ You need solid, bug-free PDF rendering.<br>✅ Custom UI or branding matters.<br>✅ Fast time-to-launch is key and the focus is on Vue or Nuxt development.</p><p>The component’s flexibility lets you scale from basic views to complex document tools without starting over each time.</p><h3>Setting Up Your Nuxt Project for PDF Viewing</h3><p>Getting your Nuxt project ready for PDF viewing starts with a solid foundation. You’ll want installation to be smooth and straightforward asset handling to ensure reliable PDF rendering and easy file maintenance.</p><h3>Install Dependencies and Project Scaffolding</h3><p>Start by creating a new Nuxt application, or open your existing one.</p><h4>Nuxt 3 (recommended):</h4><ol><li>Initialize your project:</li></ol><ul><li>Run npx nuxi init my-nuxt-app to create a basic structure.</li><li>Enter the project folder: cd my-nuxt-app.</li><li>Install dependencies: npm install.</li></ul><p>2. Add @vue-pdf-viewer:</p><ul><li>Install the package with npm install @vue-pdf-viewer</li></ul><p>Here’s a quick checklist before moving ahead:</p><ul><li>Vue 3</li><li>Node 16+ for Nuxt 3</li></ul><p>With your dependencies set, you’re ready to handle asset organization.</p><h3>Configure Static Assets for PDF Files</h3><p>How you store and serve your PDF files matters, especially when it comes to access speed and basic security. Nuxt 3 typically uses the public folder for this job, but there are a few gotchas to keep your files organized and safe.</p><p>In Nuxt 3, any files placed in the public folder are served from the root level. For example, a PDF saved as public/sample.pdf will be available at /sample.pdf in your browser.</p><h4>Best practices for asset management:</h4><ul><li>Organize your PDFs in subfolders (e.g. public/pdfs/) if you plan to store more than a few documents.</li><li>Keep clear, consistent filenames and avoid spaces, use dashes or underscores.</li><li>Regularly clean out unused files to keep your build lightweight.</li></ul><h4>File access security:</h4><p>Keep in mind that assets in public or static are publicly accessible. If you&#39;re dealing with sensitive or private PDFs, don&#39;t place them here. Instead:</p><ul><li>Use authentication and store the files outside public</li><li>Serve them through a secure API or custom middleware.</li></ul><h4>Useful Resources</h4><ul><li>For more on how Nuxt handles public and static files, review the <a href="https://nuxt.com/docs/getting-started/assets">official assets documentation</a>.</li><li>If you want a guide to help you decide where files belong or to understand asset handling differences, check out <a href="https://masteringnuxt.com/blog/handling-assets-in-nuxt-3">this breakdown on handling assets in Nuxt 3</a>.</li><li>For quick comparisons on when to use each folder, see the Stack Overflow thread on <a href="https://stackoverflow.com/questions/48808182/nuxt-assets-and-static-folder-when-to-use-which">Nuxt assets and static folders</a>.</li></ul><p>By planning where your PDFs live from the start, you avoid confusion later on — especially as your app grows. Keep things neat and protect anything sensitive, and your PDF workflow in Nuxt will stay smooth and manageable.</p><h3>Integrating @vue-pdf-viewer in a Nuxt Component</h3><p>With your Nuxt app set up and PDFs organized, the next step is to actually bring your PDF viewer to life. You have a few key choices here: create a self-contained component for on-demand use, wrap the viewer in client-only rendering to avoid SSR issues, or register it globally for reuse in bigger projects.</p><p>Here’s a step-by-step guide to each approach so you choose the one that fits your needs best.</p><p>📘 <strong>Related:</strong> You can also follow the official <a href="https://docs.vue-pdf-viewer.dev/introduction/basic-usage.html#nuxt?utm_source=medium&amp;utm_content=launch-a-pdf-viewer-in-nuxt-using-@vue-pdf-viewer&amp;utm_medium=referral">Nuxt setup guide</a> in the documentation for a simpler quick-start example</p><h3>Creating a Reusable PDF Viewer Component</h3><p>To start, it’s best to build a dedicated Vue component that handles all your PDF viewing logic. This keeps your code tidy and lets you drop the viewer anywhere in your app.</p><p>Here’s how you can do it:</p><ol><li>Create a new file in your components folder. e.g. PdfViewer.vue</li><li>Import @vue-pdf-viewer/viewer and define your props.</li><li>Pass in the src prop, which is the path to your PDF file.</li><li>Optionally, add viewer options to customize controls or appearance.</li></ol><p>Example code: components/PdfViewer.vue</p><pre>&lt;script setup&gt;<br>import { ref } from &#39;vue&#39;<br>import { VPdfViewer } from &#39;@vue-pdf-viewer/viewer&#39;const pdfSrc = ref(&#39;/pdfs/sample.pdf&#39;) // or use a prop for dynamic paths<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;VPdfViewer :src=&quot;pdfSrc&quot; /&gt;<br>&lt;/template&gt;</pre><p>This setup lets you easily update the source PDF or tweak viewer settings as needed. For more details about best practices with Vue components in Nuxt, check out the <a href="https://nuxt.com/docs/guide/directory-structure/components">Nuxt components directory guide</a>.</p><h3>Client-Side Only Rendering with `&lt;ClientOnly&gt;`</h3><p>Rendering PDF viewers on the server (SSR) can cause headaches since browser-specific APIs don’t exist during server-side rendering. Nuxt provides a simple fix with &lt;ClientOnly&gt; component in Nuxt 3.</p><h4>How to use it:</h4><p>In <strong>Nuxt 3</strong>, Wrap your PDF viewer like this:</p><pre>&lt;script setup&gt;<br>import PdfViewer from &#39;./components/PdfViewer.vue&#39;<br>&lt;/script&gt;<br><br>&lt;template&gt;<br> &lt;ClientOnly&gt;<br>  &lt;PdfViewer /&gt;<br> &lt;/ClientOnly&gt;<br>&lt;/template&gt;</pre><h4>What does this do?</h4><p>&lt;ClientOnly&gt; tells Nuxt to delay rendering of your PDF viewer component until it&#39;s running in the browser. This prevents SSR-related errors from happening when browser-only code is accessed too early.</p><p>If you need a deeper explanation or run into issues, check out <a href="https://stackoverflow.com/questions/72367724/client-only-nuxt-3-vue-plugin">this discussion on Nuxt client-only plugins</a>.</p><h3>Using Nuxt Plugins for Global Registration</h3><p>If your app needs to display PDFs in many places, it helps to register the viewer as a global component. Nuxt’s plugin system makes this smooth and keeps your code DRY (don’t repeat yourself).</p><p>Here’s the approach:</p><ol><li>Create a new plugin file in plugins/vue-pdf-viewer.js (or .ts).</li><li>Import and register @vue-pdf-viewer globally.</li><li>In your Nuxt config, make sure the plugin is loaded only on the client.</li></ol><p>Example for Nuxt 3:</p><pre>// plugins/vue-pdf-viewer.client.js<br>import { defineNuxtPlugin } from &#39;#app&#39;<br>import { VPdfViewer } from &#39;@vue-pdf-viewer/viewer&#39;<br><br>export default defineNuxtPlugin((nuxtApp) =&gt; {<br>  nuxtApp.vueApp.component(&#39;VPdfViewer&#39;, VPdfViewer)<br>})</pre><p>Nuxt automatically reads the files in the plugins/ directory and loads them at the creation of the Vue application. For full details, visit the <a href="https://nuxt.com/docs/guide/directory-structure/plugins">Nuxt plugins directory documentation</a>.</p><p>With the viewer globally registered, you can use &lt;VPdfViewer /&gt; anywhere in your project—no manual imports needed. This approach saves you from repetitive imports and keeps your codebase neat as your app scales.</p><h3>Bonus Section: Styling Your PDF Viewer</h3><p>Nobody wants a PDF viewer that looks out of place or breaks your app’s design flow. With a little effort, you can easily style @vue-pdf-viewer to match your branding.</p><p><strong>Tips for styling:</strong></p><ul><li><strong>Use CSS for visual tweaks:</strong> Adjust background colors, spacing, and toolbar icons by targeting the viewer’s CSS classes. For detailed steps and best practices, check out this resource on <a href="https://docs.vue-pdf-viewer.dev/tutorial/changing-viewer-appearance.html#changing-viewer-appearance?utm_medium=referral&amp;utm_source=medium&amp;utm_content=launch-a-pdf-viewer-in-nuxt-using-@vue-pdf-viewer">customizing CSS in PDF viewers</a>.</li><li><strong>Use Slots for custom controls:</strong> Vue’s slot system makes it easy to insert your own buttons or menus on the toolbar or sidebar.</li><li><strong>Hide or reorder UI parts:</strong> Vue PDF Viewer toolbar can be toggled or reorganized through props or CSS. Keep only what you need on the screen.</li></ul><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*xBTMJZFSGWjznVTz.png" /></figure><p>Launching a PDF viewer in Nuxt with <a href="https://www.vue-pdf-viewer.dev/?utm_source=medium&amp;utm_medium=referral&amp;utm_content=launch-a-pdf-viewer-in-nuxt-using-@vue-pdf-viewer">Vue PDF Viewer</a> is fast and hassle-free. You get powerful display options, modern controls, and responsive layouts — ready to go with just a few steps. The component’s flexibility means you can start simple or customize for a tailored user experience.</p><p>🙏 Thanks for reading — if you’ve tried this in your own Nuxt app, please feel to share what you built or what you want to see next in Vue PDF Viewer.</p><p>I’m looking forward to seeing what you build with Vue PDF Viewer 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*8xtKsxCdTixbXvdM.gif" /></figure><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54f0c3c8f6fc" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/launch-a-pdf-viewer-in-nuxt-using-vue-pdf-viewer-guide-for-2025-54f0c3c8f6fc">🚀 Launch a PDF Viewer in Nuxt Using @vue-pdf-viewer [Guide for 2025] 🔥</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are PDF.js Layers and How You Can Use them in Vue.js]]></title>
            <link>https://medium.com/@9haroon_dev/what-are-pdf-js-layers-and-how-you-can-use-them-in-vue-js-6fb6d33fcf37?source=rss-b001e6e0fc89------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fb6d33fcf37</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Kittisak Ma]]></dc:creator>
            <pubDate>Tue, 11 Mar 2025 08:32:29 GMT</pubDate>
            <atom:updated>2025-03-12T03:31:41.476Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*EJHCMOpwbRvDVGPSn7koQQ.jpeg" /></figure><p>PDF is everywhere, no matter what kind of web app you’re building, you’re bound to need a convenient PDF viewer at some point. But if you’ve ever tried to handle PDFs on the web, you know it can feel like wrestling with outdated plugins, iframe workaround or settling for awkward pop-ups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*4nsxcWSldAFU_Cr9.gif" /></figure><p>That’s where PDF.js comes in — it’s an open-source JavaScript library for rendering PDFs right in your browser. Now, if you’re like me and build apps in Vue.js, figuring out how to use PDF.js in your project can be tricky at first.</p><p>To leverage PDF.js’s capabilities, it’s important to understand its layered architecture. If you’ve ever wondered, “How do I enable text selection?” or “How do I handle links inside the PDF?” or even “How do I build advanced features like annotations?”, the answer usually lies in understanding these layers.</p><p>In this article, I’ll show you how PDF.js creates layers, what each layer is responsible for, and how you can apply them to your next Vue project. Let’s get going!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*Hc-rljxaSt53me4C.gif" /></figure><h3>Vue PDF Viewer: Flexible and Powerful Vue.js PDF Component</h3><p>Quick heads up on something I’ve been working on: <a href="https://www.vue-pdf-viewer.dev/?utm_source=medium&amp;utm_content=how-pdfjs-creates-layers-and-what-each-layer-is-for">Vue PDF Viewer</a>, a handy PDF Viewer that renders PDFs right within your Vue or Nuxt app. It packs over 20 features, including out-of-the-box default toolbar, customization and responsive design, so your users never have to leave your site to interact with your documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*8Bfpeo4mx9DdXyww.png" /></figure><p>If that sounds interesting, I’d love for you to give <a href="https://www.vue-pdf-viewer.dev/?utm_source=medium&amp;utm_content=how-pdfjs-creates-layers-and-what-each-layer-is-for">Vue PDF Viewer</a> a try. Your support helps me keep creating awesome tools and tutorials like this one. ❤️</p><h3>Overview of PDF.js Layers</h3><p>Before we dive in, here’s a quick snapshot of the four major layers in PDF.js. Each layer handles a specific aspect of rendering or user interaction:</p><ol><li><strong>Canvas Layer</strong>: Render the static visual content of your PDF (shapes, images, text-as-graphics). It is the foundation of the PDF Viewer.</li><li><strong>Text Layer</strong>: Sit on top of the canvas to ensure that text is selectable and searchable.</li><li><strong>Annotation Layer</strong>: Handle interactive elements (links, forms, highlights) so users can click, type, or navigate.</li><li><strong>Structural Layer</strong>: Manage the overall layout, including alignment and scaling for all the other layers.</li></ol><p>By splitting different functionalities into distinct layers, PDF.js remains modular, efficient, and surprisingly easy to tweak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*y8G1pLoWVm49yC8X.png" /></figure><p>Let’s start by creating a fresh Vue.js project to integrate PDF.js.</p><h3>Set up Vue.js Project</h3><p>In this article, I use Codepen as a code editor. If you want to follow along, you can create a new Pen on Codepen and follow the steps below.</p><h3>Step 1: Pick a Vue Pen Template</h3><p>The easiest way to get started is by using CodePen’s built-in Vue template. From the left menu, click on the Pen menu to open the options, then pick Vue Pen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*s364FRDj4JK6FooB.png" /></figure><p>This gives you a pre-configured environment with a default Vue setup. In this interface, you can experiment with Vue codes and instantly see your results in the preview area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*LhEFyTwXSeYtgIuM.png" /></figure><h3>Step 2: Configure the project and install PDF.js</h3><p>Next, let’s configure your Vue project to use the pdfjs-dist library.</p><ol><li><strong>Open Settings</strong>: Click on the Settings button at the top of your Pen.</li><li><strong>Select JS Options</strong>: In the popup, switch to the JS tab.</li><li><strong>Pick Vue Version</strong>: Under Vue version, select Vue 3 (or whichever version fits your needs).</li><li><strong>Add Packages</strong>: In the Add Packages box, search for and add pdfjs-dist.</li><li><strong>Save and Close</strong>: Click Save &amp; Close to apply your changes.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*KkE4sKejJZ-1IxTn.png" /></figure><p>CodePen will automatically inject an import statement for pdfjs-dist into your code. You’ll typically want to move that statement below your &lt;script&gt; section to keep things clean and organized.</p><p>That’s it! You’re now set up to start experimenting with PDF.js layers within a Vue environment. So let us get to the layers.</p><h3>1. Canvas Layer</h3><h3>Purpose</h3><p>The <strong>Canvas Layer</strong> is the foundation — it’s where PDF.js draws the visual elements such as images, shapes, and text (as graphics). Essentially, what you see on-screen is coming from this layer.</p><h3>How It Works</h3><ul><li>PDF.js uses the HTML &lt;canvas&gt; element to display the PDF&#39;s visual content</li><li>It utilizes the browser’s <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">2D canvas API</a> for high-performance rendering.</li><li>This means your PDF content will look consistent and accurate across various screen sizes and devices.</li></ul><h3>Use Cases</h3><ul><li>Ideal for <strong>non-interactive</strong> or <strong>static</strong> PDF content.</li><li>It renders the document as an image, ensuring PDF’s fonts, colors, and layouts are consistent across all devices.</li></ul><h3>Example of Canvas layer Code with Vue</h3><p>Here’s a quick CodePen demo showcasing a minimal Canvas Layer setup in Vue.js.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2F9haroon%2Fembed%2Fpreview%2FvEBVBqR%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DvEBVBqR&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2F9haroon%2Fpen%2FvEBVBqR&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FvEBVBqR-512.jpg%3Fversion%3D1739441006&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/18e1c6d93774728b5e98b94f0d08bab9/href">https://medium.com/media/18e1c6d93774728b5e98b94f0d08bab9/href</a></iframe><h3>📜 How the Code Works</h3><p>Below, I’ll walk through the major steps for rendering a PDF page onto the canvas.</p><h4>(1) Setting Up the PDF Worker</h4><p>Before loading the PDF, we need to configure the <strong>PDF worker</strong>. The worker is responsible for processing the PDF in a separate thread, improving performance.</p><pre>import * as PDFJS from &quot;https://esm.sh/pdfjs-dist&quot;;<br>import * as PDFWorker from &quot;https://esm.sh/pdfjs-dist/build/pdf.worker.min&quot;;<br><br>try {<br>  PDFJS.GlobalWorkerOptions.workerSrc = PDFWorker;<br>} catch (e) {<br>  window.pdfjsWorker = PDFWorker;<br>}</pre><p><strong>Explanation:</strong></p><ul><li>Here, we import pdf.worker.min.js and set it as the worker source.</li><li>The worker processes the PDF in a separate thread so our UI is not blocked.</li><li>If an error occurs, the worker is assigned to window.pdfjsWorker as a fallback</li></ul><h4>(2) Fetching and Loading the PDF</h4><pre>const PDF_SRC = &quot;https://pdfobject.com/pdf/pdf_open_parameters_acro8.pdf&quot;;<br>export default {<br> ...<br> methods: {<br>  processLoadingTask(source) {<br>    const loadingTask = PDFJS.getDocument(source);<br>    loadingTask.promise<br>    .then(docProxy =&gt; ...)<br>    .then(page =&gt; {<br>       ...<br>       const renderContext = {<br>         canvasContext: context,<br>         viewport: viewport<br>       };<br>       return page.render(renderContext);<br>    })<br>   }<br> },<br> // Start the process when the component is mounted<br> mounted() {<br>  this.processLoadingTask(PDF_SRC);<br> }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The processLoadingTask method initializes PDF loading via PDFJS.getDocument(source) from pdfjs-dist.</li><li>Once the PDF is fetched (from PDF_SRC), we store the document proxy (docProxy).</li><li>The total number of pages is determined and stored in totalPages.</li></ul><h4>(3) Rendering the Canvas Layer</h4><p><strong>Explanation:</strong><br>After the PDF is loaded and we have a page object, the first page is extracted using getPage(1). PDF.js then:</p><ul><li>Scales the canvas to match the PDF page dimensions.</li><li>A &lt;canvas&gt; element (canvasLayer) is used to render the PDF page as an image.</li><li>The rendering process is handled by page.render(renderContext), where canvasContext paints the page content onto the canvas.</li></ul><p>This ensures the final output accurately matches the original PDF’s appearance.</p><h3>2. Text Layer</h3><h3>Purpose</h3><p>The <strong>Text Layer</strong> ensures that the text in your PDF is <strong>selectable, searchable, and accessible</strong>. While the Canvas Layer does the heavy lifting of rendering visuals, the Text Layer is what lets you highlight and copy actual text.</p><h3>How It Works</h3><ul><li>PDF.js extracts the <strong>text content</strong> separately from the PDF.</li><li>It positions each piece of text exactly over the underlying canvas, using absolutely positioned &lt;div&gt; elements.</li><li>Even though you might not see these text &lt;div&gt; visually (they’re often transparent), they’re there to support <strong>selection</strong> and <strong>searching</strong>.</li></ul><h3>Use Cases</h3><ul><li>Enable <strong>text selection</strong> and <strong>copying</strong> from the PDF.</li><li>Text layer is crucial for <strong>accessibility</strong>, as it enables screen readers to interpret the content.</li><li>Provide text searching and highlighting within the PDF viewer.</li><li>Keep the text aligned with the rendered PDF page</li></ul><h3>Text layer Code Example</h3><p>Here’s a Vue.js CodePen example that demonstrates a Text Layer in action:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2F9haroon%2Fembed%2Fpreview%2FGgKbgmm%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DGgKbgmm&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2F9haroon%2Fpen%2FGgKbgmm&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FGgKbgmm-512.jpg%3Fversion%3D1739445334&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3179241c5087e355be6151a71beab34/href">https://medium.com/media/f3179241c5087e355be6151a71beab34/href</a></iframe><h3>📜 How the Code Works</h3><h4>(1) Structuring the Layers</h4><pre>&lt;div ref=&quot;pdfLayersWrapper&quot; class=&quot;pdf__layers&quot;&gt;<br>  &lt;div class=&quot;pdf__canvas-layer&quot;&gt;<br>    &lt;canvas ref=&quot;canvasLayer&quot; /&gt;<br>  &lt;/div&gt;<br>  &lt;div ref=&quot;textLayer&quot; class=&quot;pdf__text-layer&quot;&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><p><strong>Explanation:</strong></p><ul><li>The pdfLayersWrapper is a container that holds both the <strong>Canvas Layer</strong> and the <strong>Text Layer</strong>.</li><li>The <strong>Canvas Layer</strong> (canvasLayer) displays the PDF page visually.</li><li>The <strong>Text Layer</strong> (textLayer) sits on top of the canvas, allowing text selection.</li></ul><h4>(2) Fetching and Loading the PDF</h4><p>(Identical to the steps in the <strong>Canvas Layer</strong> — we load the PDF document first.)</p><h4>(3) Rendering the Text Layer</h4><pre>renderText(pdfPageProxy, textLayerContainer, viewport) {<br>  ...<br>  pdfPageProxy<br>    .getTextContent()<br>    .then((content) =&gt; {<br>      const renderTask = new PDFJS.TextLayer({<br>        container: textLayerContainer,<br>        textContentSource: content,<br>        viewport: viewport.clone({ dontFlip: true })<br>      });<br>      return renderTask.render();<br>    });<br> },<br> processLoadingTask (source) {<br>  ...<br>  this.renderText(...)<br> }</pre><p><strong>Explanation:</strong></p><ul><li>Render the text layer (this.renderText()).</li><li>pdfPageProxy.getTextContent() retrieves the text data from the PDF page.</li><li>This data is passed into a new TextLayer, specifying:</li><li>container: Container where text is rendered.</li><li>textContentSource: Extract text data from the PDF.</li><li>viewport: Define text positioning and scaling.</li><li>renderTask.render() places invisible but selectable text &lt;div&gt; over the canvas.</li></ul><h3>3. Annotation Layer</h3><h3>Purpose</h3><p>The <strong>Annotation Layer</strong> handles <strong>interactive elements</strong> like hyperlinks, highlights, form fields, and comments. If you need your PDF viewer to support internal linking (jumping to different pages), or if your PDFs have fillable forms, this layer is for you.</p><h3>How It Works</h3><ul><li>PDF.js extracts annotation data (links, form fields, etc.) from the PDF.</li><li>It overlays these data as <strong>interactive HTML elements</strong> (e.g. &lt;a&gt;, &lt;input&gt;, &lt;textarea&gt;), which sit above the <strong>Canvas Layer</strong> and <strong>Text Layer</strong> positioned using CSS.</li><li>This layer ensures that users can click, type, and interact without altering the PDF’s static visuals.</li></ul><h3>Use Cases</h3><ul><li>Clicking on links within PDF to navigate between pages.</li><li>Rendering highlights, underlines, and notes from PDF annotations.</li><li>Displaying interactive form fields within a PDF.</li></ul><h3>Annotation layer Code Example</h3><p>Check out this CodePen example on the <strong>Annotation Layer</strong> for Vue.js:</p><p><em>You can click the links inside the Codepen to change the PDF’s page.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2F9haroon%2Fembed%2Fpreview%2FqEWzOzz%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DqEWzOzz&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2F9haroon%2Fpen%2FqEWzOzz&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FqEWzOzz-512.jpg%3Fversion%3D1739504604&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/f044b03d83f9810ae2bbc3c203e3c373/href">https://medium.com/media/f044b03d83f9810ae2bbc3c203e3c373/href</a></iframe><h3>📜 How the Code Works</h3><h4>(1) Structuring the Layers</h4><pre>&lt;div ref=&quot;pdfLayersWrapper&quot; class=&quot;pdf__layers&quot;&gt;<br>  &lt;div class=&quot;pdf__canvas-layer&quot;&gt;<br>    &lt;canvas ref=&quot;canvasLayer&quot; /&gt;<br>  &lt;/div&gt;<br>  &lt;div ref=&quot;textLayer&quot; class=&quot;pdf__text-layer&quot;&gt;&lt;/div&gt;<br>  &lt;div ref=&quot;annotationLayer&quot; class=&quot;pdf__annotation-layer&quot;&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><p><strong>Explanation:</strong></p><ul><li>We add another &lt;div&gt; for the <strong>Annotation Layer</strong> within pdfLayersWrapper.</li><li>The <strong>Annotation Layer</strong> is positioned on top of the <strong>Canvas Layer</strong> and <strong>Text Layer</strong>.</li></ul><h4>(2) Fetching and Loading the PDF</h4><p>(Again, the same initial PDF loading steps as before.)</p><h4>(3) Rendering the Annotation Layer</h4><pre>async getAnnotations(pageProxy) {<br>  const annotations = await pageProxy.getAnnotations({ intent: &quot;display&quot; });<br>  return annotations;<br> },<br> async renderAnnotations(pdfPageProxy, annotationLayerContainer, viewport) {<br>   const annotations = await this.getAnnotations(pdfPageProxy);<br>   ...<br>   const annotationLayer = new PDFJS.AnnotationLayer({<br>    div: annotationLayerContainer,<br>    viewport: clonedViewport,<br>    page: pdfPageProxy<br>  });<br>  await annotationLayer.render({<br>    ...,<br>    annotations,<br>    linkService: new SimpleLinkService(),<br>    ...<br>  })<br> }</pre><p><strong>Explanation:</strong></p><ul><li>getAnnotations retrieves all annotation info from the PDF page (links, form fields, etc.).</li><li>We clone the viewport to match the page’s dimensions for correct positioning.</li><li>renderAnnotations is then called to replace existing elements in annotationLayerContainer before rendering new ones. It does so by:</li><li>Creating a new AnnotationLayer instance to manage and render annotation elements.</li><li>Displaying the annotation layer by annotationLayer.render({...}), passing in the annotations and SimpleLinkService() to handle internal PDF links.</li></ul><h4>(4) Handling Internal Link Clicks</h4><pre>...<br>annotationLayerContainer.addEventListener(&quot;click&quot;, async (event) =&gt; {<br>  ...<br>  const annotationLinkId = annotations.find((ele) =&gt; ele.id === id);<br>  ...<br>  const pageIndex = await this.pdfDocProxy.getPageIndex(<br>    annotationLinkId.dest[0]<br>  );<br>  this.currentPage = pageIndex + 1;<br>});</pre><p><strong>Explanation:</strong></p><ul><li>When a user <strong>clicks on a link</strong> inside the PDF, the event checks if it’s an annotation.</li><li>If it is, we look up the destination page by getPageIndex() and see if it points to a different page in the PDF.</li><li>We then navigate to that page by updating this.currentPage.</li></ul><h4>(5) Handling Page Navigation</h4><p>A simple navigation bar lets users switch between pages.</p><pre>&lt;div class=&quot;page-navigation&quot;&gt;<br>  &lt;button :disabled=&quot;currentPage &lt;= 1&quot; @click=&quot;--currentPage&quot;&gt;<br>   &amp;larr; <br>  &lt;/button&gt;<br>  &lt;span&gt;{{ currentPage }}/{{ totalPages }}&lt;/span&gt;<br>  &lt;button :disabled=&quot;currentPage &gt;= totalPages&quot; @click=&quot;++currentPage&quot;&gt;<br>   &amp;rarr;<br>  &lt;/button&gt;<br> &lt;/div&gt;</pre><p><strong>Explanation:</strong></p><ul><li>The currentPage value updates when navigation buttons are clicked.</li><li>watch: { currentPage(newValue) { ... } } ensures that all layers are re-rendered when the page changes.</li><li>This ensures all layers — <strong>Canvas</strong>, <strong>Text</strong>, and <strong>Annotation</strong> — stay in sync.</li></ul><h3>4. Structural Layer</h3><h3>Purpose</h3><p>Think of the <strong>Structural Layer</strong> as the master layout manager. It keeps the Canvas, Text, and Annotation layers correctly aligned, scaled, and positioned when users zoom in or out, or when the window is resized.</p><p>This layer is a must-have when creating a <strong>PDF viewer</strong> as it serves as the <strong>foundation</strong> that glues all other layers together.</p><h3>How It Works</h3><ul><li>The <strong>Structural Layer</strong> is typically implemented by a container element (&lt;div&gt;) that wraps all other layers.</li><li>Maintain consistent positioning among layers so they don’t drift apart during zooms or scrolls.</li><li>Act as the foundation that ties everything together, so your PDF viewer remains cohesive.</li></ul><h3>Use Cases</h3><ul><li>Ensure a <strong>consistent user experience</strong> across different screen sizes and resolutions.</li><li>Enable <strong>smooth zooming</strong> by scaling all layers proportionally.</li><li>Centralize navigation and layout logic (e.g. controlling how the viewer scrolls from one page to another.)</li></ul><p>In our code examples, the &lt;div ref=&quot;pdfLayersWrapper&quot; class=&quot;pdf__layers&quot;&gt; element serves as the Structural Layer, wrapping for other layers:</p><pre>&lt;div ref=&quot;pdfLayersWrapper&quot; class=&quot;pdf__layers&quot;&gt;<br>  &lt;div class=&quot;pdf__canvas-layer&quot;&gt;<br>    &lt;canvas ref=&quot;canvasLayer&quot; /&gt;<br>  &lt;/div&gt;<br>  &lt;div ref=&quot;textLayer&quot; class=&quot;pdf__text-layer&quot;&gt;&lt;/div&gt;<br>  &lt;div ref=&quot;annotationLayer&quot; class=&quot;pdf__annotation-layer&quot;&gt;&lt;/div&gt;<br>&lt;/div&gt;</pre><h3>Why is this important?</h3><ul><li>The <strong>Structural Layer</strong> wrapper ensures the Canvas, Text, and Annotation Layers all stay in sync, even when you zoom or flip through pages.</li><li>You can customize the wrapper to handle special behaviors like lazy-loading pages, scroll snapping and other performance optimizations.</li></ul><h3>How Layers Work Together</h3><p>Here’s how all four layers in PDF.js work together in harmony:</p><ol><li><strong>Rendering Process</strong>:<br>Each page is first drawn onto the <strong>Canvas Layer</strong> (visual content). Next, the <strong>Text Layer</strong> is layered on top to enable selection and searching. Finally, the <strong>Annotation Layer</strong> is placed at the very top, providing interactive elements like links and form fields.</li><li><strong>Interactivity</strong>:<br>The <strong>Annotation Layer</strong> handles user events (like clicking on links or typing into form fields), while the Text Layer ensures text can be highlighted, copied, or searched.</li><li><strong>PDF Viewer</strong>:<br>The <strong>Structural Layer</strong> wraps everything up, ensuring that zooming, resizing, and navigation across pages remain consistent. It keeps all layers aligned and responsive, so users get a polished viewing experience.</li></ol><h3>Conclusion</h3><p>I’ve used PDF.js in a variety of Vue.js projects, from simple PDF previews to fully interactive document systems, the layered architecture is always at the core.</p><p><strong>Why does this matter for you?</strong></p><ul><li>You can optimize each layer for performance or user experience.</li><li>You can customize how your viewer handles interactions, text searches, or forms.</li><li>You’ll find it much easier to maintain or extend your PDF viewer code.</li></ul><p>By understanding these layers, you will be able to optimize PDF.js implementations, customize features, and deliver a better user experience. Whether you’re building a simple Vue.js PDF viewer or a complex document management system, leveraging these layers effectively will set your project up for success.</p><h3>Vue PDF Viewer: The PDF Viewer Built for Vue.js Developers 🚀</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*q5mRjR_gU_SJdFN8.png" /></figure><p>If you enjoyed this article, I’d love for you to check out <a href="https://www.vue-pdf-viewer.dev/?utm_source=medium&amp;utm_content=how-pdfjs-creates-layers-and-what-each-layer-is-for">Vue PDF Viewer</a>. It’s a PDF Viewer built from the ground up for Vue and Nuxt applications. Whether you’re just starting out or already running a large-scale app, Vue PDF Viewer got you covered.</p><p>Designed with developers in mind, Vue PDF Viewer offers:</p><ul><li>Simple Vue integration to get you up and running fast.</li><li>Advanced customization so you can nail that perfect look and feel.</li><li>Responsive layouts that adapt to any device.</li><li>Developer-friendly APIs for more flexibility.</li></ul><p>Your support motivates me to keep creating tools and content for the Vue community. Thank you for checking out <a href="https://www.vue-pdf-viewer.dev/?utm_source=medium&amp;utm_content=how-pdfjs-creates-layers-and-what-each-layer-is-for">Vue PDF Viewer</a>. Happy coding! 🙏</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*-AkyXffCTgsSBH9N.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fb6d33fcf37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best 4 Methods to Build a PDF Viewer in React.js: PDF.js, react-pdf, and More (2024 Guide) ]]></title>
            <link>https://medium.com/@9haroon_dev/best-4-methods-to-build-a-pdf-viewer-in-react-js-pdf-js-react-pdf-and-more-2024-guide-6f5f658d30cf?source=rss-b001e6e0fc89------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f5f658d30cf</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kittisak Ma]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 11:02:11 GMT</pubDate>
            <atom:updated>2025-07-21T04:02:12.641Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*O5WTwBVmKikSHv2-I_59RQ.jpeg" /></figure><p>When working on React projects, one thing I’ve learned is that having the right tools can make or break the user experience. And when it comes to displaying documents, PDFs are still one of the best ways to share content, whether it’s reports, manuals, or e-books. The challenge, though, is how to integrate a reliable PDF viewer into your app without jumping through hoops.</p><p>In this article, I’ll walk you through four different ways to build a PDF viewer in React.js. From quick and simple methods like iFrame and opening PDFs in a new tab, to more customizable options like PDF.js and react-pdf — you’ll be able to choose the approach that works best for your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*jVe0WHkDS25EXgCp.gif" /></figure><h3>Why PDFs Matter in Web Development</h3><p>Rendering PDFs on websites comes with a wide range of use cases. Here are some scenarios where PDFs can really come in handy:</p><ol><li><strong>Financial Reports</strong><br>Imagine you’re building a finance dashboard, and your users need to access quarterly reports or balance sheets. By embedding these documents as PDFs, users can easily download, print, or view them in high resolution on any device. Plus, you keep the formatting consistent and professional, making sure nothing looks out of place.</li><li><strong>Sales Invoices</strong><br>For apps that generate or display invoices, PDFs are the perfect format to ensure clarity and accuracy. You can provide users with downloadable, printable invoices that maintain the exact layout and branding you’ve designed. No more worrying about documents being altered or misinterpreted.</li><li><strong>Research Papers</strong><br>If you’re working on a platform that handles academic content or research, PDFs are a great way to present papers, journal articles, and white papers. Researchers can zoom in for detail, highlight key points, or leave annotations — all while preserving the document’s original format.</li><li><strong>Legal Contracts</strong><br>For businesses dealing with contracts, confidentiality agreements, or any legal documents, PDFs are essential for maintaining integrity and security. PDFs ensure that legal contracts remain tamper-proof, preserving the original formatting and allowing for secure digital signatures. This is crucial when handling sensitive agreements, ensuring they can be easily shared, viewed, and stored by all parties involved without the risk of edits.</li></ol><h3>React PDF: A Flexible and Powerful PDF Viewer for React.js</h3><p>Before diving into the technical side of things, let me introduce you to <a href="https://www.react-pdf.dev/?utm_source=medium&amp;utm_medium=referral&amp;utm_content=best-4-methods-to-build-a-pdf-viewer-in-react-js-2024">React PDF</a> — a library I’ve been working on that brings PDF viewing directly into your React or Next.js applications. With over 20 features including theme customization, external APIs, and responsive layouts, it’s perfect for ensuring your users can interact with PDFs without leaving your site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GDcSASE5N3NabRZeakIGiw.jpeg" /></figure><p>If you’re interested in trying it out, I’d be super grateful if you could check out <a href="https://www.react-pdf.dev/?utm_source=medium&amp;utm_medium=referral&amp;utm_content=best-4-methods-to-build-a-pdf-viewer-in-react-js-2024">React PDF</a>. Your support will motivate me to keep creating more content! ❤️‍🔥</p><h3>Method 1: Open PDF in a New Tab</h3><p>If you’re working in React and need a simple way to open PDFs, Method 1 is your go-to solution: opening the PDF in a new browser tab. Let’s break it down:</p><h3>1. Add a Link or Button</h3><p>In your React component, create a link or button to open the PDF.</p><pre>&lt;a href=&quot;/your-pdf.pdf&quot; id=&quot;pdfLink&quot; target=&quot;_blank&quot;&gt;Open PDF&lt;/a&gt;<br>&lt;!-- or button --&gt;<br>&lt;button id=&quot;pdf-button&quot;&gt;Open PDF&lt;/button&gt;</pre><h3>2. Trigger the PDF</h3><p>Add an onclick event to open the PDF in a new tab.</p><pre>const pdfUrl = &#39;/your-pdf-url-goes-here.pdf&#39;;<br>document.getElementById(&#39;pdf-button&#39;).onclick = function() {<br>    window.open(pdfUrl, &#39;_blank&#39;);<br>};</pre><h3>Pros and Cons</h3><h4>Pros:</h4><ul><li><strong>Easy to Implement</strong>: This method is quick and simple.</li><li><strong>Direct Access</strong>: Users can view the PDF without anything in between.</li></ul><h4>Cons:</h4><ul><li><strong>Limited Control</strong>: You can’t fully control how the PDF is displayed.</li><li><strong>Browser Differences</strong>: The way it behaves can vary between browsers.</li></ul><h3>When to Use It</h3><p>Use this method when you want to keep the PDF viewer separate from your main website. For instance, if embedding it in an iframe isn’t ideal.</p><h3>Method 2: Using an iFrame, Embed, or Object</h3><p>A simple way to display PDFs in React is by using an &lt;iframe&gt;, &lt;embed&gt;, or &lt;object&gt; element. These methods leverage the browser’s built-in PDF capabilities, allowing you to embed the PDF directly into your app.</p><h3>How to Implement:</h3><ol><li>Create your React project.</li><li>Add one of these elements (&lt;iframe&gt;, &lt;embed&gt;, or &lt;object&gt;) in your JSX.</li><li>Set the src attribute to the PDF file’s URL.</li></ol><h4>&lt;iframe&gt; example:</h4><pre>&lt;iframe src=&quot;/your-pdf-url.pdf&quot; width=&quot;100%&quot; height=&quot;600px&quot;&gt;&lt;/iframe&gt;</pre><h4>&lt;embed&gt; example:</h4><pre>&lt;embed src=&quot;/your-pdf-url.pdf&quot; width=&quot;100%&quot; height=&quot;600px&quot; type=&quot;application/pdf&quot; /&gt;</pre><h4>&lt;object&gt; example:</h4><pre>&lt;object data=&quot;/your-pdf-url.pdf&quot; width=&quot;100%&quot; height=&quot;600px&quot; type=&quot;application/pdf&quot;&gt;<br>  &lt;p&gt;Your browser doesn’t support PDFs. Please download the PDF to view it: &lt;a href=&quot;/your-pdf-url.pdf&quot;&gt;Download PDF&lt;/a&gt;.&lt;/p&gt;<br>&lt;/object&gt;</pre><p>You can see a React code in my <a href="https://github.com/9haroon/pdf-embed-react-examples/tree/main/src/components">Github</a> repository</p><h3>Pros:</h3><ul><li><strong>Super Easy</strong>: It’s quick and simple to implement.</li><li><strong>Uses Browser’s PDF Viewer</strong>: No extra libraries required — just use the browser’s native PDF viewer.</li><li><strong>No Setup Needed</strong>: Works right away without additional configuration.</li></ul><h3>Cons:</h3><ul><li><strong>Limited Control</strong>: You can’t control the PDF viewer’s interface or customize it.</li><li><strong>Browser Compatibility</strong>: Not all browsers handle these methods the same way.</li><li><strong>Customization Limits</strong>: These options don’t offer much flexibility for customizing the viewing experience.</li></ul><h3>When to Use It:</h3><p>Use these methods when you want a fast, straightforward solution and don’t need to customize the PDF viewer.</p><h3>Method 3: Using PDF.js</h3><p>If you need more control over how PDFs are displayed and interacted with, PDF.js is a great option. Created by Mozilla, PDF.js lets you fully customize the PDF viewing experience within your app.</p><h3>How to Implement:</h3><ol><li>Install the PDF.js library in React project.</li></ol><pre>npm install pdfjs-dist</pre><p>2. Create a React component to render the PDF using PDF.js.</p><pre>import { PdfProps } from &quot;../types&quot;;<br>import * as PDFJS from &quot;pdfjs-dist&quot;;<br>import type {<br>  PDFDocumentProxy,<br>  RenderParameters,<br>} from &quot;pdfjs-dist/types/src/display/api&quot;;<br>import { useCallback, useRef, useState, useEffect } from &quot;react&quot;;<br><br>export default function PdfJs(props: PdfProps) {<br>  PDFJS.GlobalWorkerOptions.workerSrc =<br>    &quot;https://unpkg.com/pdfjs-dist@4.7.76/build/pdf.worker.min.mjs&quot;;<br>  const { src } = props;<br>  const canvasRef = useRef&lt;HTMLCanvasElement&gt;(null);<br>  const [pdfDoc, setPdfDoc] = useState&lt;PDFDocumentProxy&gt;();<br>  const [currentPage, setCurrentPage] = useState(1);<br>  let renderTask: PDFJS.RenderTask;<br>  const renderPage = useCallback(<br>    (pageNum: number, pdf = pdfDoc) =&gt; {<br>      const canvas = canvasRef.current;<br>      if (!canvas || !pdf) return;<br>      canvas.height = 0;<br>      canvas.width = 0;<br>      // canvas.hidden = true;<br>      pdf<br>        .getPage(pageNum)<br>        .then((page) =&gt; {<br>          const viewport = page.getViewport({ scale: 1.5 });<br>          canvas.height = viewport.height;<br>          canvas.width = viewport.width;<br>          const renderContext: RenderParameters = {<br>            canvasContext: canvas.getContext(&quot;2d&quot;)!,<br>            viewport: viewport,<br>          };<br>          try {<br>            if (renderTask) {<br>              renderTask.cancel();<br>            }<br>            renderTask = page.render(renderContext);<br>            return renderTask.promise;<br>          } catch (error) {}<br>        })<br>        .catch((error) =&gt; console.log(error));<br>    },<br>    [pdfDoc]<br>  );<br>  useEffect(() =&gt; {<br>    renderPage(currentPage, pdfDoc);<br>  }, [pdfDoc, currentPage, renderPage]);<br>  useEffect(() =&gt; {<br>    const loadingTask = PDFJS.getDocument(src);<br>    loadingTask.promise.then(<br>      (loadedDoc) =&gt; {<br>        setPdfDoc(loadedDoc);<br>      },<br>      (error) =&gt; {<br>        console.error(error);<br>      }<br>    );<br>  }, [src]);<br>  const nextPage = () =&gt;<br>    pdfDoc &amp;&amp; currentPage &lt; pdfDoc.numPages &amp;&amp; setCurrentPage(currentPage + 1);<br>  const prevPage = () =&gt; currentPage &gt; 1 &amp;&amp; setCurrentPage(currentPage - 1);<br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={prevPage} disabled={currentPage &lt;= 1}&gt;<br>        Previous<br>      &lt;/button&gt;<br>      &lt;button<br>        onClick={nextPage}<br>        disabled={currentPage &gt;= (pdfDoc?.numPages ?? -1)}<br>      &gt;<br>        Next<br>      &lt;/button&gt;<br>      &lt;canvas ref={canvasRef}&gt;&lt;/canvas&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>You can find a complete example code on my <a href="https://github.com/9haroon/pdf-embed-react-examples/blob/main/src/components/PdfJs.tsx">Github</a>: components/PdfJs.tsx.</p><p>Here is the result 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*YrsMh_3seQncSGyX.gif" /></figure><h3>Pros:</h3><ul><li><strong>Advanced Features</strong>: PDF.js provides powerful PDF rendering with options like zoom, page navigation, and more.</li><li><strong>Highly Customizable</strong>: You have full control over how the PDF is displayed and interacted with.</li><li><strong>Cross-Browser Support</strong>: Works across most modern browsers.</li><li><strong>Well-Maintained</strong>: Backed by a big community with regular updates.</li></ul><h3>Cons:</h3><ul><li><strong>Learning Curve</strong>: It takes time to learn and implement.</li><li><strong>More Complex</strong>: Setting it up is harder compared to using iFrame or opening PDFs in a new tab.</li><li><strong>Documentation Challenges</strong>: The docs can be tough to follow.</li><li><strong>Integration Issues</strong>: Customizing it for frameworks like React, Angular, or Vue can be tricky.</li><li><strong>Higher Complexity</strong>: Handling advanced interactions with PDFs increases the complexity.</li></ul><h3>When to Use It:</h3><p>Use PDF.js when you need full control over the PDF viewer and want to add advanced features directly into your app’s interface.</p><h3>Method 4: Using react-pdf (MIT)</h3><p><strong>react-pdf</strong> is an open-source package built on top of PDF.js that makes it easier to display PDFs in React apps while simplifying the development process.</p><h3>How to Implement:</h3><ul><li>Install react-pdf using npm or yarn.</li></ul><pre>npm install react-pdf</pre><ul><li>Import the react-pdf component into your app, and configure its worker</li></ul><pre>import { pdfjs } from &quot;react-pdf&quot;;<br><br>pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;</pre><ul><li>Follow the instructions on <a href="https://github.com/wojtekmaj/react-pdf">GitHub</a> for detailed setup.</li><li>Create a React component to render PDF</li></ul><pre>export default function PdfReactPdf({ src }: PdfProps) {<br>  const [numPages, setNumPages] = useState&lt;number&gt;();<br>  const [pageNumber, setPageNumber] = useState&lt;number&gt;(1);<br>  function onDocumentLoadSuccess({ numPages }: { numPages: number }): void {<br>    setNumPages(numPages);<br>  }<br>  function nextPage() {<br>    setPageNumber((v) =&gt; ++v);<br>  }<br>  function prevPage() {<br>    setPageNumber((v) =&gt; --v);<br>  }<br>  return (<br>    &lt;div style={{ width: &quot;100%&quot;, height: &quot;100%&quot; }}&gt;<br>      &lt;button onClick={prevPage} disabled={pageNumber &lt;= 1}&gt;<br>        Previous<br>      &lt;/button&gt;<br>      &lt;button onClick={nextPage} disabled={pageNumber &gt;= (numPages ?? -1)}&gt;<br>        Next<br>      &lt;/button&gt;<br>      &lt;Document<br>        file={src}<br>        onLoadSuccess={onDocumentLoadSuccess}<br>        className=&quot;my-react-pdf&quot;<br>      &gt;<br>        &lt;Page pageNumber={pageNumber} /&gt;<br>      &lt;/Document&gt;<br>      &lt;p&gt;<br>        Page {pageNumber} of {numPages}<br>      &lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>You can check out my example on my <a href="https://github.com/9haroon/pdf-embed-react-examples/blob/main/src/components/PdfReactPdf.tsx">Github</a>: components/PdfReactPdf.tsx.</p><h3>Pros:</h3><ul><li><strong>Easy Integration</strong>: Works smoothly with React. Better developer documentation compared to PDF.js.</li><li><strong>More Control</strong>: Offers more customization than iFrame or New Tab methods.</li><li><strong>Responsive and Customizable</strong>: Adjusts well to different screen sizes and offers some customization.</li></ul><h3>Cons:</h3><ul><li><strong>More Setup</strong>: Takes a bit more effort to set up compared to simpler methods.</li><li><strong>Limited Advanced Features</strong>: Doesn’t offer as much flexibility as using the full PDF.js library.</li></ul><h3>When to Use It:</h3><p>Use react-pdf if you need an easy-to-implement, customizable PDF viewer for your React project.</p><h3>Conclusion</h3><p>There are several ways to implement a PDF viewer in React.js. Using iFrame or opening the PDF in a new tab offers simplicity but limits customization. <strong>PDF.js</strong> provides advanced features and control, but it comes with added complexity. <strong>react-pdf</strong> (open-source) bridges the gap by offering ease of use with customization options.</p><p>Choose the method that best fits your project’s needs, whether it’s speed, simplicity, or control over the user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*ZKT-a3i9BRA07s1M.gif" /></figure><h3>Is there a Better Solution?</h3><p>While methods like iFrame or opening PDFs in a new tab can be quick fixes, they don’t offer much control or customization. PDF.js and react-pdf (an open-source library for React) provide more advanced options, but they come with their own challenges — especially if you’re looking for something easier to implement, maintain, and customize for your specific React project.</p><p>That’s why I’m building <a href="https://www.react-pdf.dev/?utm_source=medium&amp;utm_medium=referral&amp;utm_content=best-4-methods-to-build-a-pdf-viewer-in-react-js-2024">React PDF</a> (not to be confused with react-pdf). While react-pdf is a great open-source library, React PDF is designed to offer more flexibility, powerful customization options, and a simpler setup process tailored to developers working on both small and complex React applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GDcSASE5N3NabRZeakIGiw.jpeg" /></figure><ol><li><strong>Made for React.js</strong>: Unlike more general libraries, React PDF is built from the ground up to work seamlessly with React. Whether you need quick rendering or advanced features, it integrates easily into your project with just a few lines of code.</li><li><strong>Customization without Complexity</strong>: With React PDF, you have full control over the appearance and behavior of your PDF viewer. You can match the viewer’s design to your app’s theme, add interactive features like search and bookmarking, and customize the layout — all without the hassle of dealing with complex configurations.</li><li><strong>Extensive Feature Set</strong>: Whether you need basic functionality like viewing PDFs or more advanced features like rotation, different scrolling modes, and responsive design, React PDF has you covered. Plus, it’s built with performance in mind, so you don’t have to worry about lag when handling large files.</li><li><strong>User-Friendly Documentation</strong>: I’ve made sure the technical docs are clear and easy to follow. From starter kits to detailed API references, everything is in place to help you get up and running fast.</li><li><strong>Reliable Support and Updates</strong>: As developers, I know how important it is to have reliable support. That’s why React PDF comes with responsive customer support and regular updates to keep the library optimized and bug-free.</li></ol><p>If this sounds like what you need, I’d be grateful if you could check out <a href="https://www.react-pdf.dev/?utm_source=medium&amp;utm_medium=referral&amp;utm_content=best-4-methods-to-build-a-pdf-viewer-in-react-js-2024">React PDF</a>. Your support encourages me to keep improving and building tools for the community. Thank you! 🙏</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*wu1Wc_x3dDtS68cS.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f5f658d30cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Using JS Object Schemas to Validate Data with Yup, Zod, Joi and more ]]></title>
            <link>https://medium.com/@9haroon_dev/using-js-object-schemas-for-custom-validations-with-yup-zod-joi-and-more-c3eeccf5998c?source=rss-b001e6e0fc89------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3eeccf5998c</guid>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[json-schema]]></category>
            <dc:creator><![CDATA[Kittisak Ma]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 13:02:32 GMT</pubDate>
            <atom:updated>2024-03-22T08:03:38.922Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Using JS Object Schemas to Validate Data with Yup, Zod, Joi and more" src="https://cdn-images-1.medium.com/max/1000/1*TS5bQMVl56a7sOmbqRjUUQ.jpeg" /></figure><p>I’m sure many of you who have developed interactive web applications have experience handling data validation. In fact, it’s probably a common topic. You could create custom validations or you may choose to validate via JavaScript object schemas (JSON). When I need to use JSON Schema library, I tend to use Yup. Having validate data with JSON Schema libraries and without one across different project scales, they are effective in their own ways.</p><p>Today, I want to dive deeper into the world of JSON, exploring popular libraries as well as other notable libraries in the ecosystem. Additionally, I will mention how you can do custom validations without using a JSON Schema library. And finally, I will compare both methods.</p><p>Please note that I’m using code examples using JavaScript without basing on a JS framework such as React or Vue since you can apply both methods to any JS framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*q6VwrkBooyp_yyZl.gif" /></figure><h3>Validex: The Most Complete Validation Collection for React Forms</h3><p>Just a quick background about what I’m working on. <a href="https://www.validex.dev/?utm_source=medium&amp;utm_content=using-json-for-custom-validations">Validex</a> can help you validate React forms in minutes. It has over 36 validators ranging from string, password, credit card, email, file, image and more. Each validator has TypeScript and JavaScript codes, RegEx and Non-RegEx options and unit tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*6YmCPUbEOHwqeNxU.png" /></figure><p>I would be grateful 🥹 if you could take a moment to explore <a href="https://www.validex.dev/?utm_source=medium&amp;utm_content=using-json-for-custom-validations">Validex</a> out. It would motivate me to create even more contents.</p><h3>What is JavaScript Object Schema?</h3><p>JavaScript object schemas define the structure and validation rules for JavaScript objects. They provide a way to specify the expected shape of an object and enforce validation rules on its properties. This helps ensure that data is in the correct format and meets certain criteria.</p><p>Object schemas can be particularly useful in scenarios where user input needs to be validated before it is processed. For example, validating user registration forms, API request payloads, or form fields in a web application.</p><h3>Introducing Yup and Zod</h3><p>Yup and Zod are two popular libraries in the JavaScript ecosystem that provide powerful and flexible schema validation capabilities. Both libraries offer rich features and strong type support, making them ideal choices when working with TypeScript.</p><h3>Yup</h3><p><a href="https://github.com/jquense/yup?tab=readme-ov-file#yup">Yup</a> is a schema validation library that focuses on simplicity and ease of use. It provides a fluent API for defining object schemas and supports a wide range of validation rules out of the box. With Yup, you can easily define schema validation rules such as required fields, minimum and maximum values, regular expressions, and more.</p><p>Yup also supports asynchronous validation, allowing you to validate data against external data sources or perform complex validation logic. It also integrates well with popular frontend frameworks like React, making it a versatile choice for both server-side and client-side validation.</p><h3>Zod</h3><p><a href="https://github.com/colinhacks/zod?tab=readme-ov-file#zod">Zod</a> is another powerful schema validation library for JavaScript and TypeScript. It takes a pragmatic approach to validation and aims to provide a seamless development experience. Zod’s API is inspired by Yup but comes with some unique features and optimizations.</p><p>With Zod, you can define complex object schemas with ease. It supports various validation rules and provides a robust type inference system that ensures type safety throughout your codebase. Zod also includes features like partial and pick helpers, allowing you to create more flexible validation schemas.</p><h3>Other Libraries in the Ecosystem</h3><p>While Yup and Zod are popular choices, there are several other libraries available in the JavaScript ecosystem for schema validation. Some of these include:</p><ul><li><a href="https://github.com/hapijs/joi?tab=readme-ov-file#joi">Joi</a>: Joi is a powerful schema validation library that focuses on server-side validation. It provides a comprehensive rule set and supports complex validation scenarios.</li><li><a href="https://github.com/ajv-validator/ajv?tab=readme-ov-file#ajv-json-schema-validator">Ajv</a>: Ajv is a fast and powerful JSON Schema validator that supports a wide range of validation keywords and features. It is highly extensible and widely used in the JavaScript community.</li><li><a href="https://github.com/ianstormtaylor/superstruct?tab=readme-ov-file#why">Superstruct</a>: Superstruct is a lightweight and minimalist validation library that leverages TypeScript’s powerful typesystem to provide compile-time validation.</li></ul><p>These libraries offer different features and tradeoffs, so exploring the options and choosing the one that best fits your needs is recommended.</p><h3>How to Utilize Each Library in a Customized Manner</h3><p>In this section, I will explore how to implement custom email validation using libraries such as Yup, Zod, and other popular options like Joi and Ajv. Email validation is a common requirement in many applications, and different libraries offer different approaches and features to handle this task. Let’s dive into the examples and explore how each library can be used to validate email addresses in a customized manner.</p><h3>Email Validation Rules</h3><p>Here are some commonly used email validation rules that I will be incorporating in the examples:</p><ol><li><strong>Email is required</strong>: The email field must not be empty or null.</li><li><strong>Email must include @ symbol</strong>: The email address should contain the “@” symbol.</li><li><strong>Email must include the domain</strong>: The email address should include the domain name (e.g., example.com).</li><li><strong>Email must include the top-level domain</strong>: The email address should have a valid top-level domain (e.g., .com, .org, .net).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/0*Lc-3EOMv--eOCB9o.gif" /></figure><h4>Yup</h4><p>For an email validation, Yup will use string and test methods to create custom validation. Here is an example.</p><pre>import { object, string } from &quot;yup&quot;;<br>const formSchema = object({<br>  email: string()<br>    .required(&quot;Please provide an email address&quot;)<br>    .test(&quot;email-symbol&quot;, &quot;Please include an `@` symbol&quot;, (value) =&gt; {<br>      return value.includes(&quot;@&quot;);<br>    })<br>    .test(&quot;email-domain&quot;, &quot;Please provide an email&#39;s domain&quot;, (value) =&gt; {<br>      return /@[a-zA-Z]{2,}/gi.test(value);<br>    })<br>    .test(<br>      &quot;email-top-level-domain&quot;,<br>      &quot;Please include top level domain such as .co .org&quot;,<br>      (value) =&gt; {<br>        return /\.[a-zA-Z]{2,}$/gi.test(value);<br>      }<br>    )<br>    .test(&quot;email-format&quot;, &quot;Invalid email format&quot;, (value) =&gt; {<br>      const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;<br>      return emailRegex.test(value);<br>    })<br>});<br>...</pre><p>You may find the codes in this <a href="https://codepen.io/9haroon/pen/xxBvqPb">CodePen link</a>.</p><h4>Zod</h4><p>Zod will use string and refine methods to create custom validation</p><pre>import { z } from &quot;zod&quot;;</pre><pre>const formSchema = z.object({<br>  email: z<br>    .string()<br>    .refine(<br>      (val) =&gt; !!val,<br>      () =&gt; {<br>        return {<br>          message: &quot;Please provide an email address&quot;<br>        };<br>      }<br>    )<br>    .refine((val) =&gt; val.includes(&quot;@&quot;), {<br>      message: &quot;Please include an `@` symbol&quot;<br>    })<br>    .refine((val) =&gt; /@[a-zA-Z]{2,}/gi.test(val), {<br>      message: &quot;Please provide an email&#39;s domain&quot;<br>    })<br>    .refine((val) =&gt; /\.[a-zA-Z]{2,}$/gi.test(val), {<br>      message: &quot;Please include top level domain such as .co .org&quot;<br>    })<br>});</pre><p><a href="https://codepen.io/9haroon/pen/JjzgQEZ">CodePen link</a> of Zod validation.</p><h4>Joi</h4><p>Joi will use any and custom methods to create non-primitive data validation.</p><pre>import Joi from &quot;joi&quot;;<br><br>const validateEmailFn: Joi.CustomValidator&lt;string&gt; = (value, helpers) =&gt; {<br>  console.log(&quot;validateEmail&quot;, value);<br>  if (!value) {<br>    return helpers.message(&quot;Please provide an email address&quot;);<br>  }<br>  if (!value.includes(&quot;@&quot;)) {<br>    return helpers.message(&quot;Please include an `@` symbol&quot;);<br>  }<br>  if (!/@[a-zA-Z]{2,}/gi.test(value)) {<br>    return helpers.message(&quot;Please provide an email&#39;s domain&quot;);<br>  }<br>  if (!/\.[a-zA-Z]{2,}$/gi.test(value)) {<br>    return helpers.message(&quot;Please include top level domain such as .co .org&quot;);<br>  }<br>  return value;<br>};<br><br>const { object, string } = Joi.types();<br>const formSchema = object.keys({<br>  email: Joi.any().custom(validateEmailFn, &quot;test&quot;)<br>});</pre><p><a href="https://codepen.io/9haroon/pen/RwObbjy">CodePen link</a> of custom email validation with Joi.</p><h4>Ajv</h4><p>For Ajv, you have to use addKeyword method with code, compile or validate properties to custom how to validate your JSON schema. Referring to its <a href="https://ajv.js.org/keywords.html">documentation</a>, I have created an example with validate property.</p><pre>import Ajv, { ErrorObject, JSONSchemaType } from &quot;https://esm.sh/ajv&quot;;<br>interface Form {<br>  email: string;<br>}<br>// Create an instance of Ajv<br>const ajv = new Ajv({ allErrors: true });<br>ajv.addKeyword({<br>  keyword: &#39;emailFormat&#39;,<br>  type: &#39;string&#39;,<br>  errors: true,<br>  validate:<br>    function customValidate(schema: boolean, value: string) {<br>      let message = &#39;&#39;;<br>      if (!value) {<br>        message = &#39;Please provide an email address&#39;;<br>      } else if (!value.includes(&#39;@&#39;)) {<br>        message = &#39;Please include an `@` symbol&#39;;<br>      } else if (!/@[a-zA-Z]{2,}/gi.test(value)) {<br>        message = &#39;Please provide an email\&#39;s domain&#39;;<br>      } else if (!/\.[a-zA-Z]{2,}$/gi.test(value)) {<br>        message = &#39;Please include top level domain such as .co .org&#39;;<br>      } else {<br>        return true<br>      }<br>      customValidate.errors = [{keyword: &#39;emailFormat&#39;, message}];<br>        // Use a regular expression to validate email format<br>        // const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;<br>        // return emailRegex.test(value);<br>      return false;<br>    },<br>})<br>const formSchema: JSONSchemaType&lt;Form&gt; = {<br>  type: &quot;object&quot;,<br>  properties: {<br>    email: {<br>      type: &quot;string&quot;,<br>      emailFormat: true<br>    }<br>  },<br>};<br>// Compile the schema<br>const validate = ajv.compile(formSchema);</pre><p>This shows Ajv custom validation without ajv-formats. <a href="https://codepen.io/9haroon/pen/qBwWdda">CodePen link</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*iF-csdLgQSdW-Ktq.gif" /></figure><h3>Custom Validation Without JSON Schema Libraries</h3><p>When it comes to data validation, an alternative approach to using JSON schema libraries is to implement custom validation logic. This involves writing code specifically tailored to validate the data based on the requirements and constraints of the application. Here is the example of the Email validation without any JSON schema library.</p><pre>import { debounce } from &#39;https://codepen.io/9haroon/pen/GRLgddJ.js&#39;;<br><br>function validateEmail(email: string) {<br>  if (!email) {<br>    return { message: &#39;Please provide an email address&#39; }<br>  }<br>  if (!email.includes(&#39;@&#39;)) {<br>    return { message: &#39;Please include an `@` symbol&#39; }<br>  }<br>  if (!(/@[a-zA-Z]{2,}/gi.test(email))) {<br>    return { message: &#39;Please provide an email\&#39;s domain&#39; }<br>  }<br>  if (!(/\.[a-zA-Z]{2,}$/gi.test(email))) {<br>    return { message: &#39;Please include top level domain such as .co .org&#39; }<br>  }<br>  return { message: null }<br>}<br><br>const form = document.querySelector(&quot;#form&quot;);<br>const errorElem = document.querySelector(&quot;#form &gt; p&quot;);<br>const emailElem = document.querySelector(&#39;[name=&quot;email&quot;]&#39;);<br><br>const submitCallback = (event) =&gt; {<br>  console.log(&#39;Start Validation&#39;)<br>  errorElem.innerHTML = &quot;&quot;;<br>  const { message } = validateEmail(emailElem.value)<br>  if (message) {<br>    errorElem.innerHTML = message;<br>  }<br>};<br><br>form.addEventListener(&quot;submit&quot;, submitCallback, false);<br>emailElem.addEventListener(&quot;input&quot;, debounce(submitCallback, 500), false);</pre><p>The codes has an event listeners for the form submission event and the email input event. When the form is submitted, the submitCallback function is executed. Similarly, when the user inputs text in the email field, the submitCallback function is executed after a debounce of 500 milliseconds (to prevent rapid validation). In submitCallback function. It clears any previous error messages, calls the validateEmail function to validate the email value entered by the user, and displays the error message (if any) in the errorElem element.</p><p>Overall, this code demonstrates how to validate an email address without using a JSON Object schema. It combines DOM manipulation, email validation logic, and event handling to provide a basic form validation functionality.</p><p>This is <a href="https://codepen.io/9haroon/pen/JjVEPpb">CodePen link</a>. Feel free to explore it further.</p><h3>Comparing Using V. Without JSON Schema Libraries</h3><p>Based on various technical factors, I have made a side by side comparison summary below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*OCUAoZKYuy6AChlEMN352w.png" /></figure><p>Considering the pros and cons outlined above, the decision to use or not use JSON schema libraries for data validation depends on factors such as the project requirements, complexity of validation rules, familiarity with JSON schemas, and the trade-off between standardization and customization in data validation processes.</p><h3>Conclusion</h3><p>In this article, I explore data validation various JavaScript Object Notation (JSON) Schemas libraries and show how you can use them to implement validation rules for schema validation in TypeScript. JSON Schema offers a formidable mechanism for defining and enforcing validation rules on objects, thereby ensuring data integrity and consistency.</p><p>While JSON Schema libraries provide powerful tools, sometimes custom validation tailored to specific project requirements becomes necessary. When opting for custom validation, consider the following steps:</p><ol><li><strong>Define Custom Validation Functions</strong>: Create custom validation functions that directly inspect the object properties and enforce your desired rules. These functions can be as simple or complex as needed.</li><li><strong>Integrate Custom Validation Logic</strong>: Incorporate your custom validation logic into your application code. You have the flexibility to check individual properties, cross-validate fields, or apply domain-specific rules.</li><li><strong>Error Handling and Feedback</strong>: When validation fails, provide meaningful error messages to guide users or developers. Clear feedback ensures better understanding and smoother debugging.</li><li><strong>Unit Testing</strong>: Rigorously test your custom validation functions to ensure they behave as expected. Unit tests help catch edge cases and maintain reliability.</li></ol><p>By embracing custom validation, you can tailor your validation rules precisely to your project’s needs.</p><p>As summarized above, both methods have their own merits. In fact, depending on your requirements, you can even apply custom validation method to validate data via JSON Schema. What are your thoughts on this matter? Feel free to leave your comments in the comment section. Much appreciated!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*fp3aEtuwT5LmUfQD.gif" /></figure><h3>Validex: The Most Complete Validation Collection for React Forms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*edB6WJXCWTxWufu_.png" /></figure><p>If you feel like this article helped you, please check out <a href="https://www.validex.dev/?utm_source=medium&amp;utm_content=using-json-for-custom-validations">Validex</a>. It has over 36 validators (such as string, password, credit card, email, file, image and more) so that you can validate React forms in minutes.</p><p>It would encourage me to continue creating even more contents. Thank you in advance! 🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3eeccf5998c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Supercharge Your Repo for Hacktoberfest 2023: Essential Guide for Maintainers ]]></title>
            <link>https://medium.com/@9haroon_dev/supercharge-your-repo-for-hacktoberfest-2023-essential-guide-for-maintainers-9ada0c4cdc8b?source=rss-b001e6e0fc89------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ada0c4cdc8b</guid>
            <category><![CDATA[hacktoberfest]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Kittisak Ma]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 09:23:06 GMT</pubDate>
            <atom:updated>2023-09-27T09:23:06.739Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Supercharge Your Repo for Hacktoberfest 2023: Essential Guide for Maintainers" src="https://cdn-images-1.medium.com/max/1000/1*jzb1P0E31UYPVtJdIE5CMA.jpeg" /></figure><p>Hi everyone! This year, I’m tasked with setting up my company’s Github repositories for <a href="https://hacktoberfest.com/">Hacktoberfest</a> 2023. While researching and preparing, I thought I would share what I found to be helpful. Hope the information is useful to any maintainers out there.</p><p>Hacktoberfest, started by <a href="https://www.digitalocean.com/">DigitalOcean</a>, is celebrating its 10th anniversary this year 🥳 It is an annual event that celebrates open-source software development by having developers actively contribute to open-source projects. As of last year alone, there were over 147,000 participants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*cRExk9PJZQ7bodZK.gif" /></figure><p>For maintainers who want to get involved, the article will explain what Hacktoberfest is, why you should give it a try and what you need to do participate.</p><p>For maintainers who have previously participated or heard of Hacktoberfest, you can treat this as a checklist or a refresher on what you need to prepare as maintainers. It has been a year after all 😂</p><h3>What is Hacktoberfest?</h3><p>Hacktoberfest is an event to encourages developers to contribute to open-source projects. Contributors are encouraged to make <strong>four</strong> valid pull/merge requests to public and participating repositories to be eligible for digital rewards. It provides an opportunity for developers, both new and experienced, to engage with open-source projects and make meaningful contributions.</p><h3>When and Where does it take place?</h3><p>Hacktoberfest 2023 will take place between October 1 and October 31 (in any time zone, UTC-12 thru UTC+14).</p><p>Pull/merge requests is only valid if made on either via the <a href="https://github.com/topics/hacktoberfest">GitHub</a> or <a href="https://gitlab.com/explore/projects/topics/hacktoberfest">GitLab</a> platform.</p><h3>Why should you participate as maintainers?</h3><p>Since contributors can only earn counts from qualified Pull/merge requests from issues created by maintainers, maintainers play a crucial role in the success of Hacktoberfest. By participating as a maintainer, you can benefit in various ways:</p><ol><li><strong>Increased community engagement:</strong> Brings attention to your project and attracts new contributors, kickstarting or fostering an active community around your repository going forward.</li><li><strong>Quality contributions:</strong> Ensure that the contributions made to your project are meaningful and adhere to your project’s guidelines and standards. More on ways to handle spam in the next section.</li><li><strong>Skill development and collaboration:</strong> Provides a great opportunity to collaborate with developers from diverse backgrounds, learn from others, and improve your coding skills.</li></ol><blockquote><em>Note: Although maintainers who review Pull/merge requests from others do not get digital rewards, you are still eligible for rewards if you submit Pull/merge requests to other participating repositories or even your own repositories.</em></blockquote><h3>Wouldn’t there be a lot of spam?</h3><p>There is a strict rule of disqualification by Hacktoberfest</p><blockquote><em>Pull/merge requests that have a label containing the word spam won’t be counted, and participants with two or more requests identified as spam will be disqualified</em></blockquote><p>However, due to the nature of the event, spams are definitely possible. The benefits definitely outweigh the trouble for maintainers who are looking to get more attention. For other maintainers, participating is one of the ways to give back to the open-source community. So what better timing to foster a stronger open-source community to attract new contributors (beginner or experienced developers).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*VaZ_CfoOVLFlh9Kj.gif" /></figure><p>To further minimize spam, here are some more suggestions:</p><ul><li><strong>Contribution guidelines:</strong> Set up clear contribution guidelines to discourage spammy contributions. Include requirements such as meaningful code changes, proper documentation updates, or thorough bug reports. Here is an amazing <a href="https://github.com/nayafia/contributing-template/blob/HEAD/CONTRIBUTING-template.md">contributing template</a> by <a href="https://twitter.com/nayafia">@nadia</a> to get started. For a good real-life example, you may want to check out <a href="https://github.com/amplication/amplication/blob/master/CONTRIBUTING.md">Amplication</a>.</li><li><strong>Communication and feedback:</strong> Engage with contributors by providing constructive feedback if you consider a contribution a spam or invalid. By being patient and offering guidance and suggestions to improve their contributions, you can create a more welcoming environment for everyone to thrive in.</li></ul><h3>How to participate as maintainers?</h3><h3>Step 1A: Add a hacktoberfest topic to your repository</h3><figure><img alt="Add Hacktoberfest Topic" src="https://cdn-images-1.medium.com/max/800/0*N9IUsKv69qpezRRP.png" /></figure><h3>Step 1B: Add hacktoberfest-accepted label to your issue</h3><figure><img alt="Add Hacktoberfest-Accepted Label" src="https://cdn-images-1.medium.com/max/800/0*O-PrZmY7kGGc6gz5.png" /></figure><blockquote><em>Note: You can also choose to do both steps.</em></blockquote><h3>Step 2: Create meaningful issues</h3><p>Like how we don’t like contributors to spam us, we should not create “spam” issues. Bad issues like adding a name or profile to a list or arbitrarily curating content should be discouraged. Anyone can report a repository for Hacktoberfest to investigate.</p><p>Although you may not need to prepare much for existing contributors of your repositories, you may want to create issues with good first issue for new contributors who still unfamiliar with your repository to get involved. In my opinion, <a href="https://github.com/ToolJet/ToolJet/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22">ToolJet</a> and <a href="https://github.com/PostHog/posthog/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22">Posthog</a> have great examples of good first issue.</p><p>Besides issues related to coding, you can also create issues that are low-code or non-code in nature such as writing technical documentation, tutorials , blog posts, translating to different languages and many more. For more inspiration, please check out more examples at <a href="https://opensource.com/life/16/1/8-ways-contribute-open-source-without-writing-code">8 non-code ways to contribute to open source</a>.</p><figure><img alt="Low Code and Non Code Contribution" src="https://cdn-images-1.medium.com/max/800/0*ZIS1jGbiNfF5noCT.png" /></figure><p><em>Note: For more information, please see </em><a href="https://hacktoberfest.com/participation/#low-or-non-code"><em>low-or-non-code</em></a><em> section of Hacktoberfest.</em></p><h3>Review Pull/Merge Request</h3><p>It’s important to be kind and patient. If Pull/merge requests are rejected due to spam or invalid contributions, please explain to them. Some contributors may just be making honest mistakes. Everyone is a beginner at first 🤭</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/0*H3o3obxYCpPq03vj.gif" /></figure><h3>Conclusion</h3><p>Preparing your Github repository for Hacktoberfest is essential to attract contributors, foster collaboration, and maintain the overall quality of your project. By actively engaging with the Hacktoberfest community and providing support to contributors, you can create a welcoming environment for open-source contributions.</p><h3>Could you support me by starring <a href="https://github.com/logicspark/berryjam">Berryjam repo</a>?</h3><p>Berryjam is a UI components analyzer for Vue 3 &amp; Nuxt to detect component usage, relationships and more. If you feel this article is useful, could you consider starring ⭐⭐⭐ Berryjam’s Github <a href="https://github.com/logicspark/berryjam">repo</a>?</p><p>It would mean the world and encourage me to create more content.</p><p>Thank you in advance! 🙏</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*_vM2PMoqUI5Qs6Vn.gif" /></figure><p>P.S Feel free to add your or other repos that you wish people would contribute to in the comment section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ada0c4cdc8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>