2211 words
11 minutes
Generating PDFs with a Custom React Hook
Background
Sooner or later most projects need to generate PDF files, and the process turns out to be surprisingly fiddly — there are a lot of details to get right.
If all you need is a PDF that mirrors the page exactly as rendered, html2canvas plus jsPDF is enough.
The code is straightforward:
import html2canvas from 'html2canvas';import jsPDF from 'jspdf';
const Example = () => { const onDownload = () => { html2canvas(document.body).then((canvas) => { const imgData = canvas.toDataURL('image/png'); const pdf = new jsPDF(); pdf.addImage(imgData, 'PNG', 0, 0); pdf.save('example.pdf'); }); };
return <button onClick={onDownload}>Download PDF</button>;};
export default Example;That’s the minimal version. Real projects, however, pile on extra requirements:
- Hyperlinks in the PDF must be clickable (implemented by walking every
<a>tag on the page, overlaying a transparent hit area at the right coordinates, and wiring it to jump to the target URL) - The PDF file can get huge (well over 80 MB — mitigated by lowering the resolution, compressing images, and shrinking the file)
- The PDF must match the on-page styling (the + button on antd table extra rows rendered as a misaligned stack of strokes in the export — fixed by hiding the original ::before/::after pseudo-elements, overlaying an inline SVG, and restoring everything after export)
The Solution
To make all of this reusable, I wrapped the whole pipeline into a hook.
Using the hook:
import { usePdfGenerator } from '@/src/hooks/usePdfGenerator';import { Button } from 'antd';
const Example = () => { const { contentRef, generatePdf, isLoading } = usePdfGenerator(); const onDownload = () => { generatePdf('example'); // If you need the exported file, pass a callback or use the return value of generatePdf const file = generatePdf('example', {}, (file) => { console.log('file', file); }); };
return <div ref={contentRef}> <h1>Hello World</h1> <Button loading={isLoading} onClick={onDownload}>Download PDF</Button> </div>;};
export default Example;WARNINGThe callback and the return value deliver the generated image file, not the PDF — our project also has a Word-export requirement where the backend expects the image from the frontend.
The hook source:
import { useRef, useCallback, useState } from 'react';import html2canvas from 'html2canvas';import jsPDF from 'jspdf';
type GeneratePdfOptions = { // Output image type: JPEG is smaller; PNG is lossless but larger imageType?: 'jpeg' | 'png'; // Only applies when imageType is JPEG; range 0-1, recommended 0.6~0.85 jpegQuality?: number; // Secondary downscale ratio, 0-1. Reduces pixel count without visibly hurting sharpness; recommended 0.7~0.9. downscaleRatio?: number; // Target max file size (KB); used for adaptive PNG compression (steps resolution down, preserving sharpness where possible) maxFileSizeKB?: number; // Whether to download isDownload?: boolean; // Callback callback?: (file: File) => void;};
export const usePdfGenerator = () => { // 1. Create a ref to attach to the DOM node you want to export const contentRef = useRef(null); const [isLoading, setIsLoading] = useState(false); // 2. Track loading state during generation for a better UX // const [isLoading, setIsLoading] = useState(false);
// 3. Wrap the core function in useCallback to avoid unnecessary re-renders const generatePdf = useCallback(async ( fileName = 'document', options: GeneratePdfOptions = {}, callback: (file: File) => void = () => { } ): Promise<File | undefined> => { const { imageType = 'png', jpegQuality = 0.82, downscaleRatio = 0.88, isDownload = true } = options; const element: HTMLElement = contentRef.current!;
if (!element) { console.error("Cannot generate PDF: the referenced content element was not found."); return undefined; }
setIsLoading(true); // Generation started, set loading to true // Pre-prepare anchor style restorers and inline the computed colors before rendering so the export matches the page const anchorsInDom = Array.from(element.querySelectorAll('a')) as HTMLAnchorElement[]; const restoreAnchorInlineStyles: Array<() => void> = []; anchorsInDom.forEach((a) => { const prevColor = a.style.color; const prevTdColor = (a.style as any).textDecorationColor as string; const prevTextDecoration = a.style.textDecoration; const cs = window.getComputedStyle(a); const computedColor = cs.color; const computedTdColor = (cs as any).textDecorationColor || computedColor; a.style.color = computedColor; try { (a.style as any).textDecorationColor = computedTdColor; } catch (_) { } if ((cs.textDecorationLine || '').includes('underline') && !a.style.textDecoration) { a.style.textDecoration = 'underline'; } restoreAnchorInlineStyles.push(() => { a.style.color = prevColor; try { (a.style as any).textDecorationColor = prevTdColor; } catch (_) { } a.style.textDecoration = prevTextDecoration; }); });
// Fix antd Table expand/collapse icons (+/-) rendering badly under html2canvas: // Approach: hide the original ::before/::after pseudo-elements, overlay an inline SVG, restore after export const cleanupExpandIconFixers: Array<() => void> = []; const styleTag = document.createElement('style'); styleTag.setAttribute('data-pdf-export-fix', 'expand-icon'); styleTag.textContent = ` .ant-table-row-expand-icon.__pdf_export_fix::before, .ant-table-row-expand-icon.__pdf_export_fix::after { content: none !important; background: none !important; border: 0 !important; } `; document.head.appendChild(styleTag); cleanupExpandIconFixers.push(() => { try { document.head.removeChild(styleTag); } catch (_) { } });
const expandButtons = Array.from( element.querySelectorAll('button.ant-table-row-expand-icon') ) as HTMLButtonElement[]; expandButtons.forEach((btn) => { const cs = window.getComputedStyle(btn); const beforeStyle = window.getComputedStyle(btn, '::before'); const afterStyle = window.getComputedStyle(btn, '::after'); const isTransparent = (c: string | null | undefined) => !c || c === 'transparent' || c === 'rgba(0, 0, 0, 0)'; const pickColor = (...colors: Array<string | null | undefined>) => colors.find((c) => !isTransparent(c)); const strokeColor = (pickColor( beforeStyle.backgroundColor, (beforeStyle as any).borderColor, afterStyle.backgroundColor, (afterStyle as any).borderColor, cs.backgroundColor, cs.color, 'rgba(0,0,0,0.45)' ) || 'rgba(0,0,0,0.45)') as string; const prevPosition = btn.style.position; const prevClassName = btn.className; btn.style.position = prevPosition || 'relative'; if (!btn.classList.contains('__pdf_export_fix')) btn.classList.add('__pdf_export_fix');
const overlay = document.createElement('span'); overlay.style.position = 'absolute'; overlay.style.inset = '0'; overlay.style.display = 'flex'; overlay.style.alignItems = 'center'; overlay.style.justifyContent = 'center'; overlay.style.pointerEvents = 'none'; overlay.style.zIndex = '1';
const expanded = btn.getAttribute('aria-expanded') === 'true'; // Draw + or - in a 16x16 viewport, 1.5 stroke width, color from the button's color const svg = expanded ? `<?xml version="1.0" encoding="UTF-8"?> <svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> <line x1="3" y1="8" x2="13" y2="8" stroke="${strokeColor}" stroke-width="1.5" stroke-linecap="round"/> </svg>` : `<?xml version="1.0" encoding="UTF-8"?> <svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> <line x1="3" y1="8" x2="13" y2="8" stroke="${strokeColor}" stroke-width="1.5" stroke-linecap="round"/> <line x1="8" y1="3" x2="8" y2="13" stroke="${strokeColor}" stroke-width="1.5" stroke-linecap="round"/> </svg>`; overlay.innerHTML = svg; btn.appendChild(overlay);
cleanupExpandIconFixers.push(() => { try { btn.removeChild(overlay); } catch (_) { } try { btn.className = prevClassName; } catch (_) { } btn.style.position = prevPosition; }); });
try {
// Call html2canvas. The scale setting boosts sharpness. const canvasScale = 2; // html2canvas render scale; feeds into coordinate math later const canvas = await html2canvas(element, { scale: canvasScale, // Higher resolution useCORS: true, // Allow cross-origin images logging: false, // Keep the console quiet backgroundColor: '#FFFFFF', });
// High-quality downscale of the raw canvas, with adaptive compression for PNG (by stepping the resolution down) const exportCanvas = document.createElement('canvas'); const ctx = exportCanvas.getContext('2d'); if (!ctx) throw new Error('Failed to acquire 2D context');
const originalWidth = canvas.width; const originalHeight = canvas.height; let currentDownscale = Math.min(1, Math.max(0.5, downscaleRatio)); const minDownscale = 0.6; // Floor for the downscale ratio to avoid visible blur const maxFileSizeBytes = Math.max(1, Math.round((options.maxFileSizeKB ?? 320) * 1024));
const redrawWithDownscale = (ratio: number) => { exportCanvas.width = Math.max(1, Math.round(originalWidth * ratio)); exportCanvas.height = Math.max(1, Math.round(originalHeight * ratio)); ctx.imageSmoothingEnabled = true; // @ts-ignore: browser support check if (ctx.imageSmoothingQuality) ctx.imageSmoothingQuality = 'high'; ctx.clearRect(0, 0, exportCanvas.width, exportCanvas.height); ctx.drawImage( canvas, 0, 0, originalWidth, originalHeight, 0, 0, exportCanvas.width, exportCanvas.height ); };
// Initial draw redrawWithDownscale(currentDownscale);
// For PNG, adaptively lower the resolution to cap the file size; JPEG is handled by the quality parameter const getPngBlob = async (): Promise<Blob> => new Promise((resolve, reject) => { try { exportCanvas.toBlob((blob) => { if (blob) resolve(blob); else reject(new Error('Failed to export PNG blob')); }, 'image/png'); } catch (e) { reject(e); } });
let tentativePngBlob: Blob | undefined; for (let attempt = 0; attempt < 6; attempt += 1) { // Generate the PNG blob and check its size // eslint-disable-next-line no-await-in-loop const blob = await getPngBlob(); tentativePngBlob = blob; if (blob.size <= maxFileSizeBytes || currentDownscale <= minDownscale) { break; } // Shrink another ~8-12% per attempt to minimize sharpness loss currentDownscale = Math.max(minDownscale, Math.round(currentDownscale * 0.9 * 100) / 100); redrawWithDownscale(currentDownscale); }
const mime = imageType === 'png' ? 'image/png' : 'image/jpeg'; const quality = imageType === 'png' ? undefined : Math.min(1, Math.max(0.5, jpegQuality)); const imgData = exportCanvas.toDataURL(mime, quality as any);
// Create the jsPDF instance (A4) const pdf = new jsPDF({ orientation: 'portrait', // p: portrait, l: landscape unit: 'mm', format: 'a4', }); // console.log(canvas);
// Compute PDF page and image dimensions const pdfWidth = pdf.internal.pageSize.getWidth(); const pdfHeight = pdf.internal.pageSize.getHeight(); const imgWidth = exportCanvas.width; const imgHeight = exportCanvas.height;
// Margins: 36px left/right, 20px top/bottom (converted to mm) const marginLeft = 36 * 0.264583; // px to mm (1px = 0.264583mm) const marginTop = 20 * 0.264583;
// Usable space after margins const availableWidth = pdfWidth - (marginLeft * 2); const availableHeight = pdfHeight - (marginTop * 2);
// Recompute the ratio to fit within the margins const ratioWithMargins = Math.min(availableWidth / imgWidth, availableHeight / imgHeight); const finalWidth = imgWidth * ratioWithMargins; const finalHeight = imgHeight * ratioWithMargins;
// Position the image on the PDF page (with margins) const x = marginLeft; const y = marginTop;
// Add the image to the PDF const addImageType = imageType === 'png' ? 'PNG' : 'JPEG'; pdf.addImage(imgData, addImageType as any, x, y, finalWidth, finalHeight);
// Overlay clickable link regions on the PDF // Approach: // 1) Walk every <a> tag inside the element // 2) Use getClientRects() to get a rect per visible line (handles wrapping) // 3) Map DOM CSS px -> canvas px (x canvasScale) -> PDF mm (x ratioWithMargins) // 4) Offset by the (x, y) margins const elementRect = element.getBoundingClientRect(); // Build an accurate CSSpx->Canvaspx ratio from the actual canvas output vs. element CSS size const elementCssWidth = Math.max(1, element.scrollWidth || elementRect.width); const elementCssHeight = Math.max(1, element.scrollHeight || elementRect.height); const cssToCanvasScaleX = imgWidth / elementCssWidth; const cssToCanvasScaleY = imgHeight / elementCssHeight;
// Canvaspx->PDFmm ratio from the final drawn size (keep X/Y separate to avoid floating-point drift) const canvasToPdfScaleX = finalWidth / imgWidth; const canvasToPdfScaleY = finalHeight / imgHeight;
// Helper: accumulate scroll offsets of all scrollable ancestors between the node and the root container (element) const getAccumulatedScrollOffset = (node: Element, root: Element) => { let cur: Element | null = node.parentElement; let accLeft = 0; let accTop = 0; while (cur && cur !== root && cur !== document.body && cur !== document.documentElement) { const style = window.getComputedStyle(cur); const overflowY = style.overflowY; const overflowX = style.overflowX; const isScrollableY = overflowY === 'auto' || overflowY === 'scroll'; const isScrollableX = overflowX === 'auto' || overflowX === 'scroll'; if (isScrollableY) accTop += (cur as HTMLElement).scrollTop; if (isScrollableX) accLeft += (cur as HTMLElement).scrollLeft; cur = cur.parentElement; } return { accLeft, accTop }; }; const anchors = Array.from(element.querySelectorAll('a[href]')) as HTMLAnchorElement[];
const isValidHref = (href: string | null): href is string => { if (!href) return false; const lowered = href.trim().toLowerCase(); return ( lowered.startsWith('http://') || lowered.startsWith('https://') || lowered.startsWith('mailto:') || lowered.startsWith('tel:') ); };
anchors.forEach((anchor) => { if (!isValidHref(anchor.getAttribute('href'))) return; const url = anchor.getAttribute('href') as string;
const clientRects = anchor.getClientRects(); if (!clientRects || clientRects.length === 0) return;
// Accumulated scroll (handles inner scrollable containers like antd Table) const { accLeft, accTop } = getAccumulatedScrollOffset(anchor, element);
for (let i = 0; i < clientRects.length; i += 1) { const rect = clientRects[i];
// DOM CSS px -> px relative to element // Plus scroll offsets of intermediate scrollable containers, mapped to the content origin const relLeftPx = (rect.left - elementRect.left) + accLeft; const relTopPx = (rect.top - elementRect.top) + accTop; const widthPx = rect.width; const heightPx = rect.height;
if (widthPx <= 0 || heightPx <= 0) continue;
// CSS px -> canvas px (actual ratio, avoids drift from relying on the configured scale alone) const leftCanvasPx = relLeftPx * cssToCanvasScaleX; const topCanvasPx = relTopPx * cssToCanvasScaleY; const widthCanvasPx = widthPx * cssToCanvasScaleX; const heightCanvasPx = heightPx * cssToCanvasScaleY;
// Canvas px -> PDF mm, plus the (x, y) margin offset const leftMm = x + leftCanvasPx * canvasToPdfScaleX; const topMm = y + topCanvasPx * canvasToPdfScaleY; const widthMm = widthCanvasPx * canvasToPdfScaleX; const heightMm = heightCanvasPx * canvasToPdfScaleY; const overlayHeightMm = heightMm * 2; // Double the height for a more forgiving click target
// Overlay the link annotation (any for cross-version type compat) try { (pdf as any).link(leftMm, topMm, widthMm, overlayHeightMm, { url }); } catch (e) { // Some versions also accept pdf.link(x, y, w, h, urlNumber) or textWithLink try { // Fallback: place an invisible text link (visually inert) const fontSize = 0.01; // Tiny font size, as invisible as possible const prevSize = (pdf as any).getFontSize?.() ?? 16; (pdf as any).setFontSize?.(fontSize); (pdf as any).textWithLink?.(' ', leftMm, topMm + fontSize, { url }); (pdf as any).setFontSize?.(prevSize); } catch (_) { // Ignore } } } });
if (isDownload) { // Save the PDF pdf.save(`${fileName}.pdf`); } // Return the image file (not the PDF); prefer the adaptive-compression blob if one exists const pngBlob: Blob = tentativePngBlob ?? await new Promise((resolve, reject) => { try { exportCanvas.toBlob((blob) => { if (blob) resolve(blob); else reject(new Error(`Failed to export ${imageType.toUpperCase()} blob`)); }, mime); } catch (e) { reject(e); } }); const pngFile = new File([pngBlob], `${fileName}.${imageType}`, { type: mime }); callback(pngFile); return pngFile; } catch (error) { console.error("Error generating PDF:", error); } finally { // Restore the anchors' temporary inline colors so the live page is unaffected try { restoreAnchorInlineStyles.forEach((fn) => fn()); } catch (_) { } // Undo the antd expand-icon fix try { cleanupExpandIconFixers.forEach((fn) => fn()); } catch (_) { } setIsLoading(false); // Done — success or failure, clear loading } return undefined; }, []); // Empty deps: the function never changes for the component's lifetime
// 4. Return the ref, the generator, and the loading state return { contentRef, generatePdf, isLoading };}; Generating PDFs with a Custom React Hook
https://www.mihouo.com/en/posts/front/react-hook-pdf-generation/