OnlineFreeTools.org
  • Home
  • Tools
    Health & body →
    BMI Calculator — How to Calculate Body Mass IndexBMR & TDEE Calculator — How to Calculate Daily CaloriesBody Fat Calculator — How to Estimate Body Fat PercentageHeart Rate Zone CalculatorIdeal Weight Calculator — How to Estimate Ideal Body WeightMacro Calculator — Calories to Protein Carb Fat GramsOne-Rep Max Calculator (Epley)Pace Calculator — min/km and Speed
    Personal money →
    CAGR Calculator — How to Calculate Compound Annual Growth RateCompound Interest Calculator — How to Calculate Future ValueDebt Payoff Calculator — Months to Clear a BalanceDiscount Calculator — How to Calculate Sale PriceEMI Calculator — How to Calculate Loan PaymentsInflation Calculator — Future Purchasing PowerPercentage Change Calculator — From Old Value to NewPresent Value Calculator — PV and FV ModesRule of 72 Calculator — Years to DoubleSalary to Hourly Calculator — How to Convert Pay RatesTip Calculator — Tip Amount and SplitVAT / GST Calculator — Add or Extract Tax
    Business finance →
    Create a budget spreadsheetCreate an Excel timesheetCreate an invoice spreadsheetBreak-Even Calculator — How to Calculate Break-Even PointContribution Margin Calculator — Price Minus Variable CostGross Margin Calculator — How to Calculate Gross MarginIRR Calculator — Internal Rate of ReturnHow to Calculate Marginal Revenue — MR Calculator (ΔTR / ΔQ)Markup Calculator — How to Calculate Markup PercentageHow to Calculate NPV — Net Present Value CalculatorPayback Period Calculator — Years to Recover InvestmentProfit Margin Calculator — Net or Operating MarginROI Calculator — How to Calculate Return on Investment
    Math & stats →
    Confidence Interval Calculator — How to Calculate a CIExponent Calculator — How to Calculate PowersGPA Calculator — How to Calculate Weighted GPALogarithm Calculator — How to Calculate LogsMean Calculator — Average of a Number ListMedian and Mode CalculatorP-Value Calculator — How to Calculate a P-ValuePermutation and Combination CalculatorQuadratic Equation Solver — Roots and DiscriminantSample Size Calculator — How to Estimate Required nScientific Notation Calculator — How to Convert Scientific NotationSignificant Figures Calculator — How to Count and Round Sig FigsStandard Deviation Calculator — How to Calculate SD and VarianceZ-Score Calculator — How to Calculate a Standard Score
    Geometry & measure →
    Aspect Ratio Calculator — How to Calculate and Scale RatiosCircle Calculator — Area and CircumferenceGradient Calculator — Multivariable ∇f (Partial Derivatives)Pythagorean Theorem Calculator — How to Find a Missing SideSlope Calculator — How to Calculate Slope Between Two PointsTriangle Area CalculatorVolume Calculator — Box and SphereUnit Converter — Length / Mass / Temperature / Area / Volume / Speed
    Science & physics →
    Acceleration Calculator — Change in VelocityDensity Calculator — Mass over VolumeOhm’s Law Calculator — Resistance and PowerVelocity Calculator — Distance over TimeMeasuring Magnetic Fields — Field strength calculator
    Home & DIY →
    Concrete Calculator — How to Estimate Concrete VolumePaint Calculator — How to Estimate Paint NeededTile Calculator — How to Estimate Tile QuantitySquare Feet to Square Meters — Area Converter for Homes & Renovation
    Time & calendar →
    Age Calculator — Chronological Age from BirthdateDate Difference Calculator — Days and WeeksTime Zone Converter — Compare One Moment WorldwideUnix Timestamp Converter — Epoch ↔ Readable Time
    PDF & docs →
    Add a visible integrity mark to a PDFAdd text to a PDF fileBatch compress PDFs for emailInspect PDF/A indicatorsCombine files into one PDFCompare two PDFsReduce PDF file sizeConvert HTML to PDFExport PDF text to DXF for AutoCADConvert PDF to PDF/AConvert Word document to PDFCreate a PDF formCrop PDF — Trim Page Margins in Your BrowserEdit PDF form fieldsEdit PDF text onlineExtract text from a PDFFill out a PDF formMake a PDF fillableMake a PDF flipbookCombine PDF files into oneOpen a PDF in the browserOrganize PDF — Reorder or Remove Pages in Your BrowserAdd Page Numbers to PDF — In Your BrowserPDF Page to Image Sizes — Multi-Size Export PackConvert PDF pages to JPGPDF to Markdown — Extract Text for Notes in Your BrowserPDF Watermark — Stamp Text on Every Page in Your BrowserPrint a PDFPassword-protect a PDFRotate PDF — Fix Page Orientation in Your BrowserSign a PDF documentSplit my PDFTurn PDF into an editable text documentTurn PDF into Word documentUnlock my PDFWrite a PDF document online
    Image & media →
    Add Text Watermark to Photo — Local Browser ToolAmazon main image sizeApple-touch-icon 180×180Batch watermark product photosBulk compress PNG imagesBulk compress product photos (JPEG, PNG, WebP)Bulk convert images to JPGBulk convert images to PNGBulk convert images to WebPExtract Colors from Image — Palette & Click PickFlip Image — Mirror Horizontally or VerticallyAdd Border to Image — Color & Width OnlineImage Compressor — Shrink photos on your deviceCrop & Resize Image — Local Aspect PresetsPhoto EXIF Viewer & Remover — GPS, Camera & Local StripImage Format Converter — PNG JPEG WebP AVIF BMP GIF ICO SVGConvert Image to Grayscale — Black & White OnlineMerge Images — Combine Photos into One CollageImage Optimizer — Smaller files with on-device encodersOverlay Images — Put a Logo on a PhotoImage to Base64 Converter — Encode & Decode LocallyImages to GIF — Make an Animated GIF LocallyTurn JPG into PDFImages to PowerPoint — Photos to PPTX SlidesImages to Word — Build a DOCX from PhotosInstagram post sizeInstagram story sizeiOS app icon sizeiPhone 6.9 screenshot sizeLinkedIn banner sizeOpen Graph image sizeSVG optimizerYouTube thumbnail size
    Design & brand →
    Generate Brand Color Scale — 50–950 Palette & CSS TokensBrand Style Guide — Generate a Modular Draft You Can EditSmart Website Color Scheme — Semantic CSS TokensWCAG Contrast Checker — AA/AAA Ratio Online
    SEO & growth →
    Check if a URL is blocked by robots.txtCheck SSL certificate expirationtool_cwv_titleFind and validate XML sitemaptool_hreflang_titleIndexNow — Submit URLs to Bing without waiting for crawltool_serp_titletool_meta_titletool_onpage_titletool_og_titletool_robots_titletool_schema_titletool_sitemap_titleSPF DKIM DMARC checkertool_utm_titleValidate security.txt
    Network & IP →
    Add WWW to DNS — Point www at your apex domainAWS VPC CIDR planner — Split a VPC into AZ subnetsCIDR cheat sheet — Click a prefix to see mask and hostsCIDR to IP range — Expand a prefix into usable addressesDomain Lookup — Check DNS Records & Registration OnlineWhat Is My IP Address — See Your Public IP (IPv4 or IPv6)IP range to CIDR — Turn start–end addresses into prefix listsIPv6 CIDR calculator — Expand a prefix into its address rangePrivate CIDR ranges — Check if an IP or prefix is private or special-useTerraform cidrsubnet — Get the child CIDR Terraform would returntool_headers_title
    Dev & data →
    Base64 Encode & Decode — Convert Text in Your BrowserChatGPT export to MarkdownCSV ↔ JSON Converter — Convert tables in your browsercurl to fetchCopy common Excel formulasHTML Entity Encoder & Decoder — Escape, Unescape & LocalJSON Schema Validator — See path errors on your deviceJWT Decoder — Read Header & Payload Locally (No Verify)tool_markdown_titleWrap a formula with IFNAWrite a COUNTIF formula in ExcelWrite an IFS formula in ExcelWrite a nested IF formula for ExcelYAML ↔ JSON Converter — Convert configs in your browser
    AI prompt tools →
    Android prompt builder — Local + Optional AIFilm prompt builder — Local + Optional AIiOS prompt builder — Local + Optional AIMidjourney prompt builder — Local + Optional AIProduct design prompt builder — Local + Optional AIPrompt template builder — Local + Optional AIShort drama prompt generator — Local + Optional AISketch.app prompt generator — Local + Optional AIWriting prompt generator — Local + Optional AI
    Text compare →
    Compare two text files onlineCompare two Word documents for differencesExcel compare filesJSON diff checker onlineCheck difference between two texts
    Security & IDs →
    Batch checksum release filesFile Hash Checker — Verify Digests in Your BrowserFile metadata analyzerRandom Password Generator — Create Passwords LocallyUUID & ULID Generator — Create IDs in Your Browser
    Files & archives →
    Archive Extractor Online — Open Compressed Files in Your BrowserCreate zip fileMagnet Link Decoder — Parse Info Hash and Trackers LocallyUnzip File Online — Extract ZIP Files in Your Browser
  • Tool topics
  • Tool types
  • Dev Logs
