Use chromedp to control Chrome or Chromium from Go: navigate to the URL, call Chrome’s DevTools Protocol PrintToPDF command, then write the returned bytes to a file. This approach renders JavaScript-driven pages in a browser and exposes controls for paper size, margins, backgrounds, orientation, and more. You need a working Chrome or Chromium runtime as well as Go.
Convert a URL to PDF with Go and chromedp
The basic workflow is navigation followed by printing the rendered page through Chrome’s DevTools Protocol (CDP). This complete program accepts a URL and optional output path as command-line arguments, sets a timeout, prints the page with backgrounds, and writes the PDF.
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/chromedp/chromedp"
"github.com/chromedp/cdproto/page"
)
func main() {
if len(os.Args) < 2 {
fmt.Fprintln(os.Stderr, "usage: go run . <url> [output.pdf]")
os.Exit(2)
}
url := os.Args[1]
output := "output.pdf"
if len(os.Args) > 2 {
output = os.Args[2]
}
if err := convert(url, output); err != nil {
fmt.Fprintln(os.Stderr, "convert:", err)
os.Exit(1)
}
fmt.Println("Wrote", output)
}
func convert(url, output string) error {
// Bound the entire browser operation. Set this to fit your pages and environment.
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
// chromedp starts or connects to Chrome/Chromium using its allocator defaults.
ctx, cancel = chromedp.NewContext(ctx)
defer cancel()
var pdf []byte
err := chromedp.Run(ctx,
chromedp.Navigate(url),
chromedp.ActionFunc(func(ctx context.Context) error {
var err error
pdf, _, err = page.PrintToPDF().
WithPrintBackground(true).
WithDisplayHeaderFooter(false).
Do(ctx)
return err
}),
)
if err != nil {
return err
}
return os.WriteFile(output, pdf, 0o644)
}
Initialize the module and add chromedp, then run the program with the target URL:
go mod init example.com/urltopdf
go get github.com/chromedp/chromedp
go run . https://example.com report.pdf
Use a current Go toolchain and make Chrome or Chromium available to the process. The chromedp project documents browser availability as a prerequisite: chromedp. The Go package import for page.PrintToPDF is github.com/chromedp/cdproto/page; CDP’s generated API documents the print command and its options at cdproto/page and PrintToPDFParams.
Recommended Free Tools
#1 Best Overall
- PORTABLE SCANNER FOR USE ON-THE-GO — The fastest and lightest mobile single-sheet-fed compact document scanner in its class¹
- QUICK DOCUMENT SCANNING ― This Epson ultra-fast scanner scans a single page as quickly as 5.5 seconds²; Windows and Mac compatible
- VERSATILE PAPER HANDLING ― Portable scanner scans documents up to 8.5 x 72 in; Also easily digitizes receipts and ID cards to make accounting, bookkeeping, and organizing simpler
- INTUITIVE, HIGH-SPEED SOFTWARE — Epson ScanSmart Software³ is a smart tool allowing you to easily scan, review, and save; Stay organized easily with the help of this Epson scanner
- EASY SETUP — USB-powered connect to your computer for quick and simple scanning; No batteries or external power supply required to operate portable document scanner; Standard Connectivity: USB 2.0
Wait for pages that render after navigation
chromedp.Navigate waits for navigation, but an application may continue loading data, images, or fonts afterward. For a known page, wait for a meaningful selector before printing:
err := chromedp.Run(ctx,
chromedp.Navigate(url),
chromedp.WaitVisible("main article", chromedp.ByQuery),
chromedp.ActionFunc(func(ctx context.Context) error {
var err error
pdf, _, err = page.PrintToPDF().WithPrintBackground(true).Do(ctx)
return err
}),
)
Choose a selector that indicates the content you need is ready, not merely that the page shell exists. There is no universal wait duration that suits every site; tune timeouts and readiness checks to the target application. If a page uses delayed images, lazy loading, or client-side rendering, verify that the PDF contains the expected content before relying on the output.
Rank #2
- FAST SPEEDS - Scans color and black and white documents a blazing speed up to 16ppm (1). Color scanning won’t slow you down as the color scan speed is the same as the black and white scan speed.
- ULTRA COMPACT – At less than 1 foot in length and only about 1. 5lbs in weight you can fit this device virtually anywhere (a bag, a purse, even a pocket).
- READY WHENEVER YOU ARE – The DS-640 mobile scanner is powered via an included micro USB 3. 0 cable allowing you to use it even where there is no outlet available. Plug it into you PC or laptop and you are ready to scan.
- WORKS YOUR WAY – Use the Brother free iPrint&Scan desktop app for scanning to multiple “Scan-to” destinations like PC, Network, cloud services, Email and OCR. (2) Supports Windows, Mac and Linux and TWAIN/WIA for PC/ICA for Mac/SANE drivers. (3)
- OPTIMIZE IMAGES AND TEXT – Automatic color detection/adjustment, image rotation (PC only), bleed through prevention/background removal, text enhancement, color drop to enhance scans. Software suite includes document management and OCR software. (4)
Control the PDF layout
CDP’s PrintToPDF parameters let you set orientation, paper dimensions, margins, scaling, whether to include page backgrounds, headers and footers, tagged PDF output, and document outlines. Set print-related choices explicitly when repeatable output matters rather than relying on implicit defaults. See the parameter reference.
| Goal | Setting | Example |
|---|---|---|
| Landscape output | WithLandscape(true) |
Useful for wide tables or dashboards. |
| Keep page colors and background graphics | WithPrintBackground(true) |
The starter program enables this; set false if you want backgrounds omitted. |
| Show browser print headers and footers | WithDisplayHeaderFooter(true) |
Disable it for a clean document without those browser-generated elements. |
| Choose paper dimensions | WithPaperWidth(...) and WithPaperHeight(...) |
CDP dimensions are in inches; specify both for a deliberate page size. |
| Set margins | WithMarginTop(...), WithMarginBottom(...), WithMarginLeft(...), WithMarginRight(...) |
Values are in inches. |
| Adjust print scaling | WithScale(...) |
Use a deliberate scale when fitting content; check legibility after changing it. |
| Request tagged output or document outlines | WithGenerateTaggedPDF(true), WithGenerateDocumentOutline(true) |
Support is exposed by the CDP API; confirm the behavior you need in the resulting PDF. |
For example, to request landscape output with explicit dimensions and margins, extend the print call as follows:
Free tools Windows power users keep installed
One-click scans. No signup required.
Rank #3
- FAST DOCUMENT SCANNING — Document scanner with feeder allows you to speed through stacks with a 50-sheet Auto Document Feeder (ADF); Efficient office scanner to help you scan more productively
- INTUITIVE, HIGH-SPEED SOFTWARE — Quickly scan with this desktop document scanner; Epson ScanSmart Software lets you easily preview scans, email files, upload to the cloud, and more; Plus, automatic file naming saves even more time
- SEAMLESS INTEGRATION — Easily incorporate your data into most document management software with the included TWAIN driver; Office document scanner integrates seamlessly with business workflows
- EASY SHARING — Duplex scanner allows you to scan straight to email or popular cloud storage2 services like Dropbox, Evernote, Google Drive, and OneDrive for simple storage and sharing
- SIMPLE FILE MANAGEMENT — Scanner allows the creation of searchable PDFs with Optical Character Recognition (OCR) and convert scans to editable Word or Excel files effortlessly; Designed for home and office document scanning
pdf, _, err = page.PrintToPDF().
WithLandscape(true).
WithPaperWidth(11).
WithPaperHeight(8.5).
WithMarginTop(0.4).
WithMarginBottom(0.4).
WithMarginLeft(0.4).
WithMarginRight(0.4).
WithPrintBackground(true).
WithDisplayHeaderFooter(false).
Do(ctx)
The precise result depends on the page’s print styles and content. A very wide page may still wrap, and shrinking it to fit can make text hard to read. Inspect representative output when choosing dimensions and scale.
Choose a rendering method for your deployment
Chrome-based rendering is not the only way to create a PDF, but the alternatives differ in runtime, browser fidelity, and operational control. The choice depends on what your pages require and what you can operate.
Rank #4
- Scanner type: Document
- Connectivity technology: USB
- With Auto Scan Mode, the scanner automatically detects what you're scanning
- Digitize documents and images
| Path | Good fit | Trade-offs and available controls |
|---|---|---|
| chromedp with Chrome or Chromium | Go services and JavaScript-heavy pages that need browser rendering and programmatic control | Requires an available browser runtime. CDP offers paper dimensions, margins, scale, backgrounds, headers and footers, tags, and outlines. chromedp prerequisites; CDP options. |
| wkhtmltopdf | Teams comfortable invoking an external executable and using its URL and page options | Its documented options include cookies, JavaScript execution, copies, DPI, covers, and table-of-contents objects. Usage reference; Project site. |
| Hosted GoPDF API | Deployments that prefer not to package or operate a browser | The API reference describes authentication, a URL field at POST /convert, PDF options, and optional storage/debug behavior. Check service limits, data handling, pricing, and terms directly before choosing it. API reference. |
| Chrome headless command line | Simple scripts that can run Chrome as a separate process | Chrome documents --headless --print-to-pdf and a flag to omit print headers and footers. Calling it from Go means managing an external process. Chrome headless documentation. |
Compare the choices on four practical axes: whether the pages depend on JavaScript and modern CSS, what browser or binary you must deploy, how much print layout control you need, and the privacy and security implications of fetching each URL. A rendering tool does not guarantee access to pages behind logins, geographic restrictions, robots policies, or anti-bot challenges; treat those as separate access and authorization problems.
Or skip the browser setup
If you would rather call a managed endpoint than install and operate Chrome, ScreenshotNeo accepts a URL and returns a PDF. See the ScreenshotNeo documentation for request options. Example using cURL:
Best Value
- OUR MOST ADVANCED SCANSNAP. Large touchscreen, fast 45ppm double-sided scanning, 100-sheet document feeder, Wi-Fi and USB connectivity, automatic optimizations, and support for cloud services. Upgraded replacement for the discontinued iX1600
- CUSTOMIZABLE. SHARABLE. Select personalized profiles from the touchscreen. Send to PC, Mac, mobile devices, and clouds. QUICK MENU lets you quickly scan-drag-drop to your favorite computer apps
- STABLE WIRELESS OR USB CONNECTION. Built-in Wi-Fi 6 for the fastest and most secure scanning. Connect to smart devices or cloud services without a computer. USB-C connection also available
- PHOTO AND DOCUMENT ORGANIZATION MADE EFFORTLESS. Easily manage, edit, and use scanned data from documents, receipts, photos, and business cards. Automatically optimize, name, and sort files
- AVOIDS PAPER JAMS AND DAMAGE. Features a brake roller system to feed paper smoothly, a multi-feed sensor that detects pages stuck together, and skew detection to prevent paper damage and data loss
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o page.pdf
Request PDF output using the API’s documented format options. ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents use screenshot tools, and the free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Learn about ScreenshotNeo, or sign up free for 1,000 screenshots a month with no card.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Make URL-to-PDF conversion safer and more reliable
In production, the renderer is also an HTTP client that can reach network destinations. Treat every submitted URL as untrusted input, especially if users can supply it. These are engineering safeguards, not guarantees provided by CDP:
- Allow only the URL schemes and destinations your application needs. Apply outbound network controls so a submitted URL cannot reach internal services or sensitive infrastructure.
- Set an overall deadline for navigation and rendering, and choose a bounded output size. A slow or unusually large page should not consume resources indefinitely.
- Isolate the browser process and run it with only the permissions it requires. Avoid passing secrets to pages unless the workflow specifically requires them.
- Handle redirects and authentication deliberately. A redirect can change the destination, and a login-dependent page will not become accessible simply because it is printed.
- Close contexts and release browser resources when work finishes. For high-throughput systems, manage browser lifecycle and concurrency deliberately instead of starting unbounded work.
- Check the returned error and validate that the output is a usable PDF before delivering it to another system.
The cited browser and CDP documentation describes APIs and options; it does not certify a particular deployment’s threat model, performance, or reliability. Measure behavior with the pages and runtime you actually intend to support.
Troubleshoot common conversion failures
| Symptom | Likely cause | What to check or change |
|---|---|---|
| Chrome cannot be started or found | The runtime cannot locate or launch a compatible Chrome or Chromium installation. | Install or make the browser executable available to the service account and verify that the process can launch it. Review the chromedp setup guidance. |
| Navigation or printing times out | The page is slow, continues making requests, or waits on client-side work. | Use a bounded but appropriate deadline; wait for a meaningful selector or readiness condition instead of guessing a universal delay. Check network access from the process. |
| The PDF is blank or missing content | Printing began before the required content rendered, the URL redirected, or access was blocked. | Confirm the final page and its authorization requirements, wait for the content selector, and inspect the captured page in a browser under the same network conditions. |
| Colors or images are absent | Background printing is disabled or the page’s assets/styles are not available when printed. | Enable WithPrintBackground(true) and check that the page’s resources finish loading. Inspect print-specific CSS as well as screen rendering. |
| Layout is clipped, wrapped, or too small | Paper size, margins, orientation, scale, or the page’s print styles do not suit its content. | Set dimensions, margins, orientation, and scale explicitly, then inspect the PDF at normal reading size. Consider landscape for wide content. |
| The page shows a CAPTCHA or access-denied response | The target site is restricting automated access. | Do not treat a challenge as a PDF-rendering defect. Use an authorized access method or obtain permission; the cited tools do not promise to bypass restrictions. |
Frequently asked questions
Does this work for pages that require JavaScript?
Yes, when Chrome or Chromium can load the page and its scripts. Since the PDF is printed from a browser-rendered page, add a page-specific readiness check if the application populates content after initial navigation.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteCan I print a URL that requires a login?
Only if the browser session is authorized and configured with the necessary authentication state, such as appropriate cookies. The basic example does not log in or supply credentials; implement access deliberately and protect any secrets.
Should I use chromedp or wkhtmltopdf?
Use chromedp when you need Chrome’s rendering and CDP’s print controls from Go. Consider wkhtmltopdf when its external executable and documented options fit your pages and deployment. Test the actual layouts you need; the available documentation does not establish a universal fidelity or speed winner.
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.

