Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesSome links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Use iText pdfHTML to turn HTML and CSS into iText layout elements, then add those elements to a bounded Canvas positioned on the target PdfPage. The rectangle you provide—x, y, width, and height—defines the available PDF area. This approach places an HTML fragment at an exact coordinate without running a browser, but it requires preprocessing any JavaScript-generated markup and planning what happens when content is taller than the rectangle.
The placement model: page, rectangle, and Canvas
PDF coordinates use points, with the origin normally at the lower-left corner. Select the page, create a PdfCanvas, and wrap it in an iText layout Canvas whose root area is the target rectangle. Add layout elements to that Canvas rather than to the document-wide flow.
PdfPage page = pdfDocument.getPage(pageNumber);
PdfCanvas pdfCanvas = new PdfCanvas(page);
Rectangle target = new Rectangle(x, y, width, height);
Canvas canvas = new Canvas(pdfCanvas, target);
canvas.add(element);
canvas.close();
Here, pageNumber is one-based, x and y locate the lower-left corner, and width and height are the maximum layout area. Keep the rectangle inside the page’s media or crop box unless you deliberately need content to extend beyond it.
Recommended Free Tools
Coordinate conversion from a top-left design
Design tools often measure from the top-left. If the page height is pageHeight and your design gives a top offset top, convert it to PDF coordinates with y = pageHeight - top - height. Subtract the element height; using only pageHeight - top places the bottom edge too high.
#1 Best Overall
Margins and padding are inside the rectangle
CSS margins, padding, borders, and line boxes consume the available area. Define the rectangle for the outer box, then leave enough space for the styles applied by the HTML. A fragment that appears to have the right dimensions in a browser can still wrap differently because pdfHTML is not a browser layout engine.
Converting HTML with pdfHTML
pdfHTML parses HTML and CSS and maps them to iText objects; it does not require a browser engine. Configure ConverterProperties, especially setBaseUri when the markup references relative stylesheets, images, or fonts. The conversion overload and imports vary between iText/pdfHTML releases, so pin compatible dependency versions before selecting the exact method signature.
Open an existing PDF and place converted content
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.IBlockElement;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class HtmlAtPdfLocation {
public static void main(String[] args) throws Exception {
String html = "Invoice note
"
+ "This block is rendered by pdfHTML.
";
ConverterProperties properties = new ConverterProperties();
properties.setBaseUri("/opt/app/assets/");
try (PdfDocument pdf = new PdfDocument(
new PdfReader("input.pdf"),
new PdfWriter("output.pdf"))) {
int pageNumber = 2;
PdfPage page = pdf.getPage(pageNumber);
float x = 72;
float y = 430;
float width = 468;
float height = 300;
PdfCanvas pdfCanvas = new PdfCanvas(page);
Canvas canvas = new Canvas(pdfCanvas,
new Rectangle(x, y, width, height));
List elements = HtmlConverter.convertToElements(
new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)),
properties);
for (IBlockElement element : elements) {
canvas.add(element);
}
canvas.close();
}
}
}
The example writes onto page 2 of input.pdf. If the source PDF has fewer than two pages, getPage(2) fails; create or append the required page first. If your pdfHTML version exposes a different conversion method, retain the same sequence: configure properties, convert HTML to layout elements, create a page-bound Canvas, and add the elements.
Using external CSS, images, and fonts
Relative URLs resolve against baseUri. Use a stable local directory or an explicitly controlled URL, and ensure the process can read every referenced asset. For production, embed or package the fonts you need and test fallback behavior; a missing font can change line breaks and therefore the final height.
Keeping content inside a fixed box
A Canvas supplies an available area, but it is not a browser-style overflow container. The pdfHTML feature matrix for version 6.3.3 with iText Core 9.7.0 lists @page, margins, padding, page-break properties, and multi-page content as supported, while listing CSS overflow as unsupported. Verify the matrix for the versions you actually deploy.
Choose a policy before rendering
- Clip: draw only the portion that fits. This can hide text and should be used only when truncation is acceptable.
- Split: give the content additional layout areas or pages. This preserves content but no longer guarantees a single fixed box.
- Shrink: reduce font sizes or scale a prepared block until it fits. Scaling can reduce readability and should be bounded.
- Move: detect that the block does not fit and place it in a fallback rectangle or a later page.
Do not depend on CSS overflow:auto or overflow:hidden to make this decision. Measure or preflight the content, then apply the policy in application code.
Flowing to another area or page
iText’s renderer tree performs layout before drawing. When a layout area is exhausted, an AreaBreak can advance to another area or page. AreaBreakType.NEXT_AREA moves to the next configured layout area, NEXT_PAGE starts a new page, and LAST_PAGE is useful after changing renderers so content begins at the current end rather than being written over existing material.
For a one-page overlay, keep the Canvas bounded and handle an overflow result or preflight failure explicitly. For reports, use a document-level flow and page-break properties instead of forcing every section into one rectangle. Fixed placement and flowing pagination are different layout contracts.
HTML and CSS limits that affect exact placement
JavaScript is not executed
pdfHTML does not evaluate JavaScript. If a framework inserts the markup, resolves data, or draws a chart in the browser, render that state beforehand or generate equivalent static HTML and CSS. Sending the original script tags to pdfHTML will not produce the browser-rendered result.
Browser parity is not guaranteed
Test line wrapping, replaced elements, fonts, and unsupported CSS with the exact pdfHTML and iText Core versions used in deployment. The documented feature matrix is version-sensitive; support for a property in one release is not a promise for another.
Asset and security considerations
- Restrict base paths and remote resource access when HTML is user supplied.
- Validate image and font URLs to prevent unintended file or network access.
- Set timeouts and size limits around any asset resolver you provide.
- Sanitize markup if untrusted users can submit HTML; PDF generation is not an HTML security boundary.
Debugging exact-position problems
The block is on the wrong page
Check that page numbers are one-based and that you call getPage(pageNumber) on the intended source document. Log the page’s media and crop-box dimensions and compare them with your rectangle.
The block is shifted vertically
PDF’s origin is at the lower-left. Recalculate a top-origin design with pageHeight - top - height, and account for borders, padding, and CSS margins.
Images or styles are missing
Set ConverterProperties.setBaseUri to the directory or URL that makes relative references resolvable. Confirm permissions, spelling, and font availability. Absolute paths can help diagnose a base-URI problem but should not be hard-coded across environments.
Text is cut off or overlaps existing content
The content exceeded the rectangle or the rectangle intersects existing page content. Increase the height, shorten or resize the fragment, split it into another area, or choose a non-overlapping rectangle. CSS overflow rules will not provide browser-like clipping.
Dynamic content is blank
Replace JavaScript-dependent markup with the final HTML before conversion. A headless browser can be used as a separate preprocessing stage when the page genuinely requires script execution; pdfHTML itself remains the static HTML/CSS conversion step.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Rank #4
API or import errors after an upgrade
Check the pdfHTML and iText Core compatibility table and update the conversion call to that release’s API. Avoid copying imports from examples targeting a different major version without checking the dependency documentation.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Testing and production checklist
- Pin and record the iText Core and pdfHTML versions.
- Record the source page size, rotation, crop box, and target rectangle.
- Render representative short, long, multilingual, and image-heavy fragments.
- Verify fonts and assets in an environment matching production.
- Test content that exactly fills, slightly exceeds, and greatly exceeds the rectangle.
- Open the generated PDF in more than one viewer and inspect text selection, clipping, and page boundaries.
- Log conversion failures separately from intentional “does not fit” decisions.
Or skip the browser setup
If your starting point is a web page rather than an HTML fragment, ScreenshotNeo can return a screenshot or PDF with one request. It accepts cookie and consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result.
For a quick capture:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python:
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
See the parameter reference and PDF options in the ScreenshotNeo documentation. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Every plan includes the features; the Free plan provides 1,000 screenshots per month without a card, and paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
When to use Canvas versus another design
| Requirement | Best fit | Reason |
|---|---|---|
| One static fragment at known coordinates | Page-bound Canvas | The target Rectangle directly defines the placement area. |
| Long report with automatic pagination | Document flow and AreaBreak | Renderers can advance through areas and pages. |
| Browser-only, JavaScript-generated UI | Pre-render, then pdfHTML | pdfHTML does not execute scripts. |
| Strict visual parity with a live website | Browser capture or preprocessing | Browser layout and pdfHTML CSS support are not identical. |
Frequently Asked Questions
Can I place HTML inside a rectangle on page 2?
Yes. Get page 2, create a PdfCanvas and Canvas with the desired Rectangle, convert the HTML to iText layout elements, and add them to that Canvas.
Does pdfHTML need Chrome or another browser?
No. It parses HTML and CSS itself, but it does not run JavaScript.
Why does CSS overflow not keep my fragment in the box?
The cited pdfHTML 6.3.3 feature matrix lists overflow as unsupported. Implement clipping, splitting, shrinking, or relocation in application logic.
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.

