To create a PDF from HTML in Go, run Chrome or Chromium headlessly and use the chromedp package to call Chrome DevTools Protocol’s Page.printToPDF. Chrome renders the page; Go receives the resulting PDF bytes and writes them to a file. For a separately operated conversion service, Gotenberg accepts HTML and assets or a hosted URL through an HTTP API.
Use chromedp to render HTML with headless Chrome
chromedp is a Go driver for browsers that support Chrome DevTools Protocol (CDP); it does not render HTML itself. Install a compatible browser in the runtime, then use Go to navigate or load the document, wait until it is ready, and ask Chrome to print it. Chrome runs headlessly by default, and the project points to its headless-shell image as an option for headless deployments. See the chromedp project and its official examples.
Install the Go dependency
From your Go module directory, add chromedp:
go get github.com/chromedp/chromedp
You also need a Chrome-compatible browser available to the process. In containers or other headless environments, use a browser setup compatible with chromedp; the project documents its headless-shell image as one option.
Runnable example: navigate to a page and save a PDF
This example takes a URL from the first command-line argument and writes a PDF to the second. It uses a timeout, checks each error, and explicitly enables printed backgrounds. Save it as main.go, install the dependency, and run it with a URL and output path.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →#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.
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/chromedp/chromedp"
"github.com/chromedp/cdproto/page"
)
func main() {
if len(os.Args) != 3 {
fmt.Fprintf(os.Stderr, "usage: %s URL output.pdfn", os.Args[0])
os.Exit(2)
}
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
var pdfBytes []byte
err := chromedp.Run(ctx,
chromedp.Navigate(os.Args[1]),
chromedp.ActionFunc(func(ctx context.Context) error {
data, _, err := page.PrintToPDF().
WithPrintBackground(true).
Do(ctx)
if err != nil {
return err
}
pdfBytes = data
return nil
}),
)
if err != nil {
fmt.Fprintln(os.Stderr, "render PDF:", err)
os.Exit(1)
}
if err := os.WriteFile(os.Args[2], pdfBytes, 0o644); err != nil {
fmt.Fprintln(os.Stderr, "write PDF:", err)
os.Exit(1)
}
}
Run it, for example, as go run . https://example.com output.pdf. The core flow follows chromedp’s documented example: create a context, run browser actions, call page.PrintToPDF().Do(ctx), and write the returned bytes. The timeout and explicit background setting are included here for an application-shaped example.
Wait for dynamic pages before printing
Navigation completing does not necessarily mean a JavaScript application has finished rendering the content you need. For dynamic pages, add a readiness condition before the print action, such as waiting for a known selector or an application-ready signal. Otherwise the PDF can capture a loading state or omit content that appears later. For local HTML templates, ensure the browser can resolve relative stylesheets, fonts, images, and scripts; the cited chromedp example demonstrates navigation to a URL, not every local-file arrangement.
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.
Set print layout intentionally
The CDP print command exposes paper dimensions in inches, margins, orientation, scale, page ranges, header/footer templates, CSS page-size preference, tagged output, and document outlines. Page ranges are one-based. Decide these settings based on the document instead of relying on defaults. The generated Page API documentation shows that print backgrounds, CSS page-size preference, tagged PDF generation, and document outlines default to false.
- Paper and orientation: Set width and height or use landscape mode for wide tables. Use CSS
@pagedimensions only when you also enable the protocol’s CSS page-size preference. - Margins and scale: Tune all four margins and scale for forms, invoices, and tables. Incorrect choices can clip content or shrink it more than intended.
- Backgrounds: Enable
WithPrintBackground(true)if colored backgrounds or other background graphics are part of the design. - Headers, footers, and ranges: Add header or footer HTML when needed, and use one-based page ranges to restrict output.
- Accessibility and navigation: Consider tagged PDF generation or document outlines when those output properties matter.
Validate the resulting PDF with representative documents, including long tables, page breaks, fonts, and images. Available options do not guarantee that a particular HTML template will paginate as intended.
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.
Use Gotenberg when conversion should run as a service
Gotenberg packages conversion tools behind a Docker-based HTTP API. A Go application can send an HTML document and assets to its Chromium conversion endpoint or ask it to convert a hosted URL. This moves browser operation out of the Go process, but means your team operates the service and ensures it can access the needed files and network resources. See the Gotenberg introduction and Chromium conversion documentation.
Convert an HTML file and its assets
For HTML input, submit a multipart form to POST /forms/chromium/convert/html. The HTML file must be named index.html; include supporting assets with the document as needed. Gotenberg documents layout and print options, waiting behavior, and handling for resource failures and HTTP status codes in its conversion documentation.
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
Convert a hosted page
For a page already hosted at a URL, use POST /forms/chromium/convert/url and provide the required URL form value. The route supports JavaScript execution and dynamic or SPA rendering. It rejects file:// URLs; use the HTML or Markdown route for local documents instead. Follow the Gotenberg documentation for the exact form fields and request format.
Account for defaults and deployment
Gotenberg documents a default page size of 8.5 by 11 inches, margins of 0.39 inches, and printBackground set to false. Set these deliberately if your document requires different dimensions, margins, or background printing. The service’s Docker/API design separates conversion from the Go runtime; the trade-off is operating that service and making sure the submitted HTML, assets, and required network access are available to it.
Recommended Free Tools
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.
Choose the right conversion architecture
| Decision | chromedp in the Go application | Gotenberg service |
|---|---|---|
| Interface | Go code drives Chrome DevTools Protocol directly. | HTTP multipart requests go to conversion endpoints. |
| Browser ownership | The application deployment must provide a compatible browser; chromedp documents headless-shell as an option. | The browser is part of a separately deployed Docker-based API. |
| Control | Direct browser actions and protocol options. | Centralized routes and form options for HTML, URL, and output behavior. |
| Best fit | Choose this when direct browser control from Go matters and your runtime can provide Chrome. | Choose this when you prefer a separate conversion API boundary. |
If you want to compare browser-driver APIs, go-rod is another Go CDP driver; its official examples include Page.PDF and MustPDF.
Troubleshoot common HTML-to-PDF failures
- Chrome does not start or connect: Confirm a compatible browser is installed and available to the process, and that the deployment supports its headless runtime. A lost or terminated browser connection cancels the chromedp context.
- The PDF is blank or content is missing: Wait for a known selector or application-ready signal before printing. Check that the page and its scripts have loaded in the browser.
- Images, fonts, or styles are missing: Verify that referenced assets resolve from the browser or conversion service, including relative paths and network access. For Gotenberg HTML conversion, submit required assets with the HTML.
- Colors or background graphics disappear: Enable background printing; it is disabled by default in the cited CDP API options and in Gotenberg’s documented defaults.
- Content is clipped or unexpectedly scaled: Set page dimensions, margins, scale, and orientation. If CSS
@pagesize should control the paper dimensions, enable CSS page-size preference. - The Go process times out: Increase or tune the context deadline for the page and its assets, and make the readiness condition match the page’s actual render behavior. A timeout should be reported as a failed conversion, not treated as a complete PDF.
- Gotenberg rejects a local file URL: Its URL conversion route rejects
file://; submit the HTML through the HTML conversion route instead.
Or skip the browser setup
ScreenshotNeo is a website screenshot API with PDF output. A single request can capture a URL as a PDF, while the service removes cookie banners, popups, and chat widgets before capture. Bot checks, blank pages, and failed loads are never billed. It also provides an MCP server for AI agents to take screenshots.
For example, use cURL to save a URL as a PDF:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -d format=pdf -o page.pdf
See the ScreenshotNeo API documentation for request options and PDF settings. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Sign up for ScreenshotNeo free.
Frequently Asked Questions
Can Go turn an HTML string directly into a PDF with chromedp?
The documented chromedp example navigates to a URL. For an HTML string or template, first make it available to the browser and ensure its assets resolve, then use the same print-to-PDF flow.
Does chromedp generate the PDF?
No. chromedp controls a Chrome-compatible browser from Go; Chrome or Chromium renders the page and produces the PDF.
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.

