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.

PhantomJS image widths usually go wrong because two different settings are being treated as one. page.viewportSize controls the headless browser’s layout viewport, while page.clipRect controls the rectangle copied into the image. Set both deliberately, render, and then inspect the file’s actual pixel dimensions. For PDF output, configure page.paperSize separately.

Understand what PhantomJS is sizing

A PhantomJS capture has at least two dimensions:

  • Layout viewport: page.viewportSize is the size of the headless browser. It affects responsive breakpoints, CSS layout, and what the page considers its visible screen.
  • Captured rectangle: page.clipRect is the portion of the page copied into the screenshot. Its left, top, width, and height determine the output rectangle when you set it explicitly.

Changing only the viewport can change the page’s layout without guaranteeing the saved image has the width you expect. Conversely, changing only the clip rectangle can produce a fixed-size file while capturing a layout designed for a different screen width.

Use a fixed viewport and clip rectangle

The following complete script opens a page at a 1,280-pixel viewport and saves an exactly 1,000-by-700-pixel crop beginning at the page origin.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
var page = require('webpage').create();

page.viewportSize = {
  width: 1280,
  height: 900
};

page.open('https://example.com', function (status) {
  if (status !== 'success') {
    console.log('Open failed: ' + status);
    phantom.exit(1);
    return;
  }

  page.clipRect = {
    top: 0,
    left: 0,
    width: 1000,
    height: 700
  };

  page.render('shot.png');
  phantom.exit();
});

Here, the page lays itself out as if the browser were 1,280 pixels wide, but the PNG contains the 1,000-by-700 region selected by clipRect. If you need the entire viewport in the file, set the clip rectangle to the same width and height as page.viewportSize.

Why the viewport still matters

Responsive sites may switch navigation, columns, font sizes, or hidden elements at particular viewport widths. A 1,000-pixel crop of a page rendered at 1,280 pixels is not equivalent to a page rendered at a 1,000-pixel viewport. Decide first whether your requirement is:

  • A layout at a particular screen size: set viewportSize to that screen size, then capture the desired region.
  • A file with particular pixel dimensions: set clipRect.width and clipRect.height to the required output size, while choosing a viewport that gives the intended layout.
  • A viewport-sized screenshot: use matching dimensions for viewportSize and clipRect.

Diagnose the mismatch in a repeatable order

  1. Confirm the output type. page.render() writes a rendered image when the filename uses an image extension such as PNG, JPEG, or another format supported by your PhantomJS build. Do not diagnose a PDF as though it were an image.
  2. Print the settings immediately before rendering. Confirm that no later callback, helper function, or page-specific branch overwrites page.viewportSize or page.clipRect.
  3. Check the page-open result. Render only after page.open() reports success. A failed or incomplete load can make the visual result appear wrong even when the geometry is correct.
  4. Compare the saved file’s pixel dimensions. Use your operating system’s image information, an image editor, or an image-library script to read the output width and height. This separates an actual capture-size error from a CSS element that merely appears too narrow.
  5. Compare viewport and crop values. If the file is the wrong width, inspect clipRect.width first. If the layout itself changes unexpectedly, inspect viewportSize.width and responsive CSS behavior.
  6. Check scaling assumptions. CSS pixels, device pixels, and image-editor display size are not always presented the same way. Compare the file’s raw pixel dimensions rather than its on-screen display size.

Common configurations

Goal Viewport Clip rectangle Result
Viewport-sized image 1280 × 900 1280 × 900 at (0, 0) Captures the complete viewport rectangle
Fixed crop from a desktop layout 1280 × 900 1000 × 700 at (0, 0) 1,000 × 700 image using the 1,280-pixel layout
Capture an offset region 1280 × 900 800 × 600 at (200, 100) 800 × 600 image starting 200 pixels from the left and 100 from the top
Small responsive layout 768 × 900 768 × 900 at (0, 0) Uses the narrower layout and captures it at viewport size

