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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

To dynamically widen an HTML-generated PDF in iText, choose the page width before layout, set that width on the PdfDocument, and give pdfHTML the same width as its screen-media viewport. This keeps page geometry and responsive CSS aligned. iText does not transparently resize a page after HTML has already been laid out; if the width is unknown, determine it in your application or use a separate measurement strategy before conversion.

Decide what “dynamic width” means

There are four different requirements commonly described as a dynamic PDF width. Select the one that matches your output contract before writing code.

Requirement Recommended approach Trade-off
A known or bounded width, such as a table width supplied by your application Create a custom PageSize before conversion Your code must obtain the width; iText does not infer arbitrary HTML width automatically
Responsive CSS should react to the PDF width Set the PDF page width and the pdfHTML screen-media width to the same value Both settings must stay synchronized
One long page whose final height follows the rendered content Start with a tall page, convert to a Document, measure the ending vertical position, then change the media box The documented recipe measures height, assumes one page, and does not discover horizontal width
A4, Letter, or another fixed output size must be preserved Render on a page large enough for the HTML, then scale each page onto the required size Text, images, and spacing all become smaller

The examples below assume Java with iText 7 and pdfHTML. Method names can vary by dependency generation, so verify them against the version installed in your build.

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

Set a custom width before converting HTML

When your application knows the required width, create the page first. A PDF user unit is normally 1/72 inch, but you can calculate the value from your own units. The height is a separate decision: use a normal page height for pagination, or a deliberately tall page only when you are producing a single continuous page.

#1 Best Overall
Epson EcoTank ET-2800 Wireless Color All-in-One Supertank Printer - Black
  • INNOVATIVE CARTRIDGE-FREE PRINTING — No more dealing with lots of tiny ink cartridges; With this wireless document and photo printer each ink bottle set is equivalent to about 90 individual cartridges²
  • LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; When you choose this combination printer, scanner and copier you can print up to 4,500 pages black/7,500 color³
  • COLOR PRINTING — Up to 2 years of ink in the box4 (and with every replacement ink set) for fewer out-of-ink frustrations
  • ZERO CARTRIDGE WASTE — By using an Epson EcoTank printer you can help reduce the amount of cartridge waste ending up in landfills
  • HOME PRINTER DESIGNED FOR RELIABILITY — The Epson EcoTank ET-2800 All-in-One Supertank Color Printer creates vivid, detailed prints and documents thanks to Micro Piezo Heat-Free Technology; Fire off 10 ISO pages per minute1 to easily finish large jobs
PageSize pageSize = new PageSize(targetWidth, targetHeight);
PdfWriter writer = new PdfWriter(destination);
PdfDocument pdf = new PdfDocument(writer);
pdf.setDefaultPageSize(pageSize);

ConverterProperties properties = new ConverterProperties();
HtmlConverter.convertToPdf(htmlInputStream, pdf, properties);
pdf.close();

targetWidth must be established before HtmlConverter lays out the document. Typical sources include a report configuration, a known column model, a user-selected paper format, or a bounded width chosen by your service. Do not claim that this code measures an arbitrary DOM and then resizes the page; it only applies the width you supply.

Keep responsive CSS and PDF geometry in sync

pdfHTML evaluates responsive rules through a media description. If your HTML uses media queries, set the screen width to the same value as the PDF page width. Otherwise CSS can choose a breakpoint for one width while the PDF page has another, producing unexpected wrapping or clipped tables.

PageSize pageSize = new PageSize(targetWidth, targetHeight);
PdfDocument pdf = new PdfDocument(new PdfWriter(destination));
pdf.setDefaultPageSize(pageSize);

ConverterProperties properties = new ConverterProperties();
MediaDeviceDescription media = new MediaDeviceDescription(MediaType.SCREEN);
media.setWidth(targetWidth);
properties.setMediaDeviceDescription(media);

HtmlConverter.convertToPdf(htmlInputStream, pdf, properties);
pdf.close();

In the official responsive pattern, the width passed to the media description is derived from the selected page size (using iText’s CSS dimension parsing utilities). You can instead pass a numeric width directly when your application already works in user units. Keep the page width and media width as one configuration value rather than maintaining two independent constants.

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

Choosing a width from application data

Known table or report width

Calculate the width from the columns, cell padding, borders, and any fixed margins before creating PageSize. Add a safety allowance for borders and rounding. If the report can grow, cap the value at a maximum your viewers support and decide whether excess content should wrap or paginate.

Responsive breakpoint width

Choose a viewport width that corresponds to the layout you want (for example, the desktop breakpoint), then use that same value for PageSize and MediaDeviceDescription. This is more predictable than allowing CSS to switch layouts midway through a report.

Width discovered from HTML

There is no general “convert, inspect every horizontal box, and transparently enlarge the page” switch. A reliable implementation needs a measurement pass or application-level knowledge of the widest element, followed by a fresh conversion using the measured width. Validate the result with the actual fonts, images, CSS, and margins used in production; layout can change when those inputs change.

