Date: 2026-09-06 11:35
Summary: URL-to-PDF dropped <head> stylesheets, so sites like 163.com looked unstyled; preview now uses a sandboxed iframe document and waits for CSS before capture.
Visibility: people
[question] 测试 https://www.163.com,页面排版问题,是不是css没生效
Tool links (English)
- https://onlinefreetools.org/tools/convert-html-to-pdf Chinese: https://onlinefreetools.org/zh/tools/convert-html-to-pdf
[try to solve]
Context
Loading https://www.163.com into Convert HTML to PDF produced a broken layout. The question was whether CSS was not applying.
Process
- Worker fetch of 163.com returned ~248 KB HTML with two absolute stylesheet URLs on
static.ws.126.netplus several<style>blocks — the fetch/rewrite step was not missing CSS. - The page then ran DOMPurify with
USE_PROFILES: { html: true }and wrote the result into a<div>. DOMPurify’s default is notWHOLE_DOCUMENT, so it returns body innerHTML only.<link rel="stylesheet">and most<style>live in<head>, so they never reached the preview. - Even if those tags were kept in a div, selectors like
html#ne_wrapwould not match. The preview is now an iframesrcdoc(sandboxallow-same-origin, no scripts) so the captured page is a real document with its own head. - html2canvas then threw
Unsupported image typeon 163’s webp/svg/ico backgrounds.oncloneclears non png/jpeg/gif background images and similar<img>sources so layout CSS still applies. - Local check after the fix: 163 preview has 2 stylesheets,
html#ne_wrap[phone=1], navdisplay:block/ height 45px; PDF blob ~2.3 MB. Sample HTML still converts.
Root cause / analysis
CSS was fetched and rewritten to absolute URLs, then stripped at sanitize time. 163.com is also a JS-built homepage: without running scripts, article modules stay empty even when CSS loads. That remaining gap is expected (scripts stay blocked for XSS).
Solution
Sanitize with WHOLE_DOCUMENT, allow link/meta/base, write into a sandboxed iframe, wait for stylesheets, then html2pdf the iframe body. Strip html2canvas-unsupported image types in onclone.
Notes / boundaries
- Do not execute the source page’s JavaScript.
- A4 + html2canvas cannot match a live desktop tab for infinite-scroll news homes.
- Regexes inside the Page.ts template string must use double backslashes (
\\.), or the prerendered script is a SyntaxError.
[actions]
src/pages/convertHtmlToPdfPage.ts: iframe preview, WHOLE_DOCUMENT sanitize, wait for CSS, onclone image stripsrc/site/tool-catalog.d/convert-html-to-pdf.json:updatedAtwrangler.jsonc:PAGES_CACHE_VERSION4.25