Examples

Retina screenshots with Java and Puppeteer

Heads up before you start

Puppeteer has no official Java port. The closest equivalent is jvppeteer — an actively maintained Java library with a Puppeteer-style API that drives Chrome over the same DevTools Protocol. These examples use jvppeteer.

Add jvppeteer to your Maven project

<dependency>
  <groupId>io.github.fanyong920</groupId>
  <artifactId>jvppeteer</artifactId>
  <version>3.6.5</version>
</dependency>

jvppeteer drives a Chrome you already have installed in a standard location, or call Puppeteer.downloadBrowser() once to download a Chrome for Testing build. Check Maven Central for the latest version.

Take a retina screenshot and save to file

import com.ruiyun.jvppeteer.api.core.Browser;
import com.ruiyun.jvppeteer.api.core.Page;
import com.ruiyun.jvppeteer.cdp.core.Puppeteer;
import com.ruiyun.jvppeteer.cdp.entities.Viewport;

public class Screenshot {
  public static void main(String[] args) throws Exception {
    try (Browser browser = Puppeteer.launch()) {
      Page page = browser.newPage();
      // width, height, deviceScaleFactor, isMobile, hasTouch, isLandscape
      page.setViewport(new Viewport(480, 240, 2.0, false, false, false));
      page.goTo("https://www.htmltoimage.com/demo");
      page.screenshot("retina.png");
    }
  }
}

Find out how to take a full-page screenshot with Java and Puppeteer.

That was 16 lines of code — plus a browser to run in production

Keeping headless browsers fed, patched and scaled is a job in itself. We built Urlbox so the same screenshot is one API call:

curl "https://api.urlbox.com/v1/YOUR_API_KEY/png?url=https://example.com"

Try the Urlbox screenshot API — free trial, no browser babysitting.