Values in this table are configuration examples, not guarantees about how a particular site will lay out its content.

Capture a specific element

PhantomJS does not make an element screenshot automatically just because an element has a CSS width. Read the element’s geometry in the page, then assign that geometry to page.clipRect. The viewport must still be wide enough for the page to render the desired layout.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
var page = require('webpage').create();
page.viewportSize = { width: 1280, height: 900 };

page.open('https://example.com', function (status) {
  if (status !== 'success') {
    phantom.exit(1);
    return;
  }

  var box = page.evaluate(function () {
    var el = document.querySelector('#receipt');
    if (!el) return null;
    var r = el.getBoundingClientRect();
    return {
      left: Math.round(r.left + window.pageXOffset),
      top: Math.round(r.top + window.pageYOffset),
      width: Math.round(r.width),
      height: Math.round(r.height)
    };
  });

  if (!box || box.width <= 0 || box.height <= 0) {
    console.log('Element was not found or has no size');
    phantom.exit(1);
    return;
  }

  page.clipRect = box;
  page.render('receipt.png');
  phantom.exit();
});

Fixed headers, scrolling containers, transforms, and content that loads after the initial page event can affect the measured rectangle. If the element is populated asynchronously, wait for a page condition or a short, intentional delay before measuring it.

PDFs use paperSize, not clipRect

For PDF output, page.paperSize defines the page size. PhantomJS accepts units including mm, cm, in, and px; when a unit is omitted, the value is interpreted as pixels. Configure PDF dimensions independently from PNG or JPEG settings.

var page = require('webpage').create();
page.viewportSize = { width: 1200, height: 900 };
page.paperSize = {
  format: 'A4',
  orientation: 'portrait',
  margin: '12mm'
};

page.open('https://example.com', function (status) {
  if (status !== 'success') {
    phantom.exit(1);
    return;
  }
  page.render('page.pdf');
  phantom.exit();
});

A PNG width fix does not change the PDF’s paper width. If a PDF is unexpectedly wide, inspect paperSize, its units, orientation, and margins.

Transparency is a separate issue

A transparent background does not by itself indicate a width mismatch. PhantomJS leaves the page background transparent when the document does not establish one. If a solid background is required, set it in the page before rendering:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
page.evaluate(function () {
  document.body.bgColor = '#ffffff';
});

Use this only when transparency is not desired. Background color changes the appearance, not the geometric relationship between the viewport and clip rectangle.

Troubleshooting by symptom

The image is wider or narrower than the requested crop

Inspect page.clipRect.width and confirm that it is assigned before page.render(). Check that a later function does not replace the rectangle and that you are examining the newly written file rather than a cached or older output.

The file width is right, but the page layout is wrong

Set page.viewportSize.width to the layout width you actually need. A crop can have the correct dimensions while showing a desktop layout, mobile layout, or a clipped responsive breakpoint that was selected by a different viewport.

The right edge is missing

Increase the clip rectangle’s width or move its left coordinate. If the content itself extends beyond the viewport, use a wider viewport or capture the page in sections; a clip rectangle cannot reveal content that the page has not laid out as expected.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

The image is blank or partially loaded

Check the page.open() status, network-dependent content, redirects, and timing. Render after the required content exists. Geometry settings cannot repair a failed page load.

The output looks larger in an editor than its pixel metadata

Check the editor’s zoom and any print or display scaling. Use the file’s intrinsic pixel dimensions for width validation.

The PDF dimensions are wrong while PNG dimensions are correct

Review page.paperSize, units, orientation, and margins. PDF page geometry is a separate configuration path.

