Reputation: 177
I'm using a lambda function to launch puppeteer with headless chrome. I'm able to take a picture and save it to an s3 bucket, but the image is way too big. I was originally setting the viewport to default, but the image was still coming out as 1520 X 1520.
Here is my current code to launch the headless browser and take the screenshot.
const browser = await chromium.puppeteer.launch({
executablePath: await chromium.executablePath,
headless: chromium.headless,
args: chromium.args,
defaultViewport: { width: 800, height: 600, deviceScaleFactor: 2 },
ignoreHTTPSErrors: true,
});
const body = isJson(event.data ? event.data : event.body);
const timeStamp = Date.now();
const HandleBars = require("handlebars");
const bucketForTemplates = {
Bucket: templateBucket,
Key: `${body.template}.hbs`,
};
const file = await s3.getObject(bucketForTemplates).promise();
const template = HandleBars.compile(file.Body.toString());
const renderedPage = template(body);
const page = await browser.newPage();
await page.setViewport({ deviceScaleFactor: 2 });
await page.setContent(renderedPage);
//wait for page to load
await page.waitForSelector("#image");
const image = await page.$("#image");
const box = await image.boundingBox();
const x = box["x"];
const y = box["y"];
const w = box["width"];
const h = box["height"];
const buffer = await page.screenshot({
type: "jpeg",
clip: { x: x, y: y, width: w, height: h },
});
await page.close();
await browser.close();
//save image to s3.
The div I am taking a picture of has a set width of 760px and height of 760px but the screenshot is 1520 X 1520.
How do I reduce the size of the image to not be so big?
Upvotes: 5
Views: 5188
Reputation: 16856
You launch puppeteer with deviceScaleFactor: 2
viewport setting:
const browser = await chromium.puppeteer.launch({
defaultViewport: { width: 800, height: 600, deviceScaleFactor: 2 }, // <----
});
According to docs, it "can be thought of as DPR", or device pixel ratio, thus enlarging resolution by 2.
The default for this setting is 1
, which is what you'd like to use to get the screenshot of a correct size.
Upvotes: 4