Downloading a PDF generated from HTML has two separate parts: first create valid PDF bytes, then deliver those bytes as a download. If the PDF already exists at a same-origin URL, use an anchor with the download attribute. If JavaScript creates the PDF in memory, wrap the bytes in a Blob and download its object URL. If a server or hosted API creates it, return the bytes with Content-Type: application/pdf and, when appropriate, Content-Disposition: attachment.
1. Download an existing PDF file
When your application already serves a PDF, the simplest implementation is a normal link:
<a href="/reports/report.pdf" download="report.pdf">Download PDF</a>
The download attribute is a browser hint that suggests downloading the resource and provides a filename. It works for same-origin URLs and for blob: and data: URLs, but it is not a reliable way to force downloads from arbitrary cross-origin URLs. Browser settings can still open the PDF, prompt the user, or save it automatically. A server response with Content-Disposition may provide the final filename instead of the HTML value. See the MDN anchor documentation for the documented rules.
Server headers for an attachment
If you control the endpoint, return real PDF bytes and set headers such as:
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Content-Type: application/pdf
Content-Disposition: attachment; filename="report.pdf"
Use inline instead of attachment when you want the browser to display the PDF where supported. Headers do not convert HTML into a PDF: the response body must already be a valid PDF produced by a converter or renderer.
2. Download PDF bytes generated in the browser
Client-side libraries commonly return a Blob, an ArrayBuffer, or a byte array. Convert the result to a Blob with the PDF MIME type, create an object URL, and assign that URL to a temporary link.
async function downloadPdf(pdfBytes, filename = "report.pdf") {
const blob = new Blob([pdfBytes], { type: "application/pdf" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename;
link.textContent = "Download PDF";
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}
Call this only with bytes from an actual PDF generator. Giving HTML text a PDF filename or MIME type does not create a readable PDF. For asynchronous generation, run the function from a user-initiated button, show progress, and catch generation errors. Test the object-URL lifecycle in the browsers and deployment context you support; applications that remove links immediately can behave differently, so do not assume one revocation delay works everywhere.
Using html2pdf.js
html2pdf.js converts a webpage or selected element in the browser and documents a save flow. It runs in a browser, not Node.js. Install it with npm or include a deliberately pinned CDN version rather than an unversioned asset:
Free tools Windows power users keep installed
One-click scans. No signup required.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
npm install html2pdf.js
import html2pdf from "html2pdf.js";
const element = document.querySelector("#invoice");
await html2pdf().set({
margin: 12,
filename: "invoice.pdf",
image: { type: "jpeg", quality: 0.95 },
html2canvas: { scale: 2 },
jsPDF: { unit: "mm", format: "a4", orientation: "portrait" }
}).from(element).save();
Client conversion is convenient for a browser-only feature, but output depends on browser rendering, page-break behavior, fonts, image access, and the library’s supported options. It also exposes the source document and any client-side data to the user’s browser.
3. Generate and download on a server with Puppeteer
Server-side rendering gives you control over navigation, readiness, print settings, credentials, and secrets. Puppeteer’s guide uses page.goto() followed by page.pdf(); its PDF method waits for fonts by default, and the documented example waits for networkidle2.
import express from "express";
import puppeteer from "puppeteer";
const app = express();
app.use(express.json({ limit: "2mb" }));
app.post("/report.pdf", async (req, res) => {
const browser = await puppeteer.launch({ headless: true });
try {
const page = await browser.newPage();
await page.setContent(req.body.html, { waitUntil: "networkidle2" });
await page.emulateMediaType("print");
const pdfBytes = await page.pdf({
format: "A4",
printBackground: true,
margin: { top: "16mm", right: "14mm", bottom: "16mm", left: "14mm" }
});
res.set({
"Content-Type": "application/pdf",
"Content-Disposition": "attachment; filename="report.pdf""
});
res.send(pdfBytes);
} catch (error) {
res.status(500).json({ error: "PDF generation failed" });
} finally {
await browser.close();
}
});
app.listen(3000);
In production, reuse a controlled browser process where your hosting model permits it, limit input size, authenticate the route, and never send service credentials to the client. Validate or sanitize untrusted HTML and restrict navigation if pages can reference internal network addresses.
Wait for the page your application actually needs
networkidle2 is only a general signal. A single-page app can finish its initial network activity before its data, fonts, or charts appear. Add an application-specific readiness marker:
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
await page.goto("https://example.com/report", { waitUntil: "domcontentloaded" });
await page.waitForSelector("#report-ready", { timeout: 30000 });
await page.evaluate(() => document.fonts.ready);
const pdfBytes = await page.pdf({ printBackground: true, format: "A4" });
Set printBackground: true when CSS backgrounds or background images are part of the design. Use print CSS (@page, page-break rules, and print-only selectors) to control pagination. Confirm that external images and fonts are reachable from the server, not merely from your laptop.
4. Hosted HTML-to-PDF services
A managed service can accept a URL, raw HTML, or an archive and return a PDF without you operating a browser. Adobe PDF Services documents static and dynamic HTML, ZIP, and URL inputs through REST and SDKs for Node.js, .NET, Java, and Python; consult its current documentation for authentication, limits, pricing, and data handling: Adobe HTML-to-PDF documentation.
Cloudflare Browser Run documents a /pdf quick action that accepts a URL or raw HTML, plus Puppeteer and Playwright routes. Its documented request-body limit is 50 MB and applies specifically to that endpoint. Cloudflare warns that JavaScript-heavy pages and SPAs may be incomplete unless you wait for application content. See the /pdf reference and the Browser Rendering documentation.
Compare a hosted converter by supported input, authentication, data retention, geographic processing, request limits, readiness controls, print options, failure reporting, and current price. Do not assume limits or rendering behavior are interchangeable between vendors.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
5. ScreenshotNeo alternative for URL-to-PDF capture
If your source is a public web URL and you do not want to maintain browser automation, ScreenshotNeo is a website screenshot API and MCP server. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers report the page verdict and billing status.
It supports PDF output with paper size, margins, landscape mode, and page ranges, along with full-page capture, lazy-image loading, CSS-selector element capture, custom CSS and JavaScript, waits for selectors, delays or network idle, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients. Parameter names used by other screenshot APIs also work for easier migration.
Use the API documentation at https://screenshotneo.com/docs/ for authentication and PDF parameters. A basic request is:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
For a PDF response, add the documented PDF output parameter for your request. In Python:
Recommended Free Tools
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)
Node.js:
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(`ScreenshotNeo returned ${res.status}`);
const data = Buffer.from(await res.arrayBuffer());
ScreenshotNeo’s Free plan includes 1,000 shots per month without a card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan, and yearly billing provides two months free. Create a free ScreenshotNeo account to start.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
6. Troubleshooting downloads and rendering
The browser opens the PDF instead of saving it
- Verify the URL is same-origin or a
blob:URL;downloaddoes not generally force arbitrary cross-origin downloads. - Check the anchor filename, response
Content-Disposition, and browser download preferences. - Test a direct user click rather than a delayed or cross-origin script-triggered click.
The PDF is blank or missing application data
- Wait for a page-specific selector or ready flag after client rendering.
- Ensure API calls, images, stylesheets, and fonts are accessible from the renderer.
- For Cloudflare’s quick-action endpoint, keep the request body at or below its documented 50 MB limit.
Fonts, colors, or backgrounds differ
- Await
document.fonts.readyand verify the font network requests. - Use print CSS and enable
printBackgroundwhere supported. - Specify paper size, margins, orientation, and page ranges explicitly.
The downloaded file cannot be opened
- Inspect the response status and headers before saving.
- Confirm the body begins with actual PDF data, not an HTML error page.
- Do not label HTML as
application/pdf; regenerate it with a real converter.
7. Choosing the right method
| Method | Best fit | Key trade-offs |
|---|---|---|
| Same-origin link | PDF already exists | Simple, but subject to origin rules, headers, and browser settings. |
| Browser library | Browser-only conversion | No server browser; rendering and pagination depend on the client. |
| Puppeteer or similar | Controlled server rendering | Requires browser runtime, readiness logic, and resource management. |
| Hosted API | Managed operations | Compare vendor limits, authentication, privacy, pricing, and supported inputs. |
Frequently Asked Questions
Can I download HTML by naming it .pdf?
No. A PDF filename and MIME type do not convert HTML; generate valid PDF bytes first.
Why is my single-page app PDF empty?
The renderer likely printed before client-side content was ready. Wait for an application-specific selector or readiness signal.
Should PDF generation happen in JavaScript or on the server?
Use client-side conversion for a browser-only feature with acceptable rendering trade-offs; use a server or hosted service when you need controlled rendering, secrets, or consistent output.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesWhat does the 50 MB limit mean?
It is Cloudflare Browser Run’s documented request-body limit for its /pdf endpoint, not a universal HTML-to-PDF limit.
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.

