How to Convert HTML Code to PDF Online for Free
Convert HTML to PDF free with browser print, online converters, or an automated API. Follow the exact steps, code, layout fixes, and privacy guidance.
Fast answer: open the rendered HTML in Chrome, Edge, or Firefox, press Ctrl+P (Windows/Linux) or ⌘+P (Mac), choose Save as PDF, set the paper size and margins, enable background graphics when needed, preview every page, and save. This is free and requires no upload.
If you need repeatable conversions, paste raw HTML into an online converter or send a public URL to an HTML-to-PDF API. For confidential HTML, use your local browser or a self-hosted renderer after checking the provider’s retention policy.
1. Convert HTML to PDF with your browser
Browser printing is the quickest free method for a one-off document or a local .html file.
- Save your code as
document.html, or open the web page you want to convert. - Open the file in Chrome, Edge, or Firefox.
- Open Print with Ctrl+P on Windows/Linux or ⌘+P on macOS. Chrome documents this keyboard shortcut and the File > Print path. Chrome’s print instructions
- Choose Save as PDF in Chrome or Firefox. Edge offers the equivalent PDF destination in its print dialog.
- Choose A4 or Letter, portrait or landscape, margins, scale, and a page range.
- Turn on Background graphics if colored sections, gradients, or background images are missing. Edge documents this setting and its scale, header, and footer controls. Microsoft Edge print guidance
- Check the preview page by page, then save the PDF.
Minimal HTML example
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Invoice</title>
<style>
@page { size: A4; margin: 18mm; }
body { font: 14px/1.5 Arial, sans-serif; color: #222; }
h1 { color: #123b66; }
.total { break-inside: avoid; font-weight: 700; }
@media print {
.no-print { display: none; }
a { color: inherit; text-decoration: none; }
}
</style>
</head>
<body>
<h1>Invoice #1042</h1>
<p>Design and development services</p>
<p class="total">Total: $25.00</p>
<button class="no-print" onclick="window.print()">Print</button>
</body>
</html>
Print settings that affect the result
| Setting | Use it when |
|---|---|
| Paper size | The document must match A4, Letter, or another paper standard. |
| Orientation | Use landscape for wide tables, dashboards, and code samples. |
| Margins | Reduce them for dense layouts, but leave enough room for printers or binding. |
| Scale | Fit a slightly wide layout onto a page; inspect text size after scaling. |
| Background graphics | Required when color blocks or background images are part of the design. |
| Headers and footers | Turn them off for a clean document, or on when the URL and page number are useful. |
| Page range | Export selected pages from a long document. |
2. Make HTML print correctly
A PDF is produced from the rendered page, so layout, fonts, images, and JavaScript must be ready before printing.
- Use
@media printto hide navigation, buttons, cookie notices, and other interactive controls. - Use
@pagefor paper size and margins. - Use
break-inside: avoidon cards, totals, table rows, and other units that should stay together. - Use
break-beforeorbreak-afterfor deliberate section starts. - Keep tables within the printable width; wide code blocks may overflow or become unreadable.
- Use web-safe fonts or confirm that external fonts have loaded before printing.
- Wait for images and JavaScript-generated content to finish. A converter may capture the page before late resources appear.
@media print {
nav, .toolbar, .cookie-banner, .chat-widget { display: none !important; }
.invoice-card, table, pre { break-inside: avoid; }
a { color: #000; text-decoration: none; }
}
@page {
size: Letter portrait;
margin: 0.6in;
}
3. Paste raw HTML into an online converter
Use this route when you have HTML code but do not want to open a local file. Look for a service that explicitly accepts raw HTML, because some online tools accept only a public URL.
- Open the converter’s HTML input or playground.
- Paste the complete document, including its
<style>and script blocks. - Choose paper size, orientation, margins, and any background option.
- Preview the output and download the PDF.
HTML2PDF.app documents conversion from raw HTML markup or a publicly reachable URL and says its conversions run in headless Chromium. Its documentation also notes that CSS media mode, available fonts and resources, and JavaScript timing affect rendering. HTML2PDF.app documentation
HTMLPDF.dev advertises a playground for pasted HTML and documents an API that accepts either url or html, with paper and margin options. HTMLPDF.dev documentation
4. Automate HTML-to-PDF conversion with an API
For invoices, reports, or batch jobs, send HTML or a public URL to a provider’s authenticated endpoint and write the binary response to a .pdf file. The endpoint, authentication header, and option names differ by provider; use the provider’s current documentation instead of copying a placeholder URL.
curl -X POST 'https://api.example.invalid/pdf' \\
-H 'Content-Type: application/json' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-d '{"html":"<h1>Invoice</h1><p>Total: $25</p>","format":"A4"}' \\
--output invoice.pdf
HTML2PDF.app, HTMLPDF.dev, and HTML2PDF.co.uk document this general authenticated-request pattern. Check each service’s retention and pricing terms before sending customer or financial data.
5. Or skip the browser setup
ScreenshotNeo captures a reachable web page and can return a PDF as well as PNG, JPEG, or WebP. It is useful when your HTML is deployed at a URL and you need a repeatable capture. The API can wait for a selector, a delay, or network idle; set paper size, margins, landscape mode, and page ranges; load lazy images; run custom CSS or JavaScript; and set headers, cookies, user agent, timezone, and geolocation. See the ScreenshotNeo API documentation for the current request options.
cURL
curl -G "https://api.screenshotneo.com/v1/shot" \\
-d access_key=YOUR_API_KEY \\
--data-urlencode url=https://your-site.example/invoice.html \\
-o invoice.pdf
Python
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://your-site.example/invoice.html"},
timeout=90,
)
r.raise_for_status()
open("invoice.pdf", "wb").write(r.content)
Node.js
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://your-site.example/invoice.html'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('invoice.pdf', Buffer.from(await res.arrayBuffer()));
ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. One thousand screenshots per month are free with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
6. Choosing the right method
| Need | Best starting point | Trade-off |
|---|---|---|
| One local document | Browser print | Manual, but free and private. |
| Paste HTML once | Online playground | Convenient; review privacy and resource-loading behavior. |
| Recurring conversions | Authenticated API | Requires an account, key management, and error handling. |
| HTML already deployed | ScreenshotNeo PDF capture | Automated URL capture with cleanup, waiting, and PDF controls. |
7. Troubleshooting
Colors or images are missing
Enable background graphics, verify the asset URLs, and wait until images and fonts load. Relative paths that work locally may fail in an online converter.
The PDF has an extra blank page
Inspect large fixed heights, bottom margins, and elements that overflow the printable area. Remove unnecessary height rules and test again with a smaller margin.
Content is cut off or too wide
Switch to landscape, reduce scale, constrain tables and code blocks, or add print-specific widths. Avoid placing a wide flex or grid container outside the page width.
JavaScript content is absent
Print only after the page has rendered. For automation, use a renderer that supports JavaScript and configure a selector, delay, or network-idle wait.
Fonts look different
Confirm the font request succeeds and that the converter can reach it. Use a fallback stack and avoid relying on a font installed only on your computer.
The API returns an error
Check the URL is publicly reachable, the API key is sent in the documented location, and the request timeout is long enough for the page. Log the HTTP status and response body without exposing the key.
A sensitive document was uploaded
Read the provider’s retention policy. HTML2PDF.co.uk says PDFs are served from memory and POSTed HTML is not stored, while URLs may appear in conversion history. HTML2PDF.app says processing is temporary but selected metadata or a source URL may be retained in logs. For confidential material, prefer local or self-hosted conversion.
8. Performance, reliability, and cost
- Reduce work: inline critical CSS, compress images, and remove unused scripts before conversion.
- Make output deterministic: pin fonts, paper settings, and print CSS; avoid content that changes during capture.
- Handle retries: retry transient network failures with a limit and backoff, but do not blindly repeat invalid requests.
- Watch long pages: split very large reports or capture selected page ranges when supported.
- Budget API usage: check free quotas, per-document limits, and whether failed jobs are billed. ScreenshotNeo bills only clean shots; failed loads, blank pages, bot checks, timeouts, and cache hits are free.
- Protect credentials: keep API keys on the server or in trusted jobs. HTML2PDF.app specifically advises using its key from backend code rather than browser code.
9. FAQ
Can I convert HTML code without hosting it?
Yes. Browser print works from a local file, and a converter that accepts raw HTML can process pasted markup. A URL-based API requires the page to be reachable by that service.
Does browser print include JavaScript?
It prints the rendered state that exists when you open Print. Wait for asynchronous content to finish first.
Should I use A4 or Letter?
Use the paper size required by your audience or printer. Set it explicitly in print CSS and the print dialog.
Can I convert an HTML page with login-only content?
A local browser can access your session. A hosted converter needs a supported authentication method such as headers or cookies, and you should review its data-retention policy.
Is an online converter safe for private HTML?
It depends on the provider’s handling and retention. For sensitive documents, local or self-hosted rendering keeps the source off a third-party service.


