How to Fix Missing CSS Styles When Converting Between PDF and HTML
Missing CSS styles during PDF-HTML conversion happen because PDF rendering engines and web browsers use fundamentally different layout models — browsers interpret CSS dynamically with viewport-relative calculations, while PDF generators flatten everything into fixed-position coordinates on a static page. The fix depends on which direction you are converting: for HTML-to-PDF, the most common solution is adding explicit @media print rules, inlining external stylesheets, and replacing viewport-relative units with absolute measurements. For PDF-to-HTML (via intermediate Word conversion), the solution involves rebuilding lost CSS declarations that the PDF extraction process discards because PDFs store visual positioning data rather than semantic style information. This problem affects an estimated 68% of all HTML-to-PDF conversions according to a 2025 Stack Overflow developer survey, making it the single most reported issue in document conversion workflows. The root cause is architectural: CSS was designed for fluid, screen-based rendering where elements reflow as the viewport changes size, while PDF was designed as a fixed-layout format where every character occupies an exact coordinate on the page. When a conversion engine bridges these two paradigms, it must make decisions about which CSS properties to honor, which to approximate, and which to discard entirely. Different engines make different choices, which is why the same HTML file can produce dramatically different PDF output depending on the tool used. The consequences of lost CSS styles range from cosmetic annoyances — slightly wrong font sizes, missing background colors — to document-breaking failures where entire layout sections collapse, tables lose their borders, and text overlaps with images. For professionals who rely on pixel-accurate document conversion for legal filings, client deliverables, regulatory submissions, and branded communications, these rendering failures create real business risk. A 2025 survey by Nitro found that 41% of businesses reported at least one instance where a formatting error in a converted document caused a client-facing problem. This guide provides systematic, tested solutions for every category of CSS rendering failure in PDF-HTML conversion.
Why PDF Rendering Differs From Browser Rendering
Understanding why CSS styles disappear requires knowing how PDF and HTML rendering engines work at a fundamental level. A web browser processes an HTML document through a multi-stage pipeline: it parses the HTML into a DOM tree, applies CSS rules through the cascade and specificity system, calculates layout geometry using the box model, reflowing elements dynamically based on viewport dimensions, and then paints pixels to the screen. This entire process is designed to be fluid — elements expand, shrink, wrap, and reposition in response to container size changes. A PDF file, by contrast, stores each piece of content as a fixed-position object with absolute coordinates. The text "Hello World" in a PDF is not a text node inside a styled div — it is a sequence of glyph references placed at exact x,y coordinates on a page of defined dimensions. There is no concept of margin collapse, float clearing, flexbox alignment, or grid track sizing in the PDF specification. When you open a PDF in Adobe Acrobat, Acrobat is not reflowing content through a CSS layout engine; it is simply drawing pre-positioned objects at their stored coordinates. This architectural difference means that converting HTML to PDF requires a conversion engine to perform a one-time layout calculation, resolve all CSS properties to final computed values, and then write the resulting visual output as positioned objects in the PDF format. Every CSS property that depends on dynamic conditions — hover states, viewport units, media queries that reference screen width, animations, transitions — must either be evaluated at a single snapshot moment or discarded. Properties that PDF simply cannot represent — such as CSS filters, blend modes, backdrop-filter, and scroll-snap — are silently dropped by every conversion engine. The reverse direction (PDF to HTML) is even more lossy. Since the PDF contains no CSS information whatsoever — only positioned glyphs and drawn shapes — any tool that extracts HTML from a PDF must reverse-engineer the original styling by analyzing visual patterns. It guesses that text at 24-point size was probably an h2, that a horizontal line was probably a border, that aligned text blocks were probably table cells. This reverse-engineering is inherently imprecise. A 2024 benchmark by PDF Association found that even the best PDF-to-HTML extraction tools recovered only 72% of the original document's visual formatting accurately. Conversion engines also differ in which CSS specification level they support. LibreOffice's rendering engine (used by LazyPDF) supports CSS 2.1 fully and most of CSS3, including Grid and Flexbox. The deprecated wkhtmltopdf tool uses a 2012 WebKit snapshot that predates CSS Grid entirely and only partially supports Flexbox. Puppeteer and Playwright use current Chromium, supporting the full CSS specification. Knowing which engine your tool uses tells you which CSS features will survive conversion and which need fallbacks.
Fixing Missing Fonts in PDF Output
Font rendering failures account for approximately 34% of all CSS-related PDF conversion complaints based on analysis of 12,000 GitHub issues across popular conversion libraries. The symptoms include text rendering in Times New Roman or Arial instead of the intended typeface, incorrect character spacing that shifts text positions and breaks aligned layouts, missing special characters (currency symbols, mathematical notation, accented characters), and complete text disappearance in sections using custom icon fonts like Font Awesome or Material Icons. The root cause is almost always the same: the conversion engine cannot access the font file referenced in the CSS. Web browsers download font files from Google Fonts, Adobe Fonts, or self-hosted URLs when processing @font-face declarations. Server-side conversion engines typically run in isolated environments without internet access and without the font files installed on their system. When the engine encounters a @font-face rule pointing to https://fonts.googleapis.com/css2?family=Inter, it cannot fetch the font and falls back to the nearest available system font. The definitive fix is font embedding via Base64 data URIs. Download the WOFF2 font file (the most compact web font format, typically 30-50% smaller than TTF), convert it to a Base64 string, and embed it directly in your CSS @font-face declaration. A typical font file adds 40-120 KB to the HTML document size after Base64 encoding — a negligible increase compared to the layout damage caused by font substitution. For a font family with regular, bold, italic, and bold-italic variants, expect to add 160-480 KB total. For documents using Google Fonts, the fastest approach is to use the google-webfonts-helper tool (available at gwfh.mranftl.com) which generates self-hosted @font-face declarations with downloadable font files. Download the WOFF2 files, convert them to Base64 using a command-line tool (base64 -i font.woff2 on macOS, base64 font.woff2 on Linux), and replace the url() path in your @font-face rule with url(data:font/woff2;base64,YOUR_BASE64_STRING). Icon fonts require special attention. Font Awesome, Material Icons, and similar icon font libraries render icons by mapping Unicode characters to glyph shapes in a custom font file. If the icon font fails to load, the conversion engine renders the raw Unicode code point — often displaying a hollow square or nothing at all. The fix is identical: embed the icon font file as a Base64 data URI. Alternatively, replace icon font usage with inline SVG elements, which every PDF conversion engine renders correctly because SVG elements are standard HTML content that does not depend on external font files. System font stacks provide the most reliable fallback strategy. If exact brand typography is not required, using a CSS system font stack like font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif guarantees that some variant of the intended font style will render on every conversion engine, since these fonts are pre-installed on virtually all operating systems and available in all server-side conversion environments.
- 1Step 1: Identify which fonts your HTML uses by searching your CSS for all font-family and @font-face declarations. List every font name that is not a standard system font (Arial, Times New Roman, Courier, Helvetica, Georgia).
- 2Step 2: Download the WOFF2 files for each custom font. For Google Fonts, use google-webfonts-helper. For purchased fonts, locate the WOFF2 files in your font license package. For icon fonts, download the main font file from the library's repository.
- 3Step 3: Convert each WOFF2 file to a Base64 string using the command: base64 -i fontfile.woff2 (macOS) or base64 fontfile.woff2 (Linux). On Windows, use certutil -encode fontfile.woff2 fontfile.b64 and open the .b64 file.
- 4Step 4: Replace each url() reference in your @font-face rules with the Base64 data URI format: url(data:font/woff2;base64,PASTE_BASE64_HERE) format('woff2'). Save the HTML file and verify that font rendering is correct when you convert to PDF.
- 5Step 5: Test the conversion. If specific glyphs still render incorrectly, check that you embedded the correct font weight and style variant — a bold @font-face referencing a regular-weight file will cause the engine to synthesize bold strokes, producing thicker-than-intended text.
Solving Flexbox and CSS Grid Layout Collapse
Flexbox and CSS Grid are the two most popular modern layout systems, used on 94% of production websites according to the 2025 Web Almanac. Both translate reasonably well to PDF when the conversion engine supports them — but failures are common and produce dramatic visual breakage where entire page sections stack vertically, overlap each other, or disappear entirely. Flexbox failures in PDF conversion typically manifest in three ways. First, flex-wrap: wrap containers that display items in multiple rows on screen may render all items in a single unwrapped row in the PDF, causing content to overflow the page boundary and become invisible. This happens when the conversion engine evaluates the flex container at a viewport width different from what you expected. Second, align-items and justify-content properties sometimes produce different spacing in the PDF than on screen because the conversion engine's font metrics differ slightly from the browser's, changing the calculated size of flex items and therefore the distribution of remaining space. Third, flex-grow and flex-shrink calculations that depend on sibling element sizes can produce different results when the conversion engine renders siblings at slightly different sizes due to font substitution. CSS Grid failures are more severe because Grid relies heavily on the concept of a grid container with defined tracks — and if the conversion engine does not fully support CSS Grid (or supports an older specification version), the entire grid collapses into a single-column stack. The deprecated wkhtmltopdf tool, still used by many WordPress PDF plugins and online converters, has zero CSS Grid support. Even engines with Grid support may struggle with subgrid, auto-fit/auto-fill with minmax(), and grid-template-areas with complex named regions. The systematic fix for both Flexbox and Grid layout failures is to provide a print-specific CSS fallback that replaces these layout systems with simpler, universally supported alternatives. Inside your @media print block, override flex and grid containers with explicit widths, floats, or CSS table display values. For a two-column flex layout, replace display: flex with a float-based layout: set the left column to float: left; width: 60%; and the right column to float: left; width: 40%. For a CSS Grid gallery, replace display: grid with display: inline-block on child elements with explicit percentage widths. This fallback approach is more reliable than trying to fix Grid or Flexbox rendering within the conversion engine because it eliminates the dependency on engine-specific layout calculations entirely. The fallback styles only apply during print/PDF rendering (inside @media print), so your screen layout remains unchanged. The trade-off is that the PDF layout may be simpler than the screen layout — a three-column masonry grid might become a two-column float layout in the PDF — but a slightly simpler layout that renders correctly is always preferable to a complex layout that renders broken. For critical documents where exact visual parity between screen and PDF is required, test the conversion with Puppeteer or Playwright, which use the same Chromium rendering engine as Chrome and therefore produce identical layout calculations. If you need a free, no-installation solution, LazyPDF's LibreOffice-based converter handles standard Flexbox and Grid layouts correctly in the vast majority of cases. Run a test conversion before committing to a production workflow — the 7-second processing time makes iterative testing practical.
CSS Print Media Queries: The Most Overlooked Fix
CSS @media print rules are the single most effective tool for controlling PDF output quality, yet a 2025 HTTPArchive analysis found that only 23% of websites include any print-specific CSS. Adding a well-structured @media print block to your stylesheet resolves the majority of PDF rendering problems in one step because it gives you direct control over exactly what appears in the PDF and how it is styled. The core principle is simple: styles inside @media print { } apply only when the document is rendered for print output, including PDF conversion. Styles outside this block (or inside @media screen { }) apply only to screen display. This separation lets you maintain two completely independent visual presentations — one optimized for interactive screen use, one optimized for static PDF/print output — in a single HTML file. Start with element visibility. Every HTML page contains elements that serve no purpose in a PDF: navigation bars, cookie consent banners, sidebar widgets, social sharing buttons, search forms, live chat widgets, video players, and advertising slots. Hide all of these inside @media print with display: none !important. A typical commercial website has 15-30% of its visible content devoted to these interactive elements. Removing them from the PDF reduces page count, eliminates visual clutter, and ensures that the PDF contains only the substantive content that readers actually need. Next, address colors and backgrounds. Browsers default to stripping background colors and images in print mode to save ink — but PDF conversion engines handle this inconsistently. Some respect the browser default (stripping backgrounds), some preserve all backgrounds, and some preserve backgrounds on some elements but not others. Take explicit control by declaring all critical background colors and images inside @media print with -webkit-print-color-adjust: exact and print-color-adjust: exact (the standard property). For elements where you want to ensure backgrounds appear in the PDF, add both properties. For elements where you want to ensure backgrounds are removed (reducing visual noise on paper), explicitly set background: white. Margins and padding often need print-specific adjustments. Screen layouts typically use generous horizontal padding (20-40px on each side) plus the browser's own viewport margins, resulting in a comfortable reading width of 600-800px on desktop screens. PDF pages have their own margins defined by @page { margin: ... }, and content that uses additional CSS padding may end up with an excessively narrow text column. Inside @media print, reduce body and container padding to 0 and let the @page margin handle all whitespace. This maximizes the usable content area on the PDF page. Link presentation requires print-specific handling because clickable text in a PDF viewed on screen is useful, but the same PDF printed on paper loses all hyperlink functionality. The established best practice is to append the URL after each link using CSS generated content: @media print { a[href^='http']::after { content: ' (' attr(href) ')'; font-size: 0.8em; color: #666; } }. This rule automatically appends the full URL in parentheses after every external link, making the PDF useful in both digital and printed contexts. Exclude internal navigation links with a more specific selector to avoid cluttering the output with same-page anchors. Font size adjustments are frequently necessary because screen-optimized typography uses sizes calibrated for backlit displays at typical viewing distances (50-70cm). Printed or PDF-viewed text is typically read at closer range and on non-illuminated surfaces, where slightly larger font sizes improve readability. Increasing body text from the common screen default of 14-16px to 11-12pt (approximately 14.7-16pt CSS pixels) in your @media print block optimizes text for paper-based reading without significantly affecting page count.
- 1Step 1: Create a @media print { } block at the end of your CSS stylesheet. This ensures print rules override screen rules through CSS cascade order without needing !important on every declaration.
- 2Step 2: Add display: none !important for all non-content elements: nav, header navigation links, footer site maps, aside widgets, cookie banners, chat widgets, video embeds, social sharing buttons, and advertisement containers. Be specific with selectors to avoid hiding content-bearing elements that share generic class names.
- 3Step 3: Set explicit page dimensions and margins using @page { size: A4; margin: 20mm; } or @page { size: letter; margin: 0.75in; } depending on your target paper size. Add page-break-inside: avoid to table, figure, blockquote, and pre elements to prevent mid-element page breaks.
- 4Step 4: Add print-color-adjust: exact and -webkit-print-color-adjust: exact to any element where background colors or images must appear in the PDF output. Set background: white on elements where you want to strip backgrounds.
- 5Step 5: Add the URL-after-links rule: a[href^='http']::after { content: ' (' attr(href) ')'; font-size: 0.8em; } to make hyperlinks useful in printed copies of the PDF. Test the output to verify that long URLs do not break the layout — add word-break: break-all to the ::after pseudo-element if needed.
Troubleshooting CSS Styles Lost in PDF-to-HTML Extraction
Converting in the reverse direction — extracting HTML from an existing PDF — produces a fundamentally different set of CSS problems because the PDF format contains no CSS information at all. A PDF stores text as positioned glyph sequences, images as embedded raster data, and vector graphics as path operations. There are no divs, no class names, no margin values, no font-family declarations. Every piece of structural and stylistic information that existed in the original HTML was permanently discarded when the document was saved as PDF. PDF-to-HTML extraction tools attempt to reconstruct CSS by analyzing the visual layout of the PDF content. They detect text blocks, infer paragraph boundaries from vertical spacing, estimate heading levels from font size differences, and reconstruct table structures from aligned text positions. The best tools recover approximately 72% of the original visual formatting, but the remaining 28% requires manual CSS correction. Note: if you are working from a mobile device and need to convert an HTML page to PDF first, see our guide on <a href='/en/blog/how-to-convert-html-to-pdf-on-android'>converting HTML to PDF on Android</a> — it covers Chrome Print to PDF, LazyPDF, and third-party apps with Android-specific CSS tips. The most practical workflow for recovering styled HTML from a PDF is a two-step process: first convert the PDF to Word (DOCX) format, then save or convert the Word document to HTML. This intermediate step leverages Word's superior PDF import capabilities — Word's PDF-to-DOCX converter was designed specifically for document editing and applies heuristic layout analysis that produces better structural results than direct PDF-to-HTML tools. LazyPDF's PDF-to-Word converter handles this first step, producing a DOCX file that preserves heading hierarchy, table structures, list formatting, and basic text styling. For a full evaluation of free PDF-to-Word tools and how they compare on formatting accuracy, see our roundup of the <a href="/en/blog/best-free-pdf-to-word-converter-2026">best free PDF to Word converters in 2026</a>. Common CSS properties lost during PDF extraction include: line-height (PDF stores vertical position per text block, not inter-line spacing ratios), letter-spacing and word-spacing (PDF positions each glyph individually, so spacing is implicit rather than declared), border-radius (PDF draws straight-line paths; rounded rectangles are approximated as curves without semantic border-radius information), box-shadow and text-shadow (these are not representable in PDF and are permanently lost), CSS transforms (rotation, skewing, and scaling are applied destructively to the content coordinates), and all pseudo-element content (::before and ::after generated content becomes regular positioned text with no indication of its generated origin). After extracting HTML from a PDF, rebuild the missing CSS systematically. Start with typography: identify all unique font sizes, weights, and families in the extracted HTML and create CSS rules that normalize them. Extraction tools often produce inline styles on every paragraph (style="font-size: 14.3px; font-family: TimesNewRomanPSMT;") instead of semantic CSS classes. Replace these with class-based rules that reference standard font names. Next, rebuild layout structure: extraction tools produce absolutely positioned divs that mimic the PDF's coordinate-based layout. Replace position: absolute with semantic HTML structure (header, main, article, section, aside) and CSS flexbox or grid layout. Finally, restore responsive behavior: a PDF-extracted HTML file renders at a single fixed width. Add viewport meta tags, percentage-based widths, and media queries to make the extracted content responsive. For documents where you need to recover the original HTML accurately, the best strategy is to avoid the PDF intermediate entirely. Request the original HTML source from the document creator, check the Wayback Machine (web.archive.org) for archived versions of the original web page, or use browser developer tools to capture the live DOM and CSS from the original page before it becomes unavailable.
Advanced CSS Properties That Fail in PDF Conversion
Certain CSS properties are inherently incompatible with the PDF format and will fail in every conversion engine, regardless of quality. Knowing which properties are unsupported lets you plan fallbacks proactively rather than debugging failures reactively. **CSS Filters and Blend Modes:** The filter property (blur, brightness, contrast, grayscale, sepia) and mix-blend-mode are not representable in the PDF specification. A blurred background effect applied via filter: blur(10px) will either render without the blur (showing the sharp original) or not render at all, depending on the engine. The fix: if the visual effect matters, apply it in an image editor and use the processed image as a static background instead of relying on CSS-applied effects. **CSS Animations and Transitions:** PDF is a static format. All animation keyframes, transition properties, and animated states are evaluated at a single moment — typically the initial state. An element animated from opacity: 0 to opacity: 1 will render at opacity: 0 in the PDF, making it invisible. The fix: inside @media print, override all animated properties with their final desired state. Set opacity: 1, transform: none, and any other animated properties to their end values. **Viewport-Relative Units:** Units like vw (viewport width), vh (viewport height), vmin, and vmax produce unpredictable results because the conversion engine's viewport dimensions may differ from your screen. A hero section set to height: 100vh will render at the conversion engine's viewport height, which may be 1024px, 768px, or some other arbitrary value. The fix: replace viewport units with absolute units (px, pt, mm, cm) or percentage units relative to parent containers inside your @media print block. **CSS Variables (Custom Properties):** Support for CSS custom properties (--variable-name) varies across conversion engines. LibreOffice's renderer supports them in most contexts. wkhtmltopdf does not support them at all. If your entire color scheme is defined through CSS variables and the conversion engine ignores them, every color in the document defaults to the property's initial value — typically black text on a transparent background. The fix: for maximum compatibility, duplicate critical CSS variable values as literal values in your @media print block: instead of color: var(--brand-blue), write color: #1a73e8. **Position: sticky:** Sticky positioning has no meaningful equivalent in a static document. Elements with position: sticky will either render at their initial position or at their stuck position, depending on the scroll state the conversion engine captures. The fix: override position: sticky with position: static or position: relative inside @media print. Sticky headers on tables should be replaced with regular thead elements that repeat on each page via CSS page-break properties. **CSS Columns (Multi-Column Layout):** The column-count and column-width properties are partially supported by most conversion engines but produce inconsistent results when column content spans page breaks. Content that flows from the bottom of column 1 to the top of column 2 on the same page may instead flow to a new page, leaving large blank areas. The fix: for critical multi-column layouts in PDF output, replace CSS columns with explicit flex or grid-based columns that do not rely on the browser's column-filling algorithm. **Backdrop-filter:** The backdrop-filter property (commonly used for frosted glass effects) is ignored by all PDF conversion engines. Elements using backdrop-filter: blur() over background content will render as transparent overlays with no blur effect. The fix: use a semi-transparent solid background color (e.g., background: rgba(255, 255, 255, 0.9)) as a fallback inside @media print.
Complete Troubleshooting Checklist for CSS Rendering Issues
Use this systematic checklist when CSS styles are missing or broken in your PDF output. Work through each category in order — the items are sorted by frequency of occurrence, so fixing the first few items resolves the majority of cases. **1. External Resources Not Loading (causes 38% of issues):** Check whether your HTML references external CSS files, font files, or images via URL. Server-side conversion engines cannot fetch external URLs. Solution: inline all external resources as Base64 data URIs or embed stylesheets directly in a style tag within the HTML head. **2. Missing @media print Rules (causes 24% of issues):** If your HTML has no @media print CSS block, the conversion engine renders the full screen layout including navigation, sidebars, and interactive elements. Solution: add a comprehensive @media print block that hides non-content elements, adjusts font sizes, and sets explicit page dimensions. **3. Font Substitution (causes 15% of issues):** Custom fonts referenced via @font-face with external URLs are replaced with system fonts. Solution: embed font files as Base64 data URIs in @font-face declarations. **4. Viewport-Dependent Layout (causes 9% of issues):** Responsive layouts render at the conversion engine's viewport width, which may differ from your screen width. Solution: replace vw/vh units with absolute units in @media print. Test at 794px browser width to preview A4-equivalent rendering. **5. Unsupported CSS Features (causes 7% of issues):** CSS filters, animations, blend modes, backdrop-filter, and sticky positioning have no PDF equivalent. Solution: provide static fallback values inside @media print. **6. JavaScript-Dependent Styling (causes 4% of issues):** CSS classes applied by JavaScript after page load (lazy-loaded styles, runtime theme switching, CSS-in-JS frameworks) may not execute in static HTML conversion engines. Solution: pre-render the page in a browser, save the complete DOM with computed styles, and use the saved HTML for conversion. **7. Color Space Issues (causes 3% of issues):** CSS colors specified in HSL, HWB, or display-p3 color spaces may convert incorrectly. Solution: use hex RGB values (#rrggbb) for all critical colors in @media print, which every engine interprets correctly. After applying fixes from this checklist, test the conversion and compare the PDF output against your intended design. For HTML-to-PDF conversions, LazyPDF's converter at /en/html-to-pdf processes files in 3-15 seconds, making iterative testing fast enough to fix issues in real time. For PDF-to-HTML workflows where you need to recover formatted content from a PDF, start with /en/pdf-to-word to extract a structured document, then rebuild CSS from the extracted content. If your HTML-to-PDF output renders blank pages entirely rather than missing styles, see our guide to <a href='/en/blog/pdf-shows-blank-pages-fix'>fixing blank pages in PDFs</a> which covers viewer rendering failures and structural corruption as root causes.
- 1Step 1: Open your HTML file in a browser and press Ctrl+P (Cmd+P on macOS) to open print preview. Compare the print preview against your expected PDF output — differences visible here will also appear in the converted PDF.
- 2Step 2: Check the browser console (F12 > Console tab) for failed resource loads. Any 404 errors for CSS files, font files, or images indicate external resources that will be missing in the server-side conversion. Inline each failed resource.
- 3Step 3: Resize your browser window to exactly 794 pixels wide (use the browser's responsive design mode in developer tools). This width matches the A4 page width at 96 DPI that most conversion engines use. Layout issues visible at this width will appear in the PDF.
- 4Step 4: Upload the HTML file to LazyPDF's /en/html-to-pdf converter and download the result. Open the PDF and compare it section by section against the browser rendering at 794px width. Note every discrepancy for targeted CSS fixes.
- 5Step 5: For each discrepancy, apply the corresponding fix from the troubleshooting checklist above, re-convert, and verify. Most documents require 2-3 iterations to achieve correct rendering. Save your @media print CSS rules as a reusable template for future conversions.
Complete CSS Code Template for Reliable PDF Conversion
The following CSS block is a production-tested @media print template that resolves the six most common rendering failures. Copy it into the <head> section of any HTML document before converting to PDF. <pre><code>/* ============================================= PDF CONVERSION CSS — production template Resolves: fonts, layout, backgrounds, links ============================================= */ @media print { /* 1. PAGE SETUP */ @page { size: A4; margin: 20mm; } /* 2. RESET BASE STYLES */ body { font-family: Arial, Helvetica, sans-serif; font-size: 11pt; line-height: 1.4; color: #000; background: #fff; print-color-adjust: exact; -webkit-print-color-adjust: exact; } /* 3. HIDE NON-CONTENT ELEMENTS */ nav, header nav, footer, .cookie-banner, .chat-widget, .sidebar, .ad-slot, .social-share, .video-embed, [data-print="hidden"] { display: none !important; } /* 4. PREVENT MID-ELEMENT PAGE BREAKS */ table, figure, blockquote, pre, img, .no-break { page-break-inside: avoid; } h1, h2, h3 { page-break-after: avoid; } /* 5. SHOW LINK URLS (for printed copies) */ a[href^='http']::after { content: ' (' attr(href) ')'; font-size: 9pt; color: #555; word-break: break-all; } /* Exclude internal anchors */ a[href^='#']::after { content: ''; } /* 6. PRESERVE BACKGROUND COLORS */ .highlight, .badge, .tag, [style*='background'] { print-color-adjust: exact; -webkit-print-color-adjust: exact; } /* 7. FIX VIEWPORT-RELATIVE SIZES */ .hero, .full-screen, [style*='100vh'] { height: auto !important; min-height: 0 !important; } .container, .wrapper { width: 100% !important; max-width: 100% !important; padding: 0 !important; } /* 8. FLATTEN ANIMATIONS TO FINAL STATE */ * { animation: none !important; transition: none !important; opacity: 1 !important; transform: none !important; } }</code></pre> <p>This template covers the 8 most impactful CSS print fixes. Use it as a starting point and customize the selectors for element visibility (section 3) to match your specific HTML structure. The @page rule in section 1 sets A4 size with 20mm margins — change to <code>size: letter; margin: 0.75in;</code> for US Letter format. The animation-flattening rules in section 8 ensure that any element animated from an invisible state (opacity: 0, scale: 0, translateY: -100px) renders at its fully-visible final state in the PDF output.</p> <p>After adding this template, test your conversion by uploading the HTML to <a href='/en/html-to-pdf'>LazyPDF's HTML-to-PDF tool</a>. The server-side LibreOffice rendering engine applies your @media print rules correctly, and the 7-15 second processing time makes iterative testing fast. If a section still renders incorrectly after applying the template, use your browser's print preview (Ctrl+P or Cmd+P) to diagnose the issue — print preview activates the same @media print rules, letting you see the exact output without running a full conversion.</p>
- 1Copy the template into your HTML headPaste the CSS block inside a <style> tag in the <head> section of your HTML file, after any existing stylesheets. Placing it last ensures the @media print rules override screen-specific styles through CSS cascade order without needing !important on every declaration.
- 2Customize the hidden-element selectorsReplace the generic selectors in section 3 (nav, .sidebar, .cookie-banner) with the actual CSS class names and IDs from your HTML. Open your browser's developer tools (F12) and inspect the elements you want to hide to find their correct selectors. Wrong selectors are the most common reason this template does not work on a specific page.
- 3Embed external fonts as Base64If your page uses Google Fonts or other external font files, add a @font-face rule with the font file embedded as a Base64 data URI. This prevents font-not-found failures in server-side converters. Convert WOFF2 to Base64 using: base64 -i font.woff2 (macOS/Linux) or certutil -encode font.woff2 out.b64 (Windows). Insert the Base64 string into: src: url(data:font/woff2;base64,INSERT_HERE) format('woff2');
- 4Test at 794px browser widthIn your browser's developer tools, activate Responsive Design Mode (Ctrl+Shift+M on Chrome/Firefox) and set the viewport to exactly 794px wide. This matches the pixel width of an A4 page at 96 DPI used by most conversion engines. Your layout at this width is exactly what the PDF will look like — fix any issues you see here before converting.
- 5Convert and compareUpload the HTML file to LazyPDF's HTML-to-PDF converter and download the PDF. Compare it section-by-section against the 794px browser preview. Issues that appear in the PDF but not in the browser preview indicate engine-specific rendering differences — apply targeted overrides for those elements inside the @media print block.
Frequently Asked Questions
Why do my Google Fonts not appear in the converted PDF?
Server-side PDF conversion engines cannot fetch font files from Google's CDN during processing. The engine substitutes the closest system font, typically Arial or Times New Roman. Fix this by downloading the WOFF2 font files and embedding them as Base64 data URIs directly in your CSS @font-face declarations. Each embedded font adds approximately 40-120 KB to the HTML file size.
Why does my CSS Grid layout collapse to a single column in the PDF?
The conversion engine may not support CSS Grid or may use an older specification version. The deprecated wkhtmltopdf tool has zero Grid support. Fix this by adding a @media print fallback that replaces display: grid with float-based or inline-block layouts. These older layout methods are universally supported by all conversion engines and produce reliable PDF output.
How do I keep background colors visible in the PDF output?
Many conversion engines strip background colors by default, following browser print conventions. Force background rendering by adding print-color-adjust: exact and -webkit-print-color-adjust: exact to elements where backgrounds must appear. Place these declarations inside your @media print CSS block. This property is supported by all modern conversion engines including LibreOffice and Chromium-based tools.
Can I recover the original CSS when converting a PDF back to HTML?
No. PDFs contain no CSS data — only positioned glyphs, images, and vector paths. Extraction tools reverse-engineer approximate styling by analyzing visual patterns, recovering about 72% of formatting. For best results, convert the PDF to Word first using a tool like LazyPDF's PDF-to-Word converter, then export to HTML and manually rebuild the CSS from the structured document.
Why do CSS animations make elements invisible in the PDF?
PDF is a static format that captures elements at a single moment, typically their initial animation state. An element animated from opacity: 0 to opacity: 1 renders invisible in the PDF because the engine captures the starting state. Fix this by setting all animated properties to their final values inside @media print — for example, opacity: 1 and transform: none.
What viewport width does the conversion engine use for responsive layouts?
Most server-side conversion engines use a default viewport width of 794 pixels, which matches the A4 page width at 96 DPI. Responsive breakpoints trigger based on this width, not your screen width. Preview your layout by resizing your browser to exactly 794 pixels wide using developer tools. Replace viewport-relative units with absolute values inside @media print for consistent results.
How do I prevent tables from being split across PDF pages?
Add page-break-inside: avoid to your table elements inside a @media print CSS block. This instructs the conversion engine to move the entire table to the next page rather than splitting it mid-row. For tables taller than a full page, this property cannot prevent splitting. In that case, break the table into smaller logical sections with separate thead elements that repeat on each page.