Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You can generate a PDF from a web page in a Java application, but Puppeteer itself is not a Java library: it is a JavaScript browser-automation library. The practical choices are to run Puppeteer in a separate Node.js process that Java coordinates, or have Java send an HTTP request to a hosted browser service. For a fully Java-based integration, Browserless publishes a Java example that requests a PDF from its hosted endpoint.

What “Puppeteer in Java” means

Puppeteer provides a high-level JavaScript API for automating Chrome and Firefox. It does not expose a native Java API. That distinction matters when choosing how to deploy the conversion: a Java program can start or communicate with a separate JavaScript process, but it cannot call Puppeteer as though it were a JVM library. Chrome for Developers describes Puppeteer as a JavaScript library.

If you specifically want Puppeteer to render the page, use Node.js and Puppeteer for the browser work. If you need Java to make the conversion request, a hosted browser/PDF API can be called using Java’s HTTP client; this is an HTTP integration, not Puppeteer running inside the JVM.

Choose an implementation architecture

Approach Browser ownership Control Data and operations
Java coordinates a local Node.js/Puppeteer process You install, operate, and patch Node.js and the browser environment. Direct access to Puppeteer navigation, page interaction, readiness conditions, and PDF options. More deployment and process-management work. Page requests originate from the environment running the browser.
Java calls a hosted PDF endpoint The provider operates the browser service. Control is limited to the endpoint’s documented request options. Avoids managing a local browser process, but adds a provider dependency; the page URL and request credentials are sent to that service. Check the provider’s current limits, data-handling terms, and pricing before deployment.

Browserless documents both a PDF endpoint that accepts a URL or raw HTML and a Java HTTP-client example. Its cited documentation establishes the request shape, but not current prices or account-specific service limits. Browserless PDF endpoint documentation.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • 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.

Generate a PDF with Puppeteer and Node.js

This is the direct Puppeteer workflow: launch a browser, open a page, navigate to the URL, create the PDF, and close the browser. Install Node.js, create a project, and add Puppeteer with npm install puppeteer. Save the following as url-to-pdf.js:

const puppeteer = require('puppeteer');

async function main() {
  const url = process.argv[2];
  const outputPath = process.argv[3] || 'page.pdf';

  if (!url) {
    throw new Error('Usage: node url-to-pdf.js <url> [output.pdf]');
  }

  const browser = await puppeteer.launch({ headless: true });
  try {
    const page = await browser.newPage();
    await page.goto(url, { waitUntil: 'networkidle2' });
    await page.pdf({
      path: outputPath,
      format: 'A4',
      printBackground: true,
      margin: { top: '12mm', right: '12mm', bottom: '12mm', left: '12mm' }
    });
    console.log(`Saved PDF to ${outputPath}`);
  } finally {
    await browser.close();
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Run it with node url-to-pdf.js "https://example.com" output.pdf. The URL must be reachable from the machine running the browser. Puppeteer’s official guide demonstrates navigation with networkidle2 and PDF generation; it also says page.pdf() waits for fonts to load by default. Puppeteer PDF generation guide.

Coordinate the Node process from Java

If the Java application must own the workflow, it can invoke the Node script as a child process. This example passes the URL and output path as separate arguments rather than building a shell command string:

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 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.
import java.io.IOException;
import java.nio.file.Path;

public class ConvertUrlToPdf {
    public static void main(String[] args) throws IOException, InterruptedException {
        if (args.length < 1 || args.length > 2) {
            throw new IllegalArgumentException(
                "Usage: java ConvertUrlToPdf <url> [output.pdf]");
        }

        String url = args[0];
        Path output = Path.of(args.length == 2 ? args[1] : "page.pdf");

        Process process = new ProcessBuilder(
                "node", "url-to-pdf.js", url, output.toString())
            .inheritIO()
            .start();

        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new IOException("Puppeteer conversion failed; Node exit code: " + exitCode);
        }
        System.out.println("Saved PDF to " + output.toAbsolutePath());
    }
}

Compile and run with a JDK that supports Path.of: javac ConvertUrlToPdf.java, then java ConvertUrlToPdf "https://example.com" result.pdf. In a server application, also set an appropriate process timeout and capture standard output and error instead of allowing unbounded child processes. Restrict which URLs the application will fetch if users supply them; otherwise, the browser process may be used to reach internal services that should not be exposed.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Call a hosted PDF service from Java

When you want Java to send an HTTP request rather than manage Chromium, Browserless’s documentation shows a Java HttpClient POST integration. The endpoint takes a JSON body with a page URL and PDF options and returns PDF bytes with an application/pdf response. The following is a request-shape example; set the endpoint and token according to the provider’s current documentation and account configuration.

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;

public class HostedPdf {
    public static void main(String[] args) throws Exception {
        String endpoint = System.getenv("PDF_ENDPOINT");
        String token = System.getenv("PDF_API_TOKEN");
        String url = args[0];

        if (endpoint == null || token == null) {
            throw new IllegalStateException("Set PDF_ENDPOINT and PDF_API_TOKEN");
        }

        String json = "{"url":"" + escapeJson(url)
            + "","options":{"format":"A4","
            + ""printBackground":true,"displayHeaderFooter":false}}";

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(endpoint + "?token=" + token))
            .timeout(Duration.ofSeconds(90))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json))
            .build();

        HttpResponse<byte[]> response = HttpClient.newHttpClient().send(
            request, HttpResponse.BodyHandlers.ofByteArray());
        if (response.statusCode() < 200 || response.statusCode() >= 300) {
            throw new IllegalStateException("PDF service returned HTTP "
                + response.statusCode() + ": "
                + new String(response.body(), java.nio.charset.StandardCharsets.UTF_8));
        }
        Files.write(Path.of("page.pdf"), response.body());
    }

    private static String escapeJson(String value) {
        return value.replace("\", "\\").replace(""", "\"");
    }
}

