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

To generate a PDF that uses print CSS with PhantomJS, set the page’s paper size, open the page, wait until its styles and content are ready, and then render it to a file ending in .pdf. PhantomJS uses the document’s print rules for PDF rendering; the Node.js side must also wait for the PhantomJS operation to finish before treating the file as complete.

How PhantomJS applies print stylesheets

Print-specific layout belongs in either a linked stylesheet marked media="print" or rules wrapped in @media print. When PhantomJS renders a PDF, those rules can change layout, visibility, typography, and page breaks compared with the screen view. A stylesheet intended only for printing should not be expected to affect an ordinary screen rendering.

<link rel="stylesheet" href="/css/print.css" media="print">

<style>
@media print {
  .screen-only { display: none; }
  .report { color: #111; }
  .new-page { page-break-before: always; }
}
</style>

PhantomJS is built on an older WebKit engine. CSS support and pagination should therefore be checked against the exact PhantomJS binary used in production, rather than inferred from a current desktop browser.

Generate a PDF with PhantomJS

The PhantomJS script below sets an A4 portrait page with one-centimeter margins, opens a URL, checks the load status, and renders a PDF. PhantomJS chooses PDF output from the .pdf filename extension.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
var page = require('webpage').create();
page.paperSize = {
  format: 'A4',
  orientation: 'portrait',
  margin: '1cm'
};

page.open('http://localhost:3000/report', function (status) {
  if (status !== 'success') {
    console.error('Could not load report page');
    phantom.exit(1);
    return;
  }

  page.render('/tmp/report.pdf');
  phantom.exit();
});

Save this as a PhantomJS script and run it with the PhantomJS executable. The script is PhantomJS-side JavaScript, not a Node.js module: Node.js can launch and supervise the process, but APIs such as require('webpage') and phantom.exit() are provided inside PhantomJS.

Choose page geometry before rendering

Set page.paperSize before calling render. The API accepts standard formats such as A4 and Letter, or explicit dimensions in units including mm, cm, in, and px. It also supports orientation, margins, and optional repeating headers and footers. See the PhantomJS paperSize reference for the property’s supported values and structure.

Use a named format when the output should match a familiar paper size. Use explicit dimensions when the document has a specific physical size. Margins reduce the printable content area, so a layout that fits in the browser viewport may wrap or paginate differently on paper.

Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Render only after the operation is complete

The render API writes the page to the specified filename; PDF is selected by the extension. Consult the PhantomJS render reference for the rendering method. Do not let an external Node.js process exit or report success until the PhantomJS script has completed. Otherwise, the parent process may stop while rendering is still underway, or downstream code may read an incomplete or missing file.

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

Handle asynchronous pages and generated content

A successful page-open callback does not necessarily mean a modern application has finished every task that affects the PDF. Images, web fonts, JavaScript-generated sections, and delayed data can appear after the initial page load. Rendering immediately can produce missing assets or incomplete content.

Use an explicit readiness condition

For pages you control, expose a readiness flag only after the content required for printing has been inserted and the relevant assets are ready. Your PhantomJS script can poll for that condition before rendering. For a reusable Node wrapper, the phantomjs-node documentation describes a waitForJS readiness mechanism for asynchronous pages. Use a condition that represents the report’s actual completion, rather than an arbitrary short delay.

Rank #3
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • 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

When a page cannot expose a readiness flag, a deliberate delay may be a practical fallback, but it is less reliable: a slow response can outlast the delay, while a fast response wastes time. Validate image and font availability as part of the readiness check when those assets are essential to the printed result.

Why the PDF may ignore print CSS

  • The rules are not print rules. Check that the stylesheet is linked with media="print" or that the rules are inside @media print.
  • The stylesheet has not loaded yet. Wait for the page and its stylesheets to become ready before rendering.
  • The page is rendered too early. Wait for JavaScript-generated content, images, fonts, and delayed data that affect the output.
  • The output uses different page geometry. Set paperSize before rendering and review margins, orientation, and page format.
  • The engine does not support the CSS as expected. PhantomJS uses older WebKit; test the specific CSS features and page-break behavior with the production binary.
  • The screen and print designs intentionally differ. Print rules can hide interface elements or rearrange content, so compare the PDF to the intended print layout rather than the screen page. The jsreport PhantomJS PDF recipe also notes that print rules can make output differ from screen HTML.

Local PhantomJS, a wrapper, or a hosted renderer?

Local PhantomJS gives you direct control of the script and avoids sending the page to a rendering service, but your application must manage the executable, process completion, failures, and generated files. A Node wrapper can make process interaction and readiness handling more convenient; it does not remove the underlying engine’s CSS limits or the need to wait for page content.

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

A hosted renderer shifts local process management to a service, but its print-media behavior and PDF options depend on that service. For example, PhantomJsCloud documentation describes print-media emulation, PDF options, margins, page ranges, and templates. Compare the specific controls you need—including headers, footers, and page ranges—before choosing a route.

Or skip the browser setup

If you need a PDF endpoint without managing a local PhantomJS process, ScreenshotNeo accepts a URL and returns a PDF as well as PNG, JPEG, or WebP screenshots. For API parameters and options, see the ScreenshotNeo documentation.

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

For a PDF response, request the PDF output using the relevant API options in the documentation. ScreenshotNeo’s cleanup can accept cookie and consent banners and remove known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients.

The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots. Sign up for ScreenshotNeo to try the free monthly allowance.

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

Troubleshooting PhantomJS PDF generation

The PDF is missing or empty

  • Check that the page-open status is success and that the PhantomJS process exits with a nonzero status on failure.
  • Confirm the destination directory exists and is writable by the process.
  • Wait for the render operation to complete before the Node.js parent process exits or reads the output.
  • Check the PhantomJS process output and exit code rather than assuming that starting the script means the PDF was created.

Print styles do not appear

  • Verify the CSS is declared for print media.
  • Confirm the stylesheet URL is reachable by the page and allow time for it to load.
  • Try a minimal print rule that visibly changes one element, then test the full stylesheet to isolate unsupported CSS or conflicting rules.
  • Check the result with the production PhantomJS binary because older WebKit may differ from your development browser.

Content or images are missing

  • Do not treat initial navigation completion as proof that asynchronous work has finished.
  • Wait for a page-specific readiness signal, or use the wrapper’s documented readiness mechanism.
  • Check that image and font requests succeed and that JavaScript content has been inserted before rendering.

Pages break in the wrong places

  • Set the paper format, orientation, and margins before rendering.
  • Inspect print CSS page-break rules and content dimensions against the selected paper geometry.
  • Validate output in PhantomJS itself; a layout that paginates correctly in a modern browser may not paginate the same way in its older WebKit engine.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and cost considerations

PDF generation is a browser-rendering job, so page complexity, remote assets, and application readiness all affect how long a reliable capture takes. Avoid using a fixed wait that is shorter than the slowest legitimate page state. For a local deployment, account for launching and monitoring PhantomJS processes, detecting failed loads, and collecting completed files. A hosted service can avoid maintaining that local process, but verify its print-media support and the page controls your workflow requires.

For repeatable output, keep the page geometry and print stylesheet explicit, define a meaningful readiness condition, and test representative pages with the actual rendering binary or service you will use. There is no universal timing or fidelity guarantee for arbitrary pages; behavior depends on the page, assets, CSS, and renderer.

Frequently Asked Questions

Does PhantomJS use @media print when creating a PDF?

Yes. Print-specific stylesheet rules are the mechanism for controlling print layout during PDF rendering. The result depends on the CSS features supported by the PhantomJS WebKit engine.

Can I inject HTML instead of opening a URL?

The workflow can use injected HTML as well as a URL, but any linked stylesheets, assets, and JavaScript content still need to be available and ready before rendering.

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

Can PhantomJS add repeating headers and footers?

The paperSize API includes optional repeating headers and footers; consult its reference for the supported configuration.

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.