Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsSome links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Fix PhantomJS PDF alignment by isolating five independent variables: the browser viewport, PDF paper size, wrapper scaling and margins, print CSS, and the moment printing occurs. Record the exact PhantomJS and Node wrapper versions, operating system, page settings and input fixture, then change one variable at a time. A CSS transform or arbitrary zoom may hide one symptom while making pagination and text sizing worse.
1. Reproduce the exact failing render
Before changing CSS, save the HTML (or URL), PhantomJS version, Node.js version, wrapper package and version, operating system, paper format, orientation, margins, viewport, and whether the same fixture differs between your workstation and production. Alignment defects that appear only after deployment can be caused by the rendering stack rather than by the template. jsreport documents different element dimensions from PhantomJS 1.9.8 and 2.1.1 on Windows and Unix, so an OS or engine mismatch must be treated as a possible cause, not compensated for blindly.
| # | Preview | Product | Price | |
|---|---|---|---|---|
| 1 |
|
PDF Explained: The ISO Standard for Document Exchange | $14.41 | Buy on Amazon |
| 2 |
|
Adobe Acrobat 6 PDF For Dummies | $13.00 | Buy on Amazon |
| 3 |
|
Debugging: The 9 Indispensable Rules for Finding Even the Most Elusive Software and Hardware... | $13.39 | Buy on Amazon |
Make a small diagnostic fixture
Use a page with a visible border, a fixed-width content box, a heading, one image and a forced page break. Render that fixture locally and in production. If the box itself is shifted, investigate geometry. If only fonts or images move after a delay, investigate readiness. If the box is correct but pages split unexpectedly, investigate print CSS.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
@page { size: A4 portrait; margin: 12mm; }
* { box-sizing: border-box; }
body { margin: 0; font-family: Arial, sans-serif; }
.sheet { width: 100%; border: 1px solid #000; padding: 8mm; }
.next-page { page-break-before: always; }
</style>
</head>
<body>
<div class="sheet">Geometry test</div>
<div class="next-page">Page two</div>
</body>
</html>
2. Separate viewport, clip rectangle and paper geometry
PhantomJS exposes three different controls. page.viewportSize is the browser layout viewport used to calculate CSS. page.paperSize defines the PDF sheet, margins and orientation. clipRect limits the captured screen region; it is a crop rectangle, not a paper-size setting. Changing one does not automatically correct another.
#1 Best Overall
Choose a deliberate viewport
Set a viewport wide enough for the intended layout and inspect for elements wider than the printable content area. A desktop breakpoint rendered into a narrow PDF viewport can wrap or shift columns; an oversized viewport can make text and components appear too small when fitted to paper. Log the viewport used for every render.
page.viewportSize = { width: 1200, height: 1600 };
Define paper size and margins explicitly
Set paper dimensions in one place and make the CSS @page rule agree with them. PhantomJS accepts formats such as A4 or explicit width and height, plus margin values. Keep the printable content width within the paper width after subtracting left and right margins.
page.paperSize = {
format: 'A4',
orientation: 'portrait',
margin: { top: '12mm', right: '12mm', bottom: '12mm', left: '12mm' }
};
Do not use clipRect to repair a PDF that is off-center. Remove it while diagnosing; add it only when you intentionally need a cropped screen capture.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
3. Check wrapper scaling and margins
If you use the phantom-html-to-pdf Node wrapper, inspect its installed documentation and version before changing options. Its documented controls include paperSize, fitToPage, printDelay and waitForJS. A wrapper may apply scaling or margins in addition to CSS, so compare the wrapper’s paper dimensions and margins with your @page rule.
Use fit-to-page deliberately
fitToPage can prevent overflow, but it scales the complete layout. That can make a page look centered while reducing text or changing page breaks. First make the content fit the printable width with CSS and paper settings; use fitting only when you have verified the resulting scale and pagination.
Remove hidden width and transform traps
- Check for a fixed pixel width larger than the viewport’s printable area.
- Inspect ancestor elements for
transform: scale(), negative margins, and absolute positioning tied to a different viewport. - Use
box-sizing: border-boxwhere borders and padding must remain inside declared widths. - Ensure only one layer owns the margins: either the paper configuration or the document’s outer layout, not competing values that are hard to reason about.
4. Wait for fonts, images and JavaScript before printing
Printing immediately after page.open can capture an intermediate layout. Web fonts, images, charts and client-side DOM changes can alter widths after the first paint. The wrapper documents waitForJS and a readiness variable; use that readiness signal when your page can set it reliably. Use printDelay only when a fixed delay is appropriate, and make it long enough for the slowest expected asset.
Rank #2
Readiness-gated PhantomJS example
var page = require('webpage').create();
page.viewportSize = { width: 1200, height: 1600 };
page.paperSize = {
format: 'A4',
orientation: 'portrait',
margin: { top: '12mm', right: '12mm', bottom: '12mm', left: '12mm' }
};
page.open('file:///absolute/path/report.html', function (status) {
if (status !== 'success') {
console.error('open failed: ' + status);
phantom.exit(1);
return;
}
window.setInterval(function () {
var ready = page.evaluate(function () { return window.reportReady === true; });
if (ready) {
page.render('report.pdf');
phantom.exit();
}
}, 50);
});
Set window.reportReady = true only after your application has inserted data and confirmed required images or fonts. If you cannot add a readiness flag, configure the wrapper’s documented delay and verify the output repeatedly under realistic network speed.
5. Inspect print CSS and pagination
Use print-specific rules instead of relying on screen layout. Define @page size and margins, reset the body margin, and control breaks on block-level sections. jsreport’s PhantomJS documentation describes rules such as page-break-before; equivalent rules can be applied to your own fixture.
@media print {
@page { size: A4 portrait; margin: 12mm; }
body { margin: 0; }
.chapter { page-break-before: always; }
.avoid-split { page-break-inside: avoid; }
}
Do not put a forced break on an element that is already moved by a float, absolute position or transform. Temporarily remove application CSS and render the diagnostic fixture. If alignment returns, reintroduce styles in groups until the rule that changes geometry is identified.
6. Compare the production operating system
When local output is correct but production is not, run the same HTML, PhantomJS binary, Node wrapper and font set on the production OS. Differences in font availability change glyph widths and line wrapping; the documented jsreport observation also reports different PhantomJS element sizes between Windows and Unix for versions 1.9.8 and 2.1.1. Design and verify templates on the same OS and runtime stack used in deployment.
Avoid applying an unexplained zoom or transform as an OS “fix.” If you must use an environment-specific adjustment, keep it isolated, document the exact engine and OS, and compare representative templates rather than assuming one factor works everywhere.
Recommended Free Tools
7. Troubleshooting by symptom
| Symptom | Likely checks | Practical fix |
|---|---|---|
| Everything is shifted or clipped | Viewport width, paper margins, content width, hidden clipRect |
Remove the clip, set viewport and paper independently, and keep the layout inside printable width. |
| Content is centered but too small | fitToPage, oversized viewport, wrapper scale |
Disable fitting for diagnosis, match viewport to the design breakpoint, then choose a deliberate scale. |
| Only later sections move | Late fonts/images, chart rendering, asynchronous DOM updates | Gate printing with waitForJS or a verified printDelay. |
| Page breaks occur inside cards or tables | Missing print break rules, floats, fixed heights | Use page-break-before and page-break-inside: avoid where supported; remove fixed heights that force overflow. |
| Local and production differ | PhantomJS version, OS, fonts, wrapper version | Render the same fixture on the target stack and align versions and installed fonts. |
| PDF generation fails intermittently | Network assets, timeout, readiness race | Capture load status, wait for required resources, and fail clearly when readiness is not reached. |
8. Performance and reliability practices
- Reuse a tested page configuration rather than allowing each template to invent paper settings.
- Prefer local or reliably reachable assets for production reports; missing images can change layout.
- Record render duration, page-open status, engine version and the readiness outcome with each job.
- Keep a golden PDF fixture and compare page count, major box positions and text wrapping after dependency or OS changes.
- Use a timeout that is longer than normal asset loading but finite, then return an actionable error instead of an empty PDF.
PhantomJS is an archived project. jsreport recommends moving its PhantomJS PDF workflow to Chrome. Treat that as a migration project: compare representative templates, fonts, margins, pagination and asynchronous content timing before switching production.
Rank #3
- Used Book in Good Condition
Or skip the browser setup
If you need a clean screenshot or PDF endpoint rather than maintaining a PhantomJS browser, ScreenshotNeo accepts one request for a URL and can return PNG, JPEG, WebP or PDF. It removes cookie/consent banners, newsletter popups and chat widgets before capture. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the page verdict and billing status in headers. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo documentation for authentication and options. The same endpoint supports full-page capture, CSS-selector element capture, device and viewport settings, retina scale, PDF paper and margins, custom CSS or JavaScript, click and wait actions, request blocking, headers, cookies, user-agent, timezone, geolocation, transparent backgrounds, resizing, TTL caching, signed links, asynchronous webhooks and bulk capture.
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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
One thousand screenshots per month are free with no card. Paid plans start at $5 for 3,000 shots; every feature is included on every plan. Create a free ScreenshotNeo account.
FAQ
Is there one universal PhantomJS alignment setting?
No. The defect can originate in viewport geometry, paper settings, wrapper scaling, CSS pagination, asynchronous content or the operating system. Diagnose the layer that changes in your fixture.
Should I always use A4?
Only when A4 matches the document’s required output. Choose the actual paper format and orientation, then keep CSS @page settings consistent with it.
Can html2pdf.js replace PhantomJS without changes?
No. html2pdf.js is a different browser-side path. Its documentation describes CSS break support but also DOM-cloning and canvas limitations, so representative templates must be tested before migration.
Why does a PDF look right on screen but print incorrectly?
Screen and paper use different geometry and print rules. Validate the PDF’s paper size, margins, print CSS and pagination independently from the interactive viewport.
Frequently Asked Questions
What should I collect before asking for help?
Provide a minimal HTML fixture, PhantomJS and wrapper versions, Node.js version, operating system, viewport, paper and margin settings, and one local-versus-production output comparison.
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.