Rank #2
Sale
Epson EcoTank Photo ET-8550 Wireless Wide-Format All-in-One Tank Printer
  • CARTRIDGE-FREE PRINTING — Print lab-quality photos, graphics and creative projects; Get vibrant colors and sharp text with Epson's high-accuracy printhead and Claria ET Premium 6-color inks
  • INK BOTTLES — Save on photos1 and creative projects with affordable in-house printing; All-in-one printer allows you to print 4" x 6" photos for about 4 cents each vs. 40 cents with traditional ink cartridges1
  • LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; Printer, scanner and copier lets you print up to 6,200 color pages³
  • PRINT FOR LONGER — Up to 2 years of ink in the box² (and with every replacement ink set) for fewer out-of-ink frustrations with this wireless printer
  • ZERO CARTRIDGE WASTE — Epson EcoTank printer helps reduce the amount of cartridge waste ending up in landfills; Cartridge-free printer uses high-yield ink bottles; Each replacement ink bottle set is equivalent to about 100 individual ink cartridges⁴

One-page documents: measure height separately

iText’s documented one-page report technique solves a different problem: fitting the final height to rendered content. It starts with a page width (the example uses 595 user units) and a very tall page (14,400 units), converts with convertToDocument, records the final Y position through a custom line separator, and then changes the first page’s media box to the required height.

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

This approach assumes the content remains on one page. It does not automatically measure the width of an arbitrary HTML layout. To make width dynamic, determine or measure the horizontal requirement with a strategy appropriate to your document, then perform a new layout using that width. Do not simply alter the media box after layout and expect line breaks to be recomputed.

Viewer limits also matter. iText documents 14,400 user units as an Adobe Acrobat/Reader implementation limit for rendering page width or height. A page larger than that may appear blank in those viewers, even if the PDF file was created successfully. Keep both dimensions below the limit when Acrobat/Reader compatibility is required, or paginate instead of creating an extreme single page.

Keep a standard page by scaling oversized HTML

If a print contract requires A4, Letter, or another fixed size, increasing the page width is the wrong output model. The documented alternative is to render the HTML on a page large enough to contain it, copy each rendered page to a PdfFormXObject, and place that object on the target page with a scale factor.

Scaling preserves the prescribed media box, but it changes the physical size of everything: text, lines, images, and whitespace. Test readability, accessibility, and multi-page placement before adopting it. If the result is too small, wrapping or pagination is usually preferable to more aggressive scaling.

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

Using CSS @page

pdfHTML support information lists @page and its size property, including custom dimensions such as 210mm 297mm, as supported. You can therefore express a paper choice in HTML/CSS:

Rank #3
HP Smart Tank 5000 Wireless All-in-One Ink Tank Printer, Scanner, Copier with 2 Years of Ink Included, Best-for-Home, Cartridge-Free, Refillable and AI-Enabled. (5D1B6A)
  • SET IT UP ONCE AND PRINT WITH CONFIDENCE. No complicated maintenance. Just easy, reliable printing you can count on.
  • INK FOR YEARS. NOT MONTHS. Up to 2 years of ink included. Get thousands of pages of cartridge-free printing. More pages, less hassle
  • KEEPS PRINTING WELL AFTER COMPETITORS HAVE QUIT. No complex maintenance. Sharper text, richer colors.[2] Only with HP Smart Tank
  • PREMIUM SUPPORT - Strong technical expertise to solve issues faster
  • THE LAST PRINTER YOU'LL EVER NEED. Enjoy years of refillable, cartridge-free printing.
@page {
  size: 320mm 210mm;
  margin: 12mm;
}

Treat this as pdfHTML-specific behavior, not full browser print-engine equivalence. The same support information lists overflow handling and named-page selection through the page property as unsupported. Confirm behavior against the pdfHTML version deployed by your application, especially after upgrades. For a width supplied dynamically by Java, setting the PdfDocument default page size remains the clearest control.

Complete implementation pattern

The following method separates width selection from conversion and keeps the CSS viewport synchronized. It uses a normal page height so content can paginate.

public static void htmlToPdf(
        InputStream html,
        OutputStream destination,
        float targetWidth,
        float targetHeight) throws IOException {

    PageSize pageSize = new PageSize(targetWidth, targetHeight);
    PdfDocument pdf = new PdfDocument(new PdfWriter(destination));
    pdf.setDefaultPageSize(pageSize);

    ConverterProperties properties = new ConverterProperties();
    MediaDeviceDescription screen =
        new MediaDeviceDescription(MediaType.SCREEN);
    screen.setWidth(targetWidth);
    properties.setMediaDeviceDescription(screen);

    HtmlConverter.convertToPdf(html, pdf, properties);
    pdf.close();
}

For a real service, close the PDF in a finally or try-with-resources design appropriate to your iText version, validate positive dimensions, and reject widths above your viewer or operational limit. If conversion throws, do not return the partially written file as a successful document.

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

Or skip the browser setup

If your real requirement is obtaining a clean PDF or screenshot of a URL rather than controlling iText’s layout engine, ScreenshotNeo provides a single HTTP call. It accepts cookie/consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, 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.

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

