How to Make html2pdf Print a Div After Unhiding It
Make html2pdf capture a div that starts hidden. Learn the reliable unhide, render-wait, clone-only, sizing, CORS, and troubleshooting patterns.

Set the div to a renderable display value, wait for the browser to apply styles and layout, then pass it to html2pdf. Restore the original styles after the export. A div that remains display:none, has visibility:hidden, has zero dimensions, or sits inside a hidden ancestor is skipped by html2canvas, the renderer used by html2pdf.js.
The dependable sequence is:
- Find the export root.
- Save its current inline styles.
- Set
displayandvisibilityto values that allow painting. - Wait for one or two animation frames, plus any framework update or asset-loading promises.
- Call
html2pdf().from(element).save(). - Restore the saved styles in a
finallyblock.
Why a hidden div produces a blank PDF
html2pdf.js coordinates html2canvas and jsPDF. html2canvas builds a canvas from the rendered DOM; it does not treat display:none content as paintable content. The html2canvas issue discussion documents this behavior directly: hidden elements are intentionally omitted. Consequently, changing a class or inline style immediately before calling html2pdf can race the browser’s style recalculation and layout work.
There are several different kinds of “hidden,” and they need slightly different fixes:
| Condition | What the renderer sees | Typical fix |
|---|---|---|
display:none |
No layout box exists. | Use block, flex, grid, or the layout value the component needs. |
visibility:hidden |
A box exists but it is not painted. | Set visibility:visible. |
| Zero width or height | There is nothing useful to rasterize. | Give the root a stable width and inspect its scroll dimensions. |
| Hidden ancestor | The descendant remains effectively hidden. | Unhide the relevant ancestor or render a clone with corrected styles. |
| Off-screen positioning | Usually paintable, but can be clipped by overflow or viewport assumptions. | Use a stable render container and explicit dimensions. |
Reliable live-element export
This pattern temporarily unhides the real element, waits for a paint opportunity, exports it, and puts the page back exactly as it was. Use the display value that matches your layout; block is only an example.

