October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
HTML to PDF

How to Load JavaScript from a URL When Converting HTML to PDF in Java

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.

If a web page builds or changes its content with JavaScript, fetching its URL as HTML in Java will not run that code. Use a browser engine such as Playwright for Java to open the page, wait until the required content is ready, and print the rendered page to PDF. A library such as iText pdfHTML can convert fetched HTML, but its converter does not evaluate JavaScript.

Why fetching a URL does not run its JavaScript

A URL request can retrieve the initial HTML document without creating the browser environment that executes its scripts. Many pages load data after the initial response, then use JavaScript to insert or update visible content. A converter that only receives HTML may therefore produce a PDF with missing sections, placeholders, or an empty app area.

iText’s documented URL workflow opens a Java URL stream and passes it to pdfHTML. That retrieves HTML for conversion; it does not make pdfHTML execute page scripts. iText explicitly states that pdfHTML does not evaluate JavaScript. See iText’s explanation of browser-engine requirements.

For JavaScript-dependent pages, use a real browser engine in your Java workflow. It runs the page’s scripts, loads browser-rendered styles and assets, and can print the rendered page. For static or otherwise compatible HTML that does not rely on script execution, a direct HTML-to-PDF converter may be simpler.

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

Use Playwright for JavaScript-dependent pages

Playwright’s Java API can navigate to a URL and generate a PDF with page.pdf(). Navigation readiness and application readiness are separate: a navigation event can complete before a page’s asynchronous data has appeared. Wait for a meaningful, page-specific condition before printing.

Runnable Java example

Add the Playwright Java dependency using the installation instructions for the release you select, install its required browser binaries, and ensure the deployment environment can launch Chromium. The exact dependency version is intentionally not pinned here; check the current Playwright Java installation guide for the version and installation commands appropriate to your project.

This example navigates, checks for a successful HTTP response, waits for a report-specific selector, and writes a PDF. Replace the URL and selector with ones from your page.

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.Response;
import java.nio.file.Paths;

public class UrlToPdf {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch(
          new BrowserType.LaunchOptions().setHeadless(true));
      try {
        Page page = browser.newPage();
        page.setDefaultNavigationTimeout(30_000);
        page.setDefaultTimeout(15_000);

        Response response = page.navigate(
            "https://example.com/report",
            new Page.NavigateOptions().setWaitUntil(
                com.microsoft.playwright.options.WaitUntilState.DOMCONTENTLOADED));

        if (response == null || !response.ok()) {
          throw new IllegalStateException("Navigation did not return a successful HTTP response"
              + (response == null ? "" : ": " + response.status()));
        }

        // Use a selector that appears only after the report data is rendered.
        page.locator("#report-ready").waitFor();

        page.pdf(new Page.PdfOptions()
            .setPath(Paths.get("report.pdf"))
            .setFormat("A4")
            .setPrintBackground(true));
      } finally {
        browser.close();
      }
    }
  }
}

In the Java API, WaitUntilState is in com.microsoft.playwright.options. The example uses domcontentloaded to avoid treating every subresource as a prerequisite; the explicit selector wait represents the application’s actual readiness condition. If your app exposes a reliable ready state instead, wait for that state.

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

Choose readiness deliberately

  • domcontentloaded: the initial HTML has been parsed. This is often a useful starting point when scripts continue loading data.
  • load: the page’s load event has fired. It may wait longer, but does not guarantee that application-level asynchronous work is finished.
  • A locator or application state: usually the clearest choice when you know what indicates that the specific content is ready, such as a report table, a completed status element, or a known client-side state.
  • networkidle: Playwright’s API discourages using this as a general readiness test. Pages may keep connections open or fetch data later, and an idle network does not prove the right content is present. See the Playwright Java Page API.

Make the condition specific enough to avoid saving a partially rendered page. A selector that exists in the initial shell is not useful if the data is inserted later; wait for a rendered result or a completion marker instead.

Print media and page appearance

Playwright’s page.pdf() generates the PDF using print CSS media by default. A site’s print stylesheet may hide navigation, change colors, or alter layout. If you need the screen stylesheet, call page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.SCREEN)) before page.pdf(). The API also provides PDF options for paper format, margins, background printing, and page ranges. Consult the PDF options reference for the options supported by the release you use.

For example, set margins explicitly if the page’s default print styles leave too little room, and enable background printing if colored panels or backgrounds matter. Test the output with the actual page: browser screen appearance and print appearance can differ by design.

When iText pdfHTML is the right choice

Use pdfHTML when you have static HTML, or when the content has already been rendered or prepared and fits the converter’s supported HTML and CSS behavior. The documented URL pattern is to open the page as a stream and convert it:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import com.itextpdf.html2pdf.HtmlConverter;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;

public class StaticUrlToPdf {
  public static void main(String[] args) throws Exception {
    URL url = new URL("https://example.com/static-report.html");
    try (InputStream html = url.openStream()) {
      HtmlConverter.convertToPdf(html, Files.newOutputStream(Path.of("report.pdf")));
    }
  }
}

This is a static conversion example, not a JavaScript-capable browser workflow. If scripts are responsible for the report content, converting the stream will not execute them. Use Playwright to render and print the page, or use a browser to produce suitable HTML before passing that material to a converter.

Relative assets and base URIs

