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.
To generate a PDF with print styles in PhantomJS, create a webpage, set page.paperSize, open the page, wait until its print CSS and asynchronous content are ready, then call page.render('report.pdf'). PhantomJS selects PDF output from the .pdf extension. The critical details are setting the paper geometry before rendering and not exiting before the render finishes.
How PhantomJS applies print styles
Print styles are selected by the page’s CSS, not by a special PDF-rendering flag. Put rules in a stylesheet linked with media="print", or inside an @media print block. When rendering a PDF, PhantomJS uses the page’s print presentation; ordinary screen styles continue to apply where print rules do not override them.
Use print rules for changes such as hiding navigation, removing interactive controls, setting readable colors, and controlling page breaks. Keep them separate from screen rules so the page can retain its normal browser layout while producing a document-oriented version for PDF output.
<link rel="stylesheet" href="/css/site.css">
<link rel="stylesheet" href="/css/print.css" media="print">
Alternatively, put the rules in a regular stylesheet:
#1 Best Overall
@media print {
.site-navigation,
.print-hidden {
display: none;
}
body {
color: #000;
background: #fff;
}
h1, h2 {
break-after: avoid;
}
.new-page {
break-before: page;
}
}
CSS support depends on the WebKit engine in the PhantomJS binary you run. PhantomJS uses an older WebKit engine, so verify print-specific layout and pagination against that exact binary rather than assuming a modern browser’s behavior.
Set PDF paper size, orientation, and margins
Set page.paperSize before calling page.render. The official PhantomJS paperSize API defines the page size used when rendering a PDF. It supports named formats such as A4 and Letter, explicit dimensions in units including mm, cm, in, or px, orientation, margins, and optional repeating headers and footers.
For a standard portrait A4 report with equal margins:
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallpage.paperSize = {
format: 'A4',
orientation: 'portrait',
margin: '1cm'
};
Use a named format when the output should follow a common paper standard. Use explicit dimensions when you need a non-standard page size, and use the intended unit in each dimension. Orientation controls whether the page is portrait or landscape; margins reserve printable space around the page content. Header and footer options are available when a repeated page label or similar running text is needed.
Rank #2
- HTML CSS Design and Build Web Sites
- Comes with secure packaging
- It can be a gift option
Paper geometry and CSS are related but distinct: paperSize sets the physical page, while the stylesheet controls how content is laid out within it. A page may have the right paper size but still paginate badly if its print CSS has unsuitable widths, oversized elements, or ineffective page-break rules.
Complete Node.js example using PhantomJS
PhantomJS is a separate executable; Node.js code needs to launch and monitor it. One Node wrapper documents a waitForJS readiness mechanism for asynchronous pages. The example below uses that wrapper-oriented pattern; verify the wrapper API and PhantomJS binary version installed in your project before adopting it.
var phantom = require('phantom');
async function renderReport() {
var instance;
try {
instance = await phantom.create();
var page = await instance.createPage();
page.paperSize = {
format: 'A4',
orientation: 'portrait',
margin: '1cm'
};
var status = await page.open('http://localhost:3000/report');
if (status !== 'success') {
throw new Error('PhantomJS could not open the report page: ' + status);
}
// Use the wrapper's readiness mechanism when the page creates content asynchronously.
// Replace the condition with an application-specific ready signal.
await page.waitForJS(function () {
return window.reportReady === true;
});
await page.render('/tmp/report.pdf');
} finally {
if (instance) {
await instance.exit();
}
}
}
renderReport().catch(function (error) {
console.error(error);
process.exitCode = 1;
});
This pattern assumes the rendered page sets window.reportReady = true once its data and client-side rendering are complete. Add that signal in the page’s own code at the point when required content is ready. Do not treat the successful completion of page.open as proof that later JavaScript work, fonts, or images have finished.
Recommended Free Tools
The wrapper’s exact method signatures and lifecycle handling can vary by package version. Check the Node wrapper documentation for the wrapper you actually use. If working directly in a PhantomJS script rather than from Node, the essential sequence is:
Rank #3
- Brand: Wiley
- Set of 2 Volumes
- A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
var page = require('webpage').create();
page.paperSize = { format: 'A4', orientation: 'portrait', margin: '1cm' };
page.open('http://localhost:3000/report', function (status) {
if (status !== 'success') {
phantom.exit(1);
return;
}
page.render('/tmp/report.pdf');
phantom.exit();
});
The direct script illustrates the basic flow, but pages with delayed content need an explicit readiness check before rendering. Also ensure the render has completed before exiting. The official render API describes rendering the page to an image buffer and saving it to the specified filename; using a .pdf filename selects PDF output.
Wait for stylesheets, images, fonts, and generated content
A PDF rendered too early can be missing more than JavaScript-generated text. A page may still be loading a linked print stylesheet, an image, a web font, or content fetched after the initial document load. Add a readiness condition tied to what the document needs, and wait for that condition before rendering.
- For client-rendered reports, expose a page-level flag only after data fetching and DOM updates are complete.
- For required images, check that they have loaded successfully before setting the ready flag.
- For fonts, wait for the page’s intended font-loading work to complete where supported by the runtime, then validate that the PhantomJS version renders the expected typeface.
- For linked CSS, make sure the stylesheet is available to the PhantomJS process and that its load has completed before capture.
A fixed delay may be a simple fallback for a page with known, stable timing, but it is not a reliable substitute for a readiness signal: network and server response times vary. Use the wrapper’s documented readiness mechanism or an equivalent explicit check appropriate to the wrapper and PhantomJS version.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Common problems and fixes
The PDF looks like the screen version
Check that the print stylesheet is actually linked, that its URL is reachable from the PhantomJS process, and that rules are inside @media print or linked with media="print". Confirm the rules override screen styles with sufficient specificity and inspect whether the property is supported by PhantomJS’s older WebKit engine.
Rank #4
Print CSS or page content is missing
Do not render immediately after the page-open callback if the page continues to load CSS, images, fonts, or generated content. Wait for the relevant resources and an application-specific ready condition. A signal set too early will reproduce the same failure; set it after the content needed in the PDF exists.
The output is clipped or paginates incorrectly
Set the intended format, orientation, and margins before rendering. Then adjust print CSS for the available content width and page breaks. Check for fixed-width elements, large images, and rules that the PhantomJS engine does not support. Validate representative long pages, since content length can reveal pagination issues that a short test page will not.
The PDF is blank or the page never opens
Check the URL from the machine and process that run PhantomJS, not just from your desktop browser. Handle the page-open status and fail the Node operation when it is not successful. Verify the PhantomJS executable can start in the deployment environment and that the target page does not depend on inaccessible local resources or browser features absent from the older engine.
The Node process exits before the file is ready
Await the render operation or its completion callback before shutting down PhantomJS. Keep process cleanup in a finally path so errors do not leave child processes behind, but do not call the exit operation until the render has completed or failed.
Best Value
Local PhantomJS, wrappers, and hosted rendering
Local rendering gives the application control over when to open pages and what paper geometry to use, but Node must start and monitor the PhantomJS process. A Node wrapper can reduce that process-management work and provide a JavaScript-facing readiness mechanism, while its API and lifecycle still depend on the wrapper package in use. A hosted rendering API avoids maintaining a local PhantomJS process; compare the service’s print-media behavior, paper and margin controls, asynchronous-content support, and options such as headers, footers, or page ranges against the document you need.
PhantomJsCloud documents print-media emulation, PDF options, margins, page ranges, and templates. jsreport’s PhantomJS PDF recipe discusses PDF generation and notes that print rules can make output differ from screen HTML. These are options to consider when hosted operation or a rendering workflow is more important than managing a local PhantomJS binary; confirm current service capabilities and terms on their respective sites.
Or skip the browser setup
If your goal is to capture a page as a PDF without maintaining a local PhantomJS process, ScreenshotNeo is a website screenshot API and MCP server for developers. Its PDF endpoint accepts a URL in one GET request. For the full set of options, see the ScreenshotNeo API documentation.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →curl -G "https://api.screenshotneo.com/v1/shot"
-d access_key=YOUR_API_KEY
--data-urlencode url=https://stripe.com
-d format=pdf
-o report.pdf
ScreenshotNeo can accept cookie and consent banners before capture and remove known consent platforms, newsletter popups, and chat widgets; each of those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response reports the page verdict and billing status in headers. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents. 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.
Operational and cost considerations
With local PhantomJS, account for the executable as well as the Node application: deployment, process startup, failure detection, output-file handling, and cleanup all belong to your implementation. Rendering too early can produce an apparently successful but incomplete file, so readiness checks are part of correctness rather than just a performance optimization.
For either a local or hosted workflow, test the same representative pages you expect to render: pages with long content, late-loaded resources, and print-only layout changes. Compare the generated PDF’s page size, margins, and content against the intended output. No general timing or cost figure applies across local infrastructure, wrapper versions, or hosted services; actual resource use depends on page complexity, rendering frequency, and the environment.
Frequently Asked Questions
Does PhantomJS need a special flag to use print CSS?
No. Use a print stylesheet or an @media print block and render the page as a PDF.
Can PhantomJS create a PDF with custom dimensions?
Yes. The paperSize API supports explicit dimensions with units such as mm, cm, in, and px.
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.