☕ Buy me a coffee

Navigation

Home

HTML→PDF (and Word→PDF) sample conversion crashed because html2pdf.min.js needs global jsPDF; switched to the self-contained bundle. | Dev Logs

Back to Logs

Date: 2026-09-06 09:39 Summary: HTML→PDF (and Word→PDF) sample conversion crashed because html2pdf.min.js needs global jsPDF; switched to the self-contained bundle. Visibility: people

[question] http://127.0.0.1:8788/zh/tools/convert-html-to-pdf 出现 ”处理失败,请重试。“

Tool links (English)

  • https://onlinefreetools.org/tools/convert-html-to-pdf
  • https://onlinefreetools.org/tools/convert-word-document-to-pdf Chinese: https://onlinefreetools.org/zh/tools/convert-html-to-pdf

[try to solve]

Context

Opening /zh/tools/convert-html-to-pdf on the local preview (http://127.0.0.1:8788) showed the generic Chinese error「处理失败,请重试。」on page entry. The tool auto-runs loadSample(), so the failure was the default conversion path, not a bad user file. The same error string is the i18n fallback tool_convert_html_to_pdf_err_convert; the real exception was swallowed in the click handler.

The 2026-09-06 Chinese auto-QA pass had already recorded this slug (and convert-word-document-to-pdf) as a wiring bug, not a flaky CDN: the script returned HTTP 200, then typeof html2pdf === 'undefined', with a console error Cannot read properties of undefined (reading 'jsPDF').

Process

  1. Confirmed the visible string maps to tool_convert_html_to_pdf_err_convert in the zh shard.

  2. Read src/pages/convertHtmlToPdfPage.ts. The extra-body scripts loaded:

    • pdf-lib.min.js (unused leftover from the PDF-scene generator)
    • DOMPurify
    • https://cdn.jsdelivr.net/npm/html2pdf.js@0.10.2/dist/html2pdf.min.js
  3. Fetched that min file from jsDelivr. The UMD wrapper is:

    e.html2pdf = o(e.jspdf, e.html2canvas)

    So html2pdf.min.js is the library-only build. It expects window.jspdf and window.html2canvas already on the page. The factory then reads jspdf.jsPDF. When window.jspdf is missing, evaluation throws Cannot read properties of undefined (reading 'jsPDF') and never assigns window.html2pdf.

  4. Compared file sizes: html2pdf.min.js ≈ 72 KB vs html2pdf.bundle.min.js ≈ 885 KB. The bundle does not use the peer UMD factory; it inlines jsPDF and html2canvas.

  5. convert-word-document-to-pdf loaded the same non-bundle URL after mammoth, so the sample .docx path failed the same way (often shown as「无法读取该 .docx。」because the catch maps html2pdf to err_load).

  6. Switched both pages to html2pdf.bundle.min.js@0.10.2, added a typeof html2pdf === 'undefined' guard on the HTML page, and mapped html2pdf / dompurify to the load-fail copy instead of the generic convert-fail string.

  7. Bumped PAGES_CACHE_VERSION 4.14 → 4.15 so local Cache API would not keep serving the old HTML (s-maxage is 86400 seconds). Prerendered both slugs, gzipped, uploaded to the local R2 bucket, restarted wrangler on 8788 with --no-build --no-seed-r2.

  8. Playwright (headless Chrome) against http://127.0.0.1:8788/zh/tools/convert-html-to-pdf: typeof html2pdf === 'function', no pageerror, no danger text, status「完成」, download button enabled. The Word page passed the same check.

Root cause / analysis

html2pdf.js publishes two browser builds:

File Role
dist/html2pdf.min.js UMD that requires global jspdf + html2canvas
dist/html2pdf.bundle.min.js Same API, dependencies bundled

The PDF-scene page generator wired the smaller file without loading the peers. The network looked healthy (jsDelivr 200), so this was easy to misread as a conversion bug. jsPDF 2.x also attaches as window.jspdf.jsPDF, not window.jsPDF; even loading a wrong jsPDF global would still throw. The bundle avoids that namespace dance.

Solution

Use html2pdf.bundle.min.js on both HTML→PDF and Word→PDF. Keep the version pin at 0.10.2. After deploy, production still needs the usual upload:r2 + git push so R2 HTML and Worker PAGES_CACHE_VERSION 4.15 ship together.

Local verification (Playwright, ~8s after domcontentloaded):

  • /zh/tools/convert-html-to-pdf — status 完成, download enabled, no jsPDF exception
  • /zh/tools/convert-word-document-to-pdf — same

Notes / boundaries

  • Complex print CSS, remote fonts, and cross-origin images can still render poorly; html2canvas snapshots the preview DOM. The tool does not fetch a live URL.
  • Chinese How / FAQ still carry PDF-scene template leftovers (「选择 PDF 或粘贴内容」, OCR FAQ). Those are copy issues, not this crash.
  • pdf-lib remains loaded on the HTML page but is unused; left in place to keep this fix scoped to the jsPDF crash.
  • Production visitors will keep the old script until R2 HTML is uploaded and PAGES_CACHE_VERSION 4.15 is live.

Follow-up: other PDF tools

A full src/pages/*Page.ts scan shows only these two pages import html2pdf.js. The rest of the PDF cluster loads pdf-lib@1.17.1 (self-contained UMD) or pdf-lib-with-encrypt@1.2.1 for protect/unlock. They never touch window.jspdf, so they cannot hit this crash.

The 2026-09-06 auto-QA still lists three other sample failures (unlock-pdf, add-digital-signature-to-pdf, turn-pdf-into-word-document). Those are different pipelines (encryption sample, integrity-mark hash, pdf.js text extract), not a missing jsPDF global.

[actions]

  • src/pages/convertHtmlToPdfPage.ts: load html2pdf.bundle.min.js; guard missing html2pdf / DOMPurify
  • src/pages/convertWordDocumentToPdfPage.ts: same bundle URL
  • wrangler.jsonc: PAGES_CACHE_VERSION 4.14 → 4.15
  • catalog updatedAt via tool:touch for both slugs; prerender + gzip + local R2 upload
OnlineFreeTools.org · Learning project · Iterating
About·Privacy·Terms·Contact·GitHub