When converting an HTML snippet or stream that refers to relative stylesheets, images, or other resources, the converter needs a base URI to resolve those references. iText’s introductory documentation demonstrates setting ConverterProperties.setBaseUri(...). A base URI helps locate assets; it does not enable JavaScript execution. See iText’s pdfHTML getting-started documentation.

Where Flying Saucer fits

Flying Saucer’s pure-Java renderer is described as an XML/XHTML and CSS 2.1 renderer; its user guide says scripts are not supported and script tags are ignored. That renderer is therefore not the choice when a page depends on JavaScript to build its content. The project also lists a separate flying-saucer-chrome-pdf artifact, which delegates PDF output to chrome-headless-shell and supports modern HTML5/CSS3. See the Flying Saucer project repository and its user guide. Check the Java runtime requirement for the precise artifact release you choose; requirements differ across releases.

Choose by rendering needs, not by the fact that a URL is involved

Approach Runs page JavaScript? Best fit Practical consideration
Playwright for Java with Chromium Yes, in a browser engine Pages whose content or layout depends on scripts; browser-style rendering and PDF printing Manage browser binaries and lifecycle, wait for application readiness, and configure print output.
iText pdfHTML URL/stream conversion No Static or compatible HTML that can be converted without script execution Supply an appropriate base URI when relative assets need resolution; validate feature fit.
Flying Saucer pure-Java renderer No; its guide says script tags are ignored Its supported XML/XHTML and CSS 2.1 use cases For JavaScript-dependent pages, assess the project’s separate Chrome-backed PDF artifact instead.

Before choosing, check whether the source requires JavaScript, how it loads styles, fonts, images, and data, and whether it depends on cookies or authenticated state. Also decide whether print CSS or screen styling is desired, what paper and margins are required, and whether your deployment can run a browser process. If output must be accessible or meet a specific document standard, verify that requirement against the selected tool and configuration rather than assuming browser printing provides it.

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

Or skip the browser setup

If your goal is a clean screenshot of a URL rather than a Java-generated PDF, ScreenshotNeo is a website screenshot API with a one-request workflow. It returns an image (PNG, JPEG, or WebP) or PDF; this call saves a WebP screenshot:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com/report -o shot.webp

See the ScreenshotNeo API documentation for authentication and request options. It accepts cookie or consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan to try 1,000 screenshots a month with no card.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting Java URL-to-PDF output

The PDF is blank or missing dynamically loaded data

Cause: The converter received initial HTML, or the browser printed before the page finished its asynchronous work. Fix: Use Playwright for a JavaScript-dependent page and wait for a selector or state that appears after the required data renders. Do not rely on a generic navigation event alone.

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

Navigation times out or returns an unsuccessful response

Cause: The destination may be slow, unreachable from the runtime, blocked, or returning an HTTP error. A navigation event can also wait on a resource that never completes. Fix: Set an explicit timeout appropriate to the application, inspect the returned response when available, and distinguish an HTTP status failure from a navigation timeout. Confirm the URL is reachable from the machine running Chromium.

Images, stylesheets, or fonts are missing

Cause: Resources may use relative paths without a usable base URI in a converter, require authentication, or fail to load in the browser environment. Fix: For pdfHTML snippets, set a base URI as documented by iText. For browser rendering, inspect whether asset requests succeed and whether the page has the required cookies, headers, or access.

The PDF looks different from the browser window

Cause: page.pdf() uses print media by default, so print styles may change the page. Fix: Review the site’s print CSS; if screen styling is required, emulate screen media before generating the PDF. Set page size, margins, and background printing explicitly when those affect the result.

The browser works locally but not in deployment

Cause: The runtime may lack the required browser binaries or the permissions and resources needed to start them. Fix: Follow the installation instructions for the selected Playwright release, provision its browser in the deployment image, and close browser resources reliably even when navigation or PDF creation fails.

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.

Flying Saucer output ignores page scripts

Cause: Its pure-Java renderer does not support JavaScript. Fix: Use a browser-backed approach such as Playwright, or evaluate Flying Saucer’s distinct Chrome-backed PDF artifact for your version and runtime requirements.

Performance, reliability, and cost considerations

A browser-based render does more than fetch HTML: it starts or uses a browser, runs page code, and waits for rendering. That gives it the browser behavior needed for dynamic pages, but makes browser startup, page readiness, resource access, and cleanup part of the job. For repeated captures, design your service around explicit timeouts and deterministic readiness conditions; ensure a browser is closed in a finally block or equivalent even when the job fails.

Do not use a long fixed delay as a substitute for knowing the page is ready unless the page offers no better signal. A fixed wait can waste time on fast runs and still be too short on slow ones. A selector or application state is generally more useful, while a timeout provides a bound for pages that never reach that state.

Direct conversion avoids browser execution and is appropriate for static content, but it cannot supply the missing JavaScript behavior. Choose based on the fidelity and script requirements of the source page, then validate representative output in the actual deployment environment. Licensing and runtime costs depend on the specific library, artifact, and deployment arrangement; confirm those terms for the version and usage you adopt.

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

Frequently Asked Questions

Does iText pdfHTML run JavaScript from the URL it converts?

No. It converts fetched HTML but does not evaluate JavaScript.

Should I wait for network idle before printing with Playwright?

Not as a universal readiness guarantee. Prefer a selector or application state that signals the content you need has rendered.

Does Playwright generate PDFs using screen styles by default?

No. PDF generation uses print CSS media by default; emulate screen media first if that is what the output requires.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.