How to use convertHtmlToImage method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

index.js

Source: index.js Github

copy
1import html2canvas from 'html2canvas';
2import jsPDF from 'jspdf';
3
4const convertHTMLToPDF = async (html, y) => {
5
6    const canvas = await html2canvas(html, { useCORS: true, y: y || html.offsetTop });
7
8    const imgData = canvas.toDataURL(
9        'image/png');
10    const pdf = new jsPDF('p', 'mm', 'a4');
11    const imgProps = pdf.getImageProperties(imgData);
12    const pdfWidth = pdf.internal.pageSize.getWidth();
13    const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
14
15    let pageNumber = 0;
16    const pageheight = pdf.internal.pageSize.height;
17
18    while (pdfHeight > (pageheight * pageNumber)) {
19        if (pageNumber !== 0) {
20            pdf.addPage();
21        }
22        const pos = 0 - (pageheight * pageNumber);
23        pdf.addImage(imgData, 'PNG', 0, pos, pdfWidth, pdfHeight);
24        pageNumber++;
25    }
26
27    return pdf;
28}
29
30const convertHTMLToImage = async (html) => {
31
32    const canvas = await html2canvas(html, { useCORS: true, y: html.offsetTop });
33
34    return canvas.toDataURL(
35        'image/jpg');
36}
37
38export const downloadHelper = {
39    convertHTMLToPDF,
40    convertHTMLToImage
41}
42
43export default downloadHelper;
Full Screen

http-server.js

Source: http-server.js Github

copy
1let http = require('http');
2let convertHtmlToImage = require('./convert-html-to-image');
3
4const port = 8080;
5
6http.createServer(function(req, res) {
7  const headers = {
8    'Access-Control-Allow-Origin': '*',
9    'Access-Control-Allow-Headers': 'Content-Type',
10    // 'Content-Type': 'text/html',
11    'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
12    'Access-Control-Max-Age': 2592000, // 30 days
13    /** add other headers as per requirement */
14  };
15
16  if (req.method === 'OPTIONS') {
17    res.writeHead(204, headers);
18    res.end();
19    return;
20  }
21
22  if (['GET', 'POST'].indexOf(req.method) > -1) {
23
24    if (req.url == '/submitForm') {
25      parseRequestBody(req, res, headers);
26      return;
27    }
28    else {
29      res.writeHead(200, headers);
30      res.end('Request Parsed');
31      return;
32    }
33
34  }
35
36  res.writeHead(405, headers);
37  res.end(`${req.method} is not allowed for the request.`);
38
39}).listen(port);
40
41function convertToImage(data) {
42  let date = new Date();
43  return convertHtmlToImage.convertToPng(data, `output-image-${date.getTime()}`);
44}
45
46function parseRequestBody(req, res, headers) {
47    // parsing request body
48    // At this point, we have the headers, method, url and body, and can now
49    // do whatever we need to in order to respond to this request.
50    const { reqHeaders, reqMethod, reqURL } = req;
51
52    let body = [];
53    req.on('error', (err) => {
54      console.error(err);
55    }).on('data', (chunk) => {
56      body.push(chunk);
57    }).on('end', () => {
58      body = Buffer.concat(body).toString(); // at this point, `body` has the entire request body stored in it as a string
59
60      convertToImage(JSON.parse(body).data).then(response => {
61        headers['Content-Type'] = 'application/json'
62
63        if (response.success) {
64          res.writeHead(200, headers);
65        }
66        else {
67          res.writeHead(500, headers);
68        }
69
70        res.on('error', error => {
71          console.error('Error: ', error)
72        })
73
74        res.end(JSON.stringify(response));
75      });
76    });
77}
78
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cypress on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)