async function exportDiv() {
const el = document.querySelector('#printDiv');
if (!el) throw new Error('Missing #printDiv');
const previousDisplay = el.style.display;
const previousVisibility = el.style.visibility;
try {
el.style.display = 'block';
el.style.visibility = 'visible';
// Let style recalculation, layout, and painting catch up.
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
await html2pdf()
.set({
margin: 10,
filename: 'export.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: {
scale: 2,
useCORS: true
},
jsPDF: {
unit: 'mm',
format: 'a4',
orientation: 'portrait'
}
})
.from(el)
.save();
} finally {
el.style.display = previousDisplay;
el.style.visibility = previousVisibility;
}
}
// Example button handler
document.querySelector('#download').addEventListener('click', exportDiv);
The two requestAnimationFrame waits are a conservative choice. One frame can be sufficient for a simple page. Two frames are safer when a stylesheet, web font, image, or framework render is involved. The wait is about allowing the browser to commit the visibility change; it is not a fixed html2pdf delay.
Keep the right layout mode
If the hidden root was a flex or grid container, restoring it as block can change wrapping and pagination. Read the computed style first or use the component’s known value:
const el = document.querySelector('#printDiv');
const displayForExport = getComputedStyle(el).display === 'none'
? 'flex'
: getComputedStyle(el).display;
el.style.display = displayForExport;
In production code, it is often clearer to define an export class:
.report {
display: none;
}
.report.is-exporting {
display: block;
visibility: visible;
width: 794px;
background: white;
}
.report.is-exporting .toolbar,
.report.is-exporting [data-export-control] {
display: none;
}
Wait for framework updates, fonts, and images
If React, Vue, Angular, or another framework controls visibility, changing an inline style can be overwritten by the next render. Make the state change through the framework, await its next-render mechanism, and then wait for a frame. Also wait for resources that affect the final geometry.
async function waitForExportReady(root) {
if (document.fonts?.ready) await document.fonts.ready;
const images = [...root.querySelectorAll('img')];
await Promise.all(images.map(img => {
if (img.complete) return Promise.resolve();
return new Promise(resolve => {
img.addEventListener('load', resolve, { once: true });
img.addEventListener('error', resolve, { once: true });
});
}));
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
}
Do not wait forever for a broken image. The example resolves on both load and error; the troubleshooting section explains how to handle assets that cannot be drawn to a canvas.
Hide controls without hiding the export root
Buttons, menus, and download controls can be excluded while the main target remains renderable. html2canvas supports the declarative data-html2canvas-ignore attribute:
<section id="printDiv">
<div class="toolbar" data-html2canvas-ignore>
<button>Edit</button>
<button>Download</button>
</div>
<article>Content included in the PDF</article>
</section>
You can also exclude nodes programmatically with ignoreElements:
await html2pdf()
.set({
html2canvas: {
ignoreElements: element =>
element.matches('.toolbar, [data-screen-only]')
}
})
.from(document.querySelector('#printDiv'))
.save();
Use the attribute when the rule is stable and visible in markup. Use the predicate when the exclusion depends on runtime state.
Clone-only export with onclone
If making the live page visible causes flicker, changes scroll position, or conflicts with a component’s state, modify only the cloned document used by html2canvas. Its onclone callback is intended for this purpose.
async function exportHiddenClone() {
const el = document.querySelector('#printDiv');
if (!el) throw new Error('Missing #printDiv');
await html2pdf()
.set({
filename: 'export.pdf',
html2canvas: {
scale: 2,
useCORS: true,
onclone: (clonedDoc) => {
const clone = clonedDoc.querySelector('#printDiv');
if (!clone) return;
clone.style.display = 'block';
clone.style.visibility = 'visible';
clonedDoc.querySelectorAll('.toolbar, [data-screen-only]')
.forEach(node => node.remove());
}
},
jsPDF: { unit: 'mm', format: 'a4' }
})
.from(el)
.save();
}
The source element must still be selectable and clonable. If an ancestor is hidden, changing only the descendant may not be enough; update the relevant ancestor in the clone as well. Clone-specific CSS can also affect the result, so inspect selectors that depend on parent classes.
Full example with HTML and a download button
<button id="download" type="button">Export PDF</button>
<section id="printDiv" class="report" aria-hidden="true">
<header data-html2canvas-ignore>Screen-only toolbar</header>
<h1>Quarterly report</h1>
<p>This content is exported after the section becomes renderable.</p>
</section>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<script>
async function exportDiv() {
const el = document.querySelector('#printDiv');
const oldDisplay = el.style.display;
const oldVisibility = el.style.visibility;
try {
el.style.display = 'block';
el.style.visibility = 'visible';
el.removeAttribute('aria-hidden');
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
await html2pdf().set({
margin: 10,
filename: 'quarterly-report.pdf',
image: { type: 'jpeg', quality: 0.95 },
html2canvas: { scale: 2, useCORS: true },
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
}).from(el).save();
} finally {
el.style.display = oldDisplay;
el.style.visibility = oldVisibility;
el.setAttribute('aria-hidden', 'true');
}
}
document.querySelector('#download').addEventListener('click', exportDiv);
</script>
Important html2pdf and html2canvas options
| Option | Use it for | Trade-off |
|---|---|---|
margin |
Space around the rendered content. | Larger margins reduce usable page width. |
filename |
Downloaded file name. | Use a safe name without path characters. |
image.type |
jpeg, png, or another supported output type. |
JPEG is smaller but loses transparency and uses lossy compression. |
image.quality |
JPEG quality. | Higher quality increases file size. |
html2canvas.scale |
Sharper text and graphics. | Memory use and rendering time rise quickly. |
useCORS |
Images served with appropriate CORS headers. | It cannot bypass a server that does not grant cross-origin access. |
windowWidth/windowHeight |
Large or responsive documents whose layout depends on viewport dimensions. | Incorrect values can cause wrapping or clipping. |
onclone |
Clone-only style changes and cleanup. | Changes affect the render clone, not the live page. |
ignoreElements |
Programmatic descendant exclusion. | The predicate runs for many nodes, so keep it cheap. |