For PDF output, use the API’s PDF options (paper size, margins, landscape, and page ranges) rather than trying to retrofit browser setup. The service also supports full-page captures with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets and arbitrary viewports, retina scale, custom CSS and JavaScript, pre-capture clicks, hidden selectors, waits for selectors/delays/network idle, request and resource blocking, custom headers/cookies/user agents/Authorization, timezone and geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Common screenshot-API parameter names work as well, which can simplify migration.

An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. See the ScreenshotNeo documentation for request options, then create a free account.

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

Troubleshooting dynamic-width PDFs

Columns are cut off

  • Check that the supplied PageSize width includes margins, borders, and cell padding.
  • Verify that the media-device width equals the page width when responsive CSS is involved.
  • Look for fixed-width CSS or unbreakable strings that exceed the chosen width.

The layout uses the mobile breakpoint

The CSS viewport is probably narrower than the PDF page, or no screen media description was configured. Set MediaType.SCREEN and the intended width before conversion.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
NDYIN Portable Printers Wireless for Travel, N80 Bluetooth Thermal Printer
  • Wireless Bluetooth Printer: Portable thermal printer compatible with iPhone, Android phones, iPad and tablet computers via Bluetooth. For smartphones, please download the "Nada Print" App. You can also connect to laptops and computers for printing using a USB-C cable. (Note: Laptops and computers can only be connected via USB and require the installation of a driver first. Bluetooth connection is not supported.)
  • No-ink printing: Only supports US Letter and A4 size thermal paper.(Doesn't support regular paper) The no-ink portable thermal printer uses direct thermal technology, requiring no ink, toner or ribbons, making it environmentally friendly, cost-effective and time-saving. The thermal printer package comes with a roll of US Letter thermal printing paper. Note: When installing the paper, remember to switch the paper size switch on APP
  • Clear Print: NDYIN N80 portable thermal printer adopts high-definition printing technology, with a 203DPI resolution to provide you with clear printing results. This mobile printer is compatible with roll paper, folded paper and tattoo transfer paper, supporting printing from your mobile phone PDF, Word, pictures and web pages anytime and anywhere. It is recommended to use our NDYIN thermal paper to achieve good printing quality
  • Portable wireless printer for travel: The thermal printer is equipped with a built-in 1500mAh rechargeable battery, which can print 160 sheets of 8.5" x 11" thermal paper after being fully charged. It weighs only 1.5 pounds and is compact in size. This ink-free portable printer can be easily carried in a backpack or briefcase! It is perfect for business travel, cars, small offices, construction sites, schools and homes. You can print documents, contracts, invoices and boarding passes anytime and anywhere
  • The N80 thermal printer has a wide range of uses. The package includes the N80 printer, a roll of US Letter paper(7m/roll), a user manual, a guide card, a type-C soft cable and a type C adapter. Note: The charging adapter is not included. Special thermal paper is required for use; ordinary paper cannot be used. This ink-free portable thermal printer is suitable for various scenarios such as home, school, travel, office, and outdoor, meeting the printing needs of different groups of people. This tattoo template printer is also compatible with tattoo transfer paper, making it an ideal choice for tattoo art

Changing the media box did not reflow text

Changing a page’s box after conversion changes geometry, not the already-computed line breaks. Convert again with the new width.

The one-page PDF is blank in Acrobat

Check whether width or height exceeds 14,400 user units. Reduce the page, paginate, or render and scale onto a standard page.

CSS @page appears ignored

Confirm the deployed pdfHTML version and its CSS support. Avoid relying on unsupported overflow or named-page features, and set the page size in Java when the value is generated by application data.

Output is tiny after fitting Letter or A4

That is the expected consequence of scaling a large rendering onto a fixed page. Reduce the source width, allow wrapping and pagination, or accept a larger physical output page.

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

Operational checklist

  • Choose whether width is known, measured, responsive, or constrained by a fixed paper size.
  • Set PdfDocument page geometry before calling HtmlConverter.
  • Match screen-media width to page width when media queries matter.
  • Decide explicitly between pagination and one long page.
  • Keep one-page dimensions under the 14,400-user-unit viewer limit when Acrobat/Reader support is required.
  • Test fonts, images, long words, tables, margins, and the widest real dataset.
  • Reconvert after any width change; do not expect post-layout resizing to reflow content.

Frequently Asked Questions

Can iText automatically grow a PDF page to the widest HTML element?

Not as a transparent post-layout operation. Determine the width before conversion, or run an appropriate measurement process and convert again with the resulting width.

Should I use a wider page or scale onto A4?

Use a wider page when preserving physical text size is important. Scale only when the output must remain a fixed paper size and the resulting smaller content is acceptable.

Does a custom width require a special browser?

No. pdfHTML performs the conversion in Java; the important controls are the PDF page size and, for responsive layouts, the screen-media width.

The Bottom Line

Set the target width before pdfHTML lays out the document, use the same value for responsive screen media, and choose pagination or scaling deliberately when the width cannot remain arbitrary.

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.

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.