For production code, use a JSON library to build and escape the request body, validate that the successful response is a PDF, and avoid logging tokens. The provider’s official Java example documents the endpoint pattern and PDF options; do not assume a token parameter, endpoint path, or available option is identical across providers or account types. See the Browserless endpoint documentation for the current request contract.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • 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.

Set PDF rendering behavior deliberately

Print CSS or screen CSS

page.pdf() renders using the CSS print media type by default. If the PDF should use the page’s screen styles, call await page.emulateMediaType('screen') before page.pdf(). Print styles can change visibility, layout, and colors, so compare the output against the intended document rather than assuming it will match a browser window. The Puppeteer API reference for Page.pdf() describes the media behavior.

Color, backgrounds, and page geometry

For backgrounds, set printBackground: true; otherwise they are not printed by default. Puppeteer applies print-oriented color adjustment. If exact brand colors matter, the API reference points to CSS such as -webkit-print-color-adjust: exact, but the site’s own CSS and print layout still affect the result. Choose paper format, margins, and orientation to suit the content. For a hosted API, use only options documented for its endpoint.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Readiness for dynamic pages

networkidle2 is a useful navigation condition, not a guarantee that every application has finished rendering. Pages with polling, lazy-loaded sections, delayed API calls, or client-side transitions may need an application-specific readiness condition. Puppeteer can wait for a selector or other condition before PDF generation; prefer evidence that the content is ready over an arbitrary fixed delay. A delay may work for a known page but can be wasteful on fast loads and too short on slow ones.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • 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

PDF details that are easy to miss

  • Headers and footers: Browserless’s example exposes header/footer settings. Validate the resulting page numbering and margins for the endpoint you use; headers and footers can consume printable space.
  • Page ranges: If requesting only selected pages from a hosted endpoint, ensure the ranges cover every page you intend to retain. Browserless warns that pages outside specified ranges can be silently omitted and out-of-range requests can cause an error.
  • Metadata: Puppeteer’s documented page.pdf() flow does not provide built-in PDF metadata options such as title or author. Browserless says metadata can be adjusted afterward with a PDF library.
  • Tagged PDF and accessibility: Browserless documents tagged output as structural information derived from source markup, not certified PDF/UA output. Validate separately if formal accessibility conformance is required.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common conversion failures

Symptom Likely cause What to check
Java cannot find node or the script Node.js is missing from the Java process environment, or the working directory is not where the script lives. Check node --version, use an absolute script path in ProcessBuilder, and set the process working directory when needed.
The PDF is blank or missing content The page rendered a print-specific layout, navigation finished before application content appeared, or the URL redirected to an error/login page. Inspect the page in the same browser environment, test screen media if appropriate, wait for the needed selector, and verify that the browser can access the final URL.
Colors or backgrounds differ Print media and print color adjustment affect output; backgrounds may be disabled. Set printBackground: true, consider screen media when that is the desired design, and use the print-color CSS guidance for exact colors.
Some images or fonts are absent Resources were not ready or cannot be reached from the browser environment. Confirm resource URLs are reachable and authenticated as needed; wait for the specific content. Puppeteer waits for fonts in its documented PDF flow, but that does not repair failed font requests.
Hosted request returns an error instead of a PDF Incorrect endpoint/token, malformed JSON, unsupported options, provider limits, or failure to load the target page. Check HTTP status and response body, verify the provider’s current API contract and account limits, and test the page URL from the service’s network context.
PDF omits pages or range request errors Requested page ranges leave gaps or exceed the document’s page count. Adjust the range to include the pages required and confirm the rendered page count before splitting.

Performance, reliability, and cost considerations

A local browser gives control but requires deployment capacity for Node.js and Chromium, process lifecycle handling, and browser updates. Reusing a browser process may avoid repeated startup overhead, but it also requires careful isolation and cleanup between jobs. Apply timeouts to navigation and the Java process, bound concurrency to available resources, and close pages and browsers after failures as well as successes.

A hosted endpoint reduces local browser operations but makes conversion dependent on provider availability, network transfer, account quotas, and service policies. The documentation cited here does not establish current pricing or tier limits, so check the provider before estimating recurring cost. Consider whether the target page or credentials may be sent outside your infrastructure before selecting a hosted service.

Or skip the browser setup

ScreenshotNeo is a website screenshot API that can also return PDFs. A single GET request sends the URL to its API; for example, using cURL:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 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.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o page.pdf

See the ScreenshotNeo API documentation for PDF options and setup. Cookie banners, popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for ScreenshotNeo’s free plan.

Frequently Asked Questions

Can Java call Puppeteer directly?

No. Puppeteer is a JavaScript library, so Java must coordinate a separate Node.js process or call a browser service over HTTP.

Does Puppeteer create a PDF using screen CSS by default?

No. Puppeteer’s PDF generation uses print media by default; emulate screen media before generating the PDF if that is the intended styling.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.