Make the target div renderable before calling html2pdf(), give the browser a chance to apply the visibility change, then export it. Restore its original inline styles afterward. If the div must stay hidden on the live page, use html2canvas’s onclone callback to reveal it in the cloned document instead.
Why a hidden div produces a blank PDF
html2pdf.js uses html2canvas to render a webpage element and jsPDF to create the PDF. That means the element must be renderable when html2canvas captures it. An element with display: none has no rendered box, so it is excluded; setting a style and immediately starting the export can also race the browser’s style and layout update.
For a typical hidden export panel, the dependable sequence is: locate the element, save the inline values you intend to change, set an appropriate display value and visibility: visible, wait for rendering, export, and restore the values in a finally block. Choose the display value that fits the element’s layout; block is common, but a flex or grid container may need flex or grid.
Temporarily show the div, export it, then restore it
This approach makes the live element visible during capture. It is straightforward and preserves the element’s normal computed styles, but the element may briefly appear on screen. The finally block restores its original inline styles whether export succeeds or fails.
Free tools Windows power users keep installed
One-click scans. No signup required.
#1 Best Overall
- INNOVATIVE CARTRIDGE-FREE PRINTING — No more dealing with lots of tiny ink cartridges; With this wireless document and photo printer each ink bottle set is equivalent to about 90 individual cartridges²
- LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; When you choose this combination printer, scanner and copier you can print up to 4,500 pages black/7,500 color³
- COLOR PRINTING — Up to 2 years of ink in the box4 (and with every replacement ink set) for fewer out-of-ink frustrations
- ZERO CARTRIDGE WASTE — By using an Epson EcoTank printer you can help reduce the amount of cartridge waste ending up in landfills
- HOME PRINTER DESIGNED FOR RELIABILITY — The Epson EcoTank ET-2800 All-in-One Supertank Color Printer creates vivid, detailed prints and documents thanks to Micro Piezo Heat-Free Technology; Fire off 10 ISO pages per minute1 to easily finish large jobs
async function exportDiv() {
const el = document.querySelector('#printDiv');
if (!el) throw new Error('Could not find #printDiv');
const previousDisplay = el.style.display;
const previousVisibility = el.style.visibility;
try {
el.style.display = 'block'; // Use the layout value this element needs.
el.style.visibility = 'visible';
// Allow style recalculation and layout to reach a paint opportunity.
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;
}
}
Call exportDiv() from the user action that should create the PDF, such as a button handler. This example expects that html2pdf.js is already loaded and that the page contains an element with id="printDiv".
Why wait for animation frames?
Changing style.display updates the element’s inline style immediately, but the browser still needs to recalculate styles and layout. Two requestAnimationFrame callbacks provide a conservative opportunity for that work before capture. One frame may be sufficient for a simple page. If a framework updates the export panel asynchronously, also await that framework’s next-render mechanism before starting html2pdf.
Restore the state you changed
The example saves and restores the inline display and visibility values, rather than forcing the element back to none. That matters if another part of the page already set an inline value. If your code changes additional inline properties, save and restore those too. It does not undo state changes made by unrelated code during the export.
Keep the live page hidden with html2canvas onclone
If showing the panel in the live page would cause flicker or disrupt the interface, change visibility only in html2canvas’s cloned document. The clone is the document html2canvas renders, so this keeps the original page’s visibility untouched.
Recommended Free Tools
Rank #2
- CARTRIDGE-FREE PRINTING — Print lab-quality photos, graphics and creative projects; Get vibrant colors and sharp text with Epson's high-accuracy printhead and Claria ET Premium 6-color inks
- INK BOTTLES — Save on photos1 and creative projects with affordable in-house printing; All-in-one printer allows you to print 4" x 6" photos for about 4 cents each vs. 40 cents with traditional ink cartridges1
- LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; Printer, scanner and copier lets you print up to 6,200 color pages³
- PRINT FOR LONGER — Up to 2 years of ink in the box² (and with every replacement ink set) for fewer out-of-ink frustrations with this wireless printer
- ZERO CARTRIDGE WASTE — Epson EcoTank printer helps reduce the amount of cartridge waste ending up in landfills; Cartridge-free printer uses high-yield ink bottles; Each replacement ink bottle set is equivalent to about 100 individual ink cartridges⁴
const el = document.querySelector('#printDiv');
if (!el) throw new Error('Could not find #printDiv');
await html2pdf()
.set({
html2canvas: {
onclone: (clonedDoc) => {
const clone = clonedDoc.querySelector('#printDiv');
if (clone) {
clone.style.display = 'block';
clone.style.visibility = 'visible';
}
}
}
})
.from(el)
.save();
This is useful when the page must not visibly change, but it is not a way to capture an element that cannot be selected or cloned from the source document. Keep the live element in the document; the callback changes the render clone, not the source. Check the clone’s styles if the PDF layout differs from what you expect.
| Approach | What changes | Useful when | Trade-off |
|---|---|---|---|
| Temporarily unhide the live element | The source page’s inline visibility styles change for the export and are restored afterward. | You want the normal live-page styling and can tolerate a brief display change. | May cause visible flicker; asynchronous UI updates may need an additional framework render wait. |
Reveal it in onclone |
Only the cloned document used for rendering is changed. | The live interface must remain visually unchanged. | Clone-specific CSS or layout can affect the PDF; the source element still needs to be available to clone. |
Hide controls without hiding the captured root
If the div should print but buttons, menus, or other descendants should not, leave the root renderable and omit only those descendants. html2canvas supports the data-html2canvas-ignore attribute and an ignoreElements predicate for this purpose.
<div id="printDiv">
<h1>Report</h1>
<p>Content to export</p>
<button data-html2canvas-ignore>Edit report</button>
</div>
Use the attribute when the exclusion is declarative and tied to a particular element. Use ignoreElements when the exclusion depends on a programmatic rule, such as a class or a set of selectors:
html2canvas: {
ignoreElements: (element) => element.matches('.no-print')
}
Do not apply either exclusion rule to the target root if that root is the element being rendered.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Rank #3
- SET IT UP ONCE AND PRINT WITH CONFIDENCE. No complicated maintenance. Just easy, reliable printing you can count on.
- INK FOR YEARS. NOT MONTHS. Up to 2 years of ink included. Get thousands of pages of cartridge-free printing. More pages, less hassle
- KEEPS PRINTING WELL AFTER COMPETITORS HAVE QUIT. No complex maintenance. Sharper text, richer colors.[2] Only with HP Smart Tank
- PREMIUM SUPPORT - Strong technical expertise to solve issues faster
- THE LAST PRINTER YOU'LL EVER NEED. Enjoy years of refillable, cartridge-free printing.
Make the captured layout stable
Unhiding is only one part of a reliable export. The element also needs usable dimensions, and its content should be ready by the time capture begins.
- Check width and height: confirm the target and its ancestors have nonzero dimensions. A visible element with no usable size can still produce an empty-looking result.
- Wait for dynamic content: if the panel is populated by a framework, wait for that render to finish before calling html2pdf.
- Wait for fonts and images when needed: late-loading fonts or images can change wrapping and page breaks. Ensure they have loaded before capture if their final appearance matters.
- Use the intended width: establish a stable content width before rendering. A different cloned viewport or width can change line wrapping and the resulting page count.
- Check cross-origin images: browser canvas security rules can prevent html2canvas from rendering images hosted on another origin. Use assets served from the same origin or configure the image host for CORS and follow html2canvas’s CORS or proxy guidance.
Troubleshoot blank, clipped, or incorrect PDFs
The PDF is still blank
Inspect computed styles for the target and every ancestor. Look for display: none, visibility: hidden, zero width or height, or a hidden ancestor. Confirm that the selector matches the element and that the element exists when the export runs. If styles were just changed, wait for a rendering opportunity; if a framework controls the content, await its completed update as well.
The PDF has the wrong layout
Confirm that the value used for display suits the element. Replacing a grid or flex container with block can change its layout. Check the element’s width, loaded fonts and images, and any clone-specific CSS. With the onclone approach, inspect the styles that apply in the cloned document rather than assuming they match every detail of the live page.
The content is cut off or a large export is empty
Very large documents can run into browser canvas-size limits, and viewport dimensions that do not match the content can contribute to empty or truncated canvases. For a large target, try setting html2canvas’s windowWidth and windowHeight from the element’s scroll dimensions, then verify that the resulting viewport still produces the layout you want. If the content exceeds the browser’s practical canvas limits, reducing the captured area or splitting the export into smaller sections may be necessary.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Rank #4
- Wireless Bluetooth Printer: Portable thermal printer compatible with iPhone, Android phones, iPad and tablet computers via Bluetooth. For smartphones, please download the "Nada Print" App. You can also connect to laptops and computers for printing using a USB-C cable. (Note: Laptops and computers can only be connected via USB and require the installation of a driver first. Bluetooth connection is not supported.)
- No-ink printing: Only supports US Letter and A4 size thermal paper.(Doesn't support regular paper) The no-ink portable thermal printer uses direct thermal technology, requiring no ink, toner or ribbons, making it environmentally friendly, cost-effective and time-saving. The thermal printer package comes with a roll of US Letter thermal printing paper. Note: When installing the paper, remember to switch the paper size switch on APP
- Clear Print: NDYIN N80 portable thermal printer adopts high-definition printing technology, with a 203DPI resolution to provide you with clear printing results. This mobile printer is compatible with roll paper, folded paper and tattoo transfer paper, supporting printing from your mobile phone PDF, Word, pictures and web pages anytime and anywhere. It is recommended to use our NDYIN thermal paper to achieve good printing quality
- Portable wireless printer for travel: The thermal printer is equipped with a built-in 1500mAh rechargeable battery, which can print 160 sheets of 8.5" x 11" thermal paper after being fully charged. It weighs only 1.5 pounds and is compact in size. This ink-free portable printer can be easily carried in a backpack or briefcase! It is perfect for business travel, cars, small offices, construction sites, schools and homes. You can print documents, contracts, invoices and boarding passes anytime and anywhere
- The N80 thermal printer has a wide range of uses. The package includes the N80 printer, a roll of US Letter paper(7m/roll), a user manual, a guide card, a type-C soft cable and a type C adapter. Note: The charging adapter is not included. Special thermal paper is required for use; ordinary paper cannot be used. This ink-free portable thermal printer is suitable for various scenarios such as home, school, travel, office, and outdoor, meeting the printing needs of different groups of people. This tattoo template printer is also compatible with tattoo transfer paper, making it an ideal choice for tattoo art
const el = document.querySelector('#printDiv');
const width = el.scrollWidth;
const height = el.scrollHeight;
await html2pdf()
.set({
html2canvas: {
windowWidth: width,
windowHeight: height
}
})
.from(el)
.save();
Use dimensions appropriate to your page and verify the output: changing the capture viewport can affect responsive styles as well as canvas dimensions.
Images are missing
For images from another origin, check whether that host permits cross-origin image access. The example sets useCORS: true, but the option cannot override a server that does not provide the required CORS response. A same-origin asset or a correctly configured CORS/proxy setup is needed when browser security would otherwise taint or exclude the image.
The live page stays visible after an error
Use a try/finally structure around the export so restoration runs when the promise rejects. If the interface still appears changed, check that you restored every inline property your export code modified and that no other code changed the same element concurrently.
Or skip the browser setup
If you need an image or PDF of a public webpage rather than a particular in-page div, ScreenshotNeo can capture a URL through its screenshot API. It is not a drop-in replacement for html2pdf: it captures a website URL, not a selected element from your app’s DOM. See the ScreenshotNeo API documentation for request options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
- Cookie and consent banners, newsletter popups, and chat widgets are removed before capture; each cleanup step can be turned off.
- Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed; response headers identify the page verdict and billing status.
- An MCP server gives AI agents tools to take screenshots, get page information, and capture PDFs.
- The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.
Sign up for ScreenshotNeo’s free plan: 1,000 screenshots a month, no card required.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