Reliability and performance considerations

  • Choose the smallest viewport that still triggers the intended responsive layout; very large viewports can increase page layout and rendering work.
  • Keep the clip rectangle no larger than the region you need when producing many images. This reduces output size, but it does not replace a correctly chosen viewport.
  • Wait for the content that determines the dimensions. Capturing before images, fonts, or JavaScript-rendered sections appear can make a correctly sized file look incomplete.
  • Log the URL, viewport, clip rectangle, output format, open status, and resulting file dimensions for repeatable diagnostics.
  • Use unique output filenames in concurrent jobs so one render cannot overwrite another job’s image.

PhantomJS is an older headless-browser runtime. Existing scripts can still be maintained, but page compatibility, modern JavaScript, and TLS behavior depend on the PhantomJS build and the target site. Treat a successful render as a result for that environment, not a guarantee for every website.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
MixPad Free Multitrack Recording Studio and Music Mixing Software [Download]
  • Create a mix using audio, music and voice tracks and recordings.
  • Customize your tracks with amazing effects and helpful editing tools.
  • Use tools like the Beat Maker and Midi Creator.
  • Work efficiently by using Bookmarks and tools like Effect Chain, which allow you to apply multiple effects at a time
  • Use one of the many other NCH multimedia applications that are integrated with MixPad.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo provides a website screenshot API when you do not want to maintain PhantomJS geometry and page-loading code. It accepts a URL and returns PNG, JPEG, WebP, or PDF. Before capture, it accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks or 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.

One request is enough:

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 all parameters. The equivalent Python and Node.js requests are:

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}`);

ScreenshotNeo also supports full-page captures with lazy images loaded, CSS-selector element captures, dark mode, device presets and custom viewports, retina scale, PDF paper settings and page ranges, custom CSS and JavaScript, pre-capture clicks, selector hiding, selector or network-idle waits, request and resource blocking, custom headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, chosen TTL caching, signed public image links, asynchronous jobs with signed webhooks, bulk requests for up to 100 URLs, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs also work to simplify migration.

An MCP server supplies take_screenshot, get_page_info, and capture_pdf tools to Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try it.

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

FAQ

Does clipRect change the website’s CSS layout?

No. The viewport determines layout; clipRect selects which already-rendered region is saved.

Can I use clipRect to capture content below the page?

It selects a page region, but content must exist and be laid out first. For long pages, ensure the page has loaded all required content before choosing the rectangle.

Best Value
MixPad Multitrack Recording Software for Sound Mixing and Music Production Free [Mac Download]
  • Mix an audio, music and voice tracks
  • Record single or multiple tracks simultaneously
  • Intuitive tools to split, trim, join, and many other editing features
  • Loaded with audio effects including EQ, compression, reverb, and more.
  • Load an audio file and export to all popular audio formats from studio quality wav to high compression formats

Why does a transparent PNG look like it has the wrong size?

Transparency affects background appearance, not pixel dimensions. Validate the file metadata and set a page background only if you need an opaque image.

Frequently Asked Questions

Does clipRect change the website’s CSS layout?

No. The viewport determines layout; clipRect selects which already-rendered region is saved.

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

Can I use clipRect to capture content below the page?

It selects a page region, but content must exist and be laid out first. For long pages, ensure the page has loaded all required content before choosing the rectangle.

Why does a transparent PNG look like it has the wrong size?

Transparency affects background appearance, not pixel dimensions. Validate the file metadata and set a page background only if you need an opaque image.

Quick Recap

Bestseller No. 1
SaleBestseller No. 3
Bestseller No. 4
MixPad Free Multitrack Recording Studio and Music Mixing Software [Download]
MixPad Free Multitrack Recording Studio and Music Mixing Software [Download]
Create a mix using audio, music and voice tracks and recordings.; Customize your tracks with amazing effects and helpful editing tools.
Bestseller No. 5
MixPad Multitrack Recording Software for Sound Mixing and Music Production Free [Mac Download]
MixPad Multitrack Recording Software for Sound Mixing and Music Production Free [Mac Download]
Mix an audio, music and voice tracks; Record single or multiple tracks simultaneously; Intuitive tools to split, trim, join, and many other editing features

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.