Large documents, sizing, and page breaks
For a tall report, the browser canvas and the PDF page model impose practical limits. A blank or truncated result can be caused by a canvas that is too large, a viewport that is too short, or content whose dimensions are measured before it becomes visible.
const root = document.querySelector('#printDiv');
const width = Math.max(root.scrollWidth, root.offsetWidth);
const height = Math.max(root.scrollHeight, root.offsetHeight);
await html2pdf().set({
html2canvas: {
scale: 1.5,
windowWidth: width,
windowHeight: height,
useCORS: true
},
pagebreak: {
mode: ['css', 'legacy'],
avoid: ['.card', 'tr']
},
jsPDF: { unit: 'mm', format: 'a4' }
}).from(root).save();
Use CSS page-break rules for important boundaries:
.page-break-before { break-before: page; }
.keep-together { break-inside: avoid; }
Measure after unhiding and after fonts and images settle. Otherwise scrollHeight may describe an empty or partially laid-out element.
Troubleshooting checklist
The PDF is completely blank
Inspect getComputedStyle(root) and every ancestor for display:none, visibility:hidden, opacity combined with zero dimensions, or a collapsed container. Confirm that the root has non-zero offsetWidth and offsetHeight. Then add the animation-frame waits.
The first export is blank, but the second works
This is usually a timing race. The first click changes visibility and captures before layout is committed. Await the framework’s next render, then one or two requestAnimationFrame callbacks. Do not rely on an arbitrary 100 ms timeout when a render boundary is available.
The layout is wrong after unhiding
You may have replaced flex, grid, or an inline display value with block. Preserve the intended display mode, set a stable export width, and check media queries. A hidden element can also have dimensions that depend on a visible parent.
Images are missing or the export throws a security error
html2canvas cannot draw cross-origin images onto a canvas unless the image server permits it with CORS headers. Serve assets from the same origin, configure the asset server’s CORS policy, or use the documented proxy approach. useCORS:true requests CORS; it does not override browser security.
The document is cut off
Capture after the final height is known. Set windowWidth and windowHeight from the root’s scroll dimensions when responsive layout needs them. Reduce scale for very large pages and split extremely long reports into sections if the browser canvas limit is reached.
Controls still appear
Put data-html2canvas-ignore on the control itself, not on the export root. Alternatively, use an ignoreElements predicate. Check that a clone callback is not recreating the controls after you remove them.
Web fonts change pagination
Wait for document.fonts.ready before measuring or exporting. Font swaps can change line wrapping and therefore every page boundary.
Performance, reliability, and cost considerations
- Choose scale deliberately. A scale of 2 is a useful quality baseline, but it creates a canvas roughly four times the pixel area of scale 1. Lower it for long documents or memory-constrained devices.
- Remove unnecessary DOM. Exclude navigation, animations, videos, and interactive controls. A smaller tree renders faster and produces more predictable pagination.
- Freeze motion. Add an export class that disables transitions and animations so the capture does not land between frames.
- Wait for stable inputs. Capture only after data, fonts, images, and visibility state are ready. This improves repeatability more than adding a long fixed delay.
- Expect client-side resource use. html2canvas rasterizes in the user’s browser; large canvases consume memory and can fail on mobile devices.
- Control output size. JPEG quality and canvas scale affect download size. Use PNG when transparency or pixel-perfect text is more important than file size.
Or skip the browser setup
If you need a rendered image or PDF from a URL instead of maintaining a client-side html2pdf pipeline, ScreenshotNeo provides a website screenshot API and MCP server. It accepts one request and returns a PNG, JPEG, WebP, or PDF. Cookie and consent banners, newsletter popups, and chat widgets are removed before capture; bot checks, blank pages, failed loads, timeouts, and cache hits are not billed.
For a direct request, see the ScreenshotNeo API documentation:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const data = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', data);
ScreenshotNeo also supports full-page captures with lazy images loaded, element selection, custom CSS and JavaScript, waits for selectors or network idle, device presets, PDFs with paper and margin settings, blocking rules, custom headers and cookies, caching, signed links, asynchronous jobs, bulk capture, usage reporting, and an MCP server with take_screenshot, get_page_info, and capture_pdf for AI agents.
The free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 shots, and every plan includes all features. Create a free ScreenshotNeo account.
FAQ
How long should I wait after setting display:block?
Wait for one animation frame in simple pages and two when styles, fonts, images, or framework updates are involved. Await the framework’s next-render promise first when it controls the element.
Can I keep the div hidden in the live page?
Yes. Use html2canvas’s onclone callback to set visibility in the cloned document. Make sure the root and any hidden ancestors become renderable in that clone.
Should I use visibility:hidden or display:none for screen-only content?
Either can prevent capture. For export-only content, use a dedicated export state and explicitly make the root renderable during capture; do not hide the root you are passing to html2pdf.
Why does changing the CSS class not work?
The class change may be overwritten by a framework render, or capture may start before style and layout updates. Apply the state through the framework and await a render boundary plus animation frames.
Can html2pdf preserve interactive form fields?
html2pdf renders a visual canvas and places it into a PDF. Treat the result as a visual document rather than a live HTML form unless you add a separate PDF form-generation workflow.


