How to use emulateMediaType method in Puppeteer

Best JavaScript code snippet using puppeteer

Run Puppeteer automation tests on LambdaTest cloud grid

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

renderer.js

Source: renderer.js Github

copy
1/*
2 * @Author: samy
3 * @email: yessz#foxmail.com
4 * @time: 2022-04-21 00:15:24
5 * @modAuthor: samy
6 * @modTime: 2022-04-21 00:15:25
7 * @desc: 
8 * Copyright © 2015~2022 BDP FE
9 */
10/*
11 * @Author: samy
12 * @email: yessz#foxmail.com
13 * @time: 2022-04-07 10:15:23
14 * @modAuthor: samy
15 * @modTime: 2022-04-21 00:14:57
16 * @desc: 渲染相关封装
17 * Copyright © 2015~2022 BDP FE
18 */
19
20'use strict'
21const yup = require('yup')
22let chromium;
23let puppeteer;
24
25// // vercel兼容方案处理
26// // if (process.env.AWS_LAMBDA_FUNCTION_VERSION) {
27// // running on the Vercel platform.
28puppeteer = require('puppeteer-core');
29chromium = require('chrome-aws-lambda');
30// // } else {
31// //   puppeteer = require('puppeteer');// running locally.
32// // }
33
34const defaultTime = 1000 * 60 * 10 //6min
35
36const pageSchema = yup.object({
37  timeout: yup.number().default(30 * 1000),
38  waitUntil: yup.string().default('networkidle2'),
39  credentials: yup.string(),
40  headers: yup.string(),
41  emulateMediaType: yup.string(),
42})
43
44const pdfSchema = yup.object({
45  path: yup.string(),
46  scale: yup.number().default(1.0),
47  displayHeaderFooter: yup.boolean(),
48  headerTemplate: yup.string(),
49  footerTemplate: yup.string(),
50  printBackground: yup.boolean(),
51  landscape: yup.boolean(),
52  pageRanges: yup.string(),
53  format: yup.string(),
54  width: yup.string(),
55  height: yup.string(),
56  margin: yup.object({
57    top: yup.string(),
58    right: yup.string(),
59    bottom: yup.string(),
60    left: yup.string(),
61  }),
62  preferCSSPageSize: yup.boolean(),
63})
64
65class Renderer {
66  constructor(browser) {
67    this.browser = browser
68  }
69
70  async html(url, options = {}) {
71    let page = null
72    try {
73      const { timeout, waitUntil, credentials, headers } = options
74      page = await this.createPage(url, { timeout, waitUntil, credentials, headers })
75      const html = await page.content()
76      return html
77    } finally {
78      this.closePage(page)
79    }
80  }
81
82  async pdf(url, options = {}) {
83    let page = null
84    try {
85      const { timeout, waitUntil, credentials, headers, emulateMediaType, ...extraOptions } = options
86      page = await this.createPage(url, {
87        timeout,
88        waitUntil,
89        credentials,
90        headers,
91        emulateMediaType: emulateMediaType || 'print',
92      })
93      const pdfOptions = await pdfSchema.validate(extraOptions)
94      console.info("----begin---page.pdf-----", new Date(), url);
95      return await page.pdf({ ...pdfOptions, timeout: defaultTime })
96    } catch (error) {
97      console.error('---pdf---', error);
98      throw new Error(error)
99    } finally {
100      this.closePage(page)
101    }
102  }
103
104  async createPage(url, options = {}) {
105    try {
106      const { timeout, waitUntil, credentials, emulateMediaType, headers, waitForFunction } = await pageSchema.validate(options)
107      const page = await this.browser.newPage()
108      if (headers) {
109        await page.setExtraHTTPHeaders(JSON.parse(headers))
110      }
111      await page.setCacheEnabled(false)
112      await page.setDefaultNavigationTimeout(0); //这个配置跟下面的goto中的设置冲突;
113      // await page.setDefaultTimeout(defaultTime);
114      page.on('error', async error => {
115        await this.closePage(page)
116        throw new Error(error)
117      })
118      if (emulateMediaType) {
119        await page.emulateMediaType(emulateMediaType)
120      }
121      if (credentials) {
122        await page.authenticate(credentials)
123      }
124      console.log("-----begin--page.goto-----", new Date(), url);
125      // await page.goto(url, { timeout: timeout || defaultTime, waitUntil })
126      await page.goto(url, { waitUntil })
127      const renderdoneHandle = await page.waitForFunction('window.renderReportFlag', { polling: 120, timeout: defaultTime })
128      const renderdone = await renderdoneHandle.jsonValue();
129      if (renderdone) {
130        console.info('页面请求接口加载成功!', new Date(), url)
131      } else {
132        console.info('页面请求加载中...')
133      }
134      return page
135    } catch (error) {
136      console.error('---createPage---', error);
137      throw new Error(error)
138    }
139  }
140
141  async closePage(page) {
142    try {
143      if (page && !page.isClosed()) {
144        await page.close()
145      }
146    } catch (e) { }
147  }
148
149  async close() {
150    await this.browser.close()
151  }
152}
153
154async function create(options = {}) {
155  // const browser = await puppeteer.launch(Object.assign({
156  const browser = await chromium.puppeteer.launch(Object.assign({
157    args: [
158      '--disable-gpu',
159      '--full-memory-crash-report',
160      '--unlimited-storage',
161      '--no-sandbox',
162      '--disable-setuid-sandbox',
163      '--disable-dev-shm-usage',
164      '--ignore-certificate-errors',
165    ],
166  }, {
167    ...options,
168    args: chromium.args,
169    headless: chromium.headless,
170    executablePath: await chromium.executablePath,
171  }))
172  // const browser = await chromium.puppeteer.launch({
173  //   args: chromium.args,
174  //   executablePath: await chromium.executablePath,
175  //   headless: chromium.headless,
176  //   ignoreHTTPSErrors: true,
177  // });
178  return new Renderer(browser)
179}
180
181module.exports = create
182
Full Screen

pdfConfigService.js

Source: pdfConfigService.js Github

copy
1class PdfConfigService {
2  static margin(value) {
3    value = parseInt(value);
4    return Number.isInteger(value) ? value : 0;
5  }
6  static stripAnchorTagsFromHtml(value) {
7    return (this.stripAnchorTagsFromHtmlValue = value == 'true'); // jshint ignore:line
8  }
9
10  static title(title) {
11    return title ? title : 'View LPA - View a lasting power of attorney';
12  }
13
14  static subject(subject) {
15    return subject ? subject : '';
16  }
17
18  static emulateMediaType(emulateMediaType) {
19    return emulateMediaType ? emulateMediaType : 'print';
20  }
21
22  static printBackground(value) {
23    return (this.printBackgroundValue = value == 'true'); // jshint ignore:line
24  }
25}
26
27export default PdfConfigService;
28
Full Screen

compileHbsPuppeteer.js

Source: compileHbsPuppeteer.js Github

copy
1// import packages
2const chromium = require("chrome-aws-lambda");
3const hummus = require("hummus-lambda");
4// import files
5const {
6    pdfCompile1,
7    pdfCompile23,
8} =require('./compileHbsJson')
9
10const {
11    base64_encode,
12    headerFunction,
13    upload
14} =require('./globalhelper')
15
16
17
18// pdf1  Puppetter compilation hbs files
19
20const pdf1Main = async (jsonValues) => {
21    // const browser = await puppeteer.launch({
22    //     args: ["--no-sandbox", "--disable-setuid-sandbox"],
23    // });
24    const browser = await chromium.puppeteer.launch({
25        args: chromium.args,
26        defaultViewport: chromium.defaultViewport,
27        executablePath: await chromium.executablePath,
28        headless: chromium.headless,
29        ignoreHTTPSErrors: true,
30    });
31    // const browser = await puppeteer.launch({ executablePath: "./node_modules/puppeteer/.local-chromium/win64-656675/chrome-win/chrome.exe"})
32    const page = await browser.newPage();
33
34    // header Styling in an array
35    var cssb = [];
36    cssb.push("<style>");
37    cssb.push(`.t0 {
38      width: 460px;
39      font: 16px 'Calibri';
40      color: #ffffff;
41  }.tr0 {
42      height: 30px;
43  }.td0 {
44      padding: 0px;
45      margin: 0px;
46      width: 1000px;
47      vertical-align: bottom;
48      background-color: #0086c1;
49  }
50
51  .td1 {
52      padding: 0px;
53      margin: 0px;
54      width:200px;
55      vertical-align: bottom;
56      background-color: #0086c1;
57  }.ft3 {
58      font: 12px 'Calibri';
59      color: #ffffff;
60      line-height: 19px;
61  }.p8 {
62      text-align: left;
63      padding-left: 10px;
64      margin-top: 0px;
65      margin-bottom: 0px;
66      white-space: nowrap;
67  }
68
69  .p9 {
70      text-align: left;
71      margin-top: 0px;
72      
73      margin-bottom: 0px;
74      white-space: nowrap;
75  }
76  .tr1 {
77      height: 5px;
78  }
79  .p9 {
80      text-align: left;
81      margin-top: 0px;
82      margin-bottom: 0px;
83      white-space: nowrap;
84  }
85  .ft4 {
86      font: 1px 'Calibri';
87      line-height: 14px;
88  }
89`);
90    cssb.push("</style>");
91    const css = cssb.join("");
92
93    // assigning value for property Address
94    var addr = {};
95    jsonValues.map((a, i, arr) => {
96        if (a.name === "E1.2") {
97            a.name = "E11.2";
98        }
99        a.name = a.name.replace(".", "");
100        if (a.name === "A03") {
101            // console.log(a.value.split('\n'))
102            // addr[a.name] = a.value.split('\n')[0].toUpperCase()
103            addr[a.name] = a.value;
104        }
105        if (a.name === "A06") {
106            addr[a.name] = a.value;
107        }
108    });
109    const jsonValues1 = [...jsonValues];
110    // pdf1 Header
111    let header1 = `
112  <header style="-webkit-print-color-adjust: exact;margin-left:70em;">
113      <TABLE cellpadding=0 cellspacing=0 class="t0">
114          <TR>
115              <TD class="tr0 td0">
116                  <P class="p8 ft3">RESIDENTIAL VALUATION REPORT</P>
117              </TD>
118              <TD class="tr0 td1">
119                  <P class="p9 ft3">${addr.A06}</P>
120              </TD>
121          </TR>
122          <TR>
123              <TD  style="
124              background: #00b0de;">
125                  <P class="p9 ft4">&nbsp;</P>
126              </TD>
127              <TD  style="
128              background: #00b0de;">
129                  <P class="p9 ft4">&nbsp;</P>
130              </TD>
131          </TR>
132      </TABLE>
133  </header>
134  `;
135    // compiling html with Json Values by calling pdfCompile1 Fn
136    // Cover Page pdf
137    let coverPageContent = await pdfCompile1("coverpdf1", jsonValues1);
138
139    console.log("First Page");
140    await page.setDefaultNavigationTimeout(0);
141    await page.setContent(coverPageContent);
142    await page.emulateMediaType("screen");
143    const page1 = await page.pdf({
144        format: "A4",
145        // path: "coverPage.pdf",
146        pageRanges: "1",
147
148        printBackground: true,
149    });
150    const dimensions = await page.evaluate(() => {
151        return {
152            width: document.documentElement.clientWidth,
153            height: document.documentElement.clientHeight,
154            deviceScaleFactor: window.devicePixelRatio,
155        };
156    });
157
158    console.log("Dimensions:", dimensions);
159    // Remaining Pages
160    contents = await pdfCompile1("short-list", jsonValues);
161
162    await page.setContent(contents);
163
164    await page.emulateMediaType("screen");
165    const remainingPages = await page.pdf({
166        // path: 'mypdf.pdf',
167        format: "A4",
168
169        printBackground: true,
170        displayHeaderFooter: true,
171        headerTemplate: css + header1,
172        footerTemplate: `<footer style="font-size:8px;margin-left:9em;">
173      <div class="drawline" style="width: 57em;
174      border-bottom: 15px solid #00afde;
175      background-color: #00afde;">
176      </div>
177      <TABLE cellpadding=0 cellspacing=0 width="100%" class="t2">
178          <TR>
179              <TD class="tr7 td8">
180                  <P class="p9 ft8">${addr.A03}</P>
181              </TD>
182              <TD class="tr7 td9" >
183                  <P class="pageNumber" style="color:black"></P>
184              </TD>
185          </TR>
186      </TABLE>
187  </footer>`,
188        margin: {
189            top: "105px",
190            bottom: "100px",
191            right: "30px",
192            left: "40px",
193        },
194    });
195
196    await browser.close();
197    // Combine all pdf's using Stream Buffer
198    const combinePDFBuffers = async (page1, remainingPages) => {
199        var outStream = new memoryStreams.WritableStream();
200
201        try {
202            var page1 = await new hummus.PDFRStreamForBuffer(page1);
203            var remainingPages = await new hummus.PDFRStreamForBuffer(
204                remainingPages
205            );
206
207            var pdfWriter = await hummus.createWriterToModify(
208                page1,
209                new hummus.PDFStreamForResponse(outStream)
210            );
211
212            await pdfWriter.appendPDFPagesFromPDF(remainingPages);
213
214            pdfWriter.end();
215            var newBuffer = await outStream.toBuffer();
216            outStream.end();
217            return newBuffer;
218        } catch (e) {
219            outStream.end();
220            console.log("Error during PDF combination: " + e.message);
221        }
222    };
223    var result = await combinePDFBuffers(page1, remainingPages);
224
225    return result;
226};
227
228
229// pdf2  Puppetter compilation hbs files
230const pdf2Main = async (jsonValues) => {
231    // const browser = await puppeteer.launch({
232    //     args: [
233    //         "--no-sandbox",
234    //         "--disable-setuid-sandbox",
235    //         "--font-render-hinting=none",
236    //     ],
237    // });
238    const browser = await chromium.puppeteer.launch({
239        args: chromium.args,
240        defaultViewport: chromium.defaultViewport,
241        executablePath: await chromium.executablePath,
242        headless: chromium.headless,
243        ignoreHTTPSErrors: true,
244    });
245    const page = await browser.newPage();
246    // Storing Address value for property address
247    var addr = {};
248    jsonValues.map((a) => {
249        a.name = a.name.replace(".", "S");
250        if (a.name === "A0S9") {
251            addr[a.name] = a.value.replace("\n", " ").trim();
252        }
253    });
254    // All images for header and footer converted in base64 encode String
255    var rics = await base64_encode("rics.jpg");
256    var ricshomebuyer = await base64_encode("RicsHomeuyerReport.jpg");
257    var B = await base64_encode("homebuyer/B.jpg");
258    var C = await base64_encode("homebuyer/C.jpg");
259    var D = await base64_encode("homebuyer/D.jpg");
260    var E = await base64_encode("homebuyer/E.png");
261    var F = await base64_encode("homebuyer/F.png");
262    var G = await base64_encode("homebuyer/G.jpg");
263    var H = await base64_encode("homebuyer/H.png");
264    var I = await base64_encode("homebuyer/I.png");
265    var J = await base64_encode("homebuyer/J.png");
266    var K = await base64_encode("homebuyer/K.jpg");
267    var L = await base64_encode("homebuyer/L.png");
268    var Fi1 = await base64_encode("homebuyer/homeFinal.jpg");
269    // Footer Tag for Home Buyer PDF
270    let footeradr = `
271  <div id="footer-template" style="font-size:10px !important;padding-left:10px">
272      
273  <table style="margin-left: 1.6em;">
274  <tr>
275  <td>
276      <P style="margin-left:-2em;text-align:left;padding-left:42px;color:#a0a4b0;font-size:11px;">Property address</P>
277  </td>
278  <td>
279      <div style="
280              border: 1px solid #a0a4b0;
281              width: 39em;height:2em;
282          margin-left: -7em;
283          ">
284          <p style="margin-top: -0em;padding-left: 1em;padding-top: 0.7em;font-size:8px;">${addr.A0S9}</p>
285      </div>
286  </td>
287  </tr>
288          <tr>
289              <td>
290                  <img src="data:image/jpeg;base64,${rics}" width="180em">
291              </td>
292              <td style="padding-left: 13em;">
293                  <img src="data:image/jpeg;base64,${ricshomebuyer}" width="230em">
294              </td>
295          </tr>
296      </table>
297  </div>
298  `;
299
300    // Header Tag for C page
301    const headerC = `
302              < div style = "margin-top:15em;" >
303                  <table style="margin:0em 70em 0em">
304                      <tr>
305                          <td>
306                              <img src="data:image/jpeg;base64,${C}" width="30em">
307                  </td>
308                              <td style="padding-left:30em;">
309                                  <div style="font-family: Arial, Helvetica, sans-serif;
310          line-height: 1.2em;
311          font-size:20px;">Overall opinion and summary of the condition ratings</div>
312                                  <div style="margin-top:6em;border-bottom: 0.5px solid #a0a4b0;border-width: medium;width: 400em;"></div>
313                              </td>
314              </tr>
315          </table>
316      </div>
317          `;
318
319    // All headers with image, width, font, Title
320    const headerb = headerFunction(
321        B,
322        "30",
323        "70",
324        "20",
325        "30",
326        "About the Inspection"
327    );
328    const headerd = headerFunction(
329        D,
330        "30",
331        "70",
332        "20",
333        "30",
334        "About the property"
335    );
336    const headere = headerFunction(
337        E,
338        "25",
339        "70",
340        "20",
341        "40",
342        "Outside the property"
343    );
344    const headerf = headerFunction(
345        F,
346        "25",
347        "70",
348        "20",
349        "40",
350        "Inside the property"
351    );
352    const headerg = headerFunction(G, "30", "70", "19.5", "40", "Services");
353    const headerh = headerFunction(
354        H,
355        "30",
356        "70",
357        "20",
358        "30",
359        "Grounds (including shared areas for flats)"
360    );
361    const headeri = headerFunction(
362        I,
363        "14",
364        "70",
365        "21",
366        "30",
367        "Issues for your legal advisers"
368    );
369    const headerj = headerFunction(J, "16", "70", "20.5", "30", "Risks");
370    const headerk = headerFunction(K, "32", "60", "20", "30", "Valuation");
371    const headerl = headerFunction(
372        L,
373        "32",
374        "60",
375        "20",
376        "40",
377        "Surveyor's declaration"
378    );
379    const headerFinal = headerFunction(
380        "",
381        "",
382        "90",
383        "20",
384        "40",
385        "What to do now"
386    );
387    const headerFinal1 = headerFunction(
388        "",
389        "",
390        "90",
391        "20",
392        "40",
393        "Typical house diagram"
394    );
395    console.log("second Page");
396    // Cover Page
397    let content1 = await pdfCompile23("homebuyercover", jsonValues, addr);
398    await page.setContent(content1);
399    await page.emulateMediaType("screen");
400    const h1 = await page.pdf({
401        // path: 'homebuyercover.pdf',
402        printBackground: true,
403        format: "A4",
404    });
405    // Home B
406    content1 = await pdfCompile23("homeB", jsonValues);
407    await page.setContent(content1);
408    await page.emulateMediaType("screen");
409    const h2 = await page.pdf({
410        // path: 'homeB.pdf',
411        printBackground: true,
412        format: "A4",
413        displayHeaderFooter: true,
414        headerTemplate: headerb,
415        footerTemplate: footeradr,
416        margin: {
417            top: "100px",
418            bottom: "128px",
419            right: "30px",
420            left: "25px",
421        },
422    });
423    // Home C
424    content1 = await pdfCompile23("homeC", jsonValues);
425    await page.setContent(content1);
426    await page.emulateMediaType("screen");
427    const h3 = await page.pdf({
428        // path: 'homeC.pdf',
429        printBackground: true,
430        format: "A4",
431        displayHeaderFooter: true,
432        headerTemplate: headerC,
433        footerTemplate: footeradr,
434        margin: {
435            top: "120px",
436            bottom: "128px",
437            right: "30px",
438            left: "25px",
439        },
440    });
441    // Home D
442    content1 = await pdfCompile23("homeD", jsonValues);
443    await page.setContent(content1);
444    await page.emulateMediaType("screen");
445    const h4 = await page.pdf({
446        // path: 'homeD.pdf',
447        printBackground: true,
448        format: "A4",
449        displayHeaderFooter: true,
450        headerTemplate: headerd,
451        footerTemplate: footeradr,
452        margin: {
453            top: "100px",
454            bottom: "128px",
455            right: "30px",
456            left: "25px",
457        },
458    });
459    // Home E
460    content1 = await pdfCompile23("homeE", jsonValues);
461    await page.setContent(content1);
462    await page.emulateMediaType("screen");
463    const h5 = await page.pdf({
464        // path: 'homeE.pdf',
465        printBackground: true,
466        format: "A4",
467        displayHeaderFooter: true,
468        headerTemplate: headere,
469        footerTemplate: footeradr,
470        margin: {
471            top: "110px",
472            bottom: "128px",
473            right: "30px",
474            left: "25px",
475        },
476    });
477    // Home F
478    content1 = await pdfCompile23("homeF", jsonValues);
479    await page.setContent(content1);
480    await page.emulateMediaType("screen");
481    const h6 = await page.pdf({
482        // path: 'homeF.pdf',
483        printBackground: true,
484        format: "A4",
485        displayHeaderFooter: true,
486        headerTemplate: headerf,
487        footerTemplate: footeradr,
488        margin: {
489            top: "110px",
490            bottom: "128px",
491            right: "30px",
492            left: "25px",
493        },
494    });
495    // Home G
496    content1 = await pdfCompile23("homeG", jsonValues);
497    await page.setContent(content1);
498    await page.emulateMediaType("screen");
499    const h7 = await page.pdf({
500        // path: 'homeG.pdf',
501        printBackground: true,
502        format: "A4",
503        displayHeaderFooter: true,
504        headerTemplate: headerg,
505        footerTemplate: footeradr,
506        margin: {
507            top: "110px",
508            bottom: "128px",
509            right: "30px",
510            left: "25px",
511        },
512    });
513    // Home H
514    content1 = await pdfCompile23("homeH", jsonValues);
515    await page.setContent(content1);
516    await page.emulateMediaType("screen");
517    const h8 = await page.pdf({
518        // path: 'homeH.pdf',
519        printBackground: true,
520        format: "A4",
521        displayHeaderFooter: true,
522        headerTemplate: headerh,
523        footerTemplate: footeradr,
524        margin: {
525            top: "105px",
526            bottom: "128px",
527            right: "30px",
528            left: "25px",
529        },
530    });
531    // Home I
532    content1 = await pdfCompile23("homeI", jsonValues);
533    await page.setContent(content1);
534    await page.emulateMediaType("screen");
535    const h9 = await page.pdf({
536        // path: 'homeI.pdf',
537        printBackground: true,
538        format: "A4",
539        displayHeaderFooter: true,
540        headerTemplate: headeri,
541        footerTemplate: footeradr,
542        margin: {
543            top: "105px",
544            bottom: "128px",
545            right: "30px",
546            left: "25px",
547        },
548    });
549    // Home J
550    content1 = await pdfCompile23("homeJ", jsonValues);
551    await page.setContent(content1);
552    await page.emulateMediaType("screen");
553    const h10 = await page.pdf({
554        // path: 'homeJ.pdf',
555        printBackground: true,
556        format: "A4",
557        displayHeaderFooter: true,
558        headerTemplate: headerj,
559        footerTemplate: footeradr,
560        margin: {
561            top: "105px",
562            bottom: "128px",
563            right: "30px",
564            left: "25px",
565        },
566    });
567    // Home K
568    content1 = await pdfCompile23("homeK", jsonValues);
569    await page.setContent(content1);
570    await page.emulateMediaType("screen");
571    const h11 = await page.pdf({
572        // path: 'homeK.pdf',
573        printBackground: true,
574        format: "A4",
575        displayHeaderFooter: true,
576        headerTemplate: headerk,
577        footerTemplate: footeradr,
578        margin: {
579            top: "105px",
580            bottom: "128px",
581            right: "30px",
582            left: "25px",
583        },
584    });
585    // Home L
586    content1 = await pdfCompile23("homeL", jsonValues);
587    await page.setContent(content1);
588    await page.emulateMediaType("screen");
589    const h12 = await page.pdf({
590        // path: 'homeL.pdf',
591        printBackground: true,
592        format: "A4",
593        displayHeaderFooter: true,
594        headerTemplate: headerl,
595        footerTemplate: footeradr,
596        margin: {
597            top: "105px",
598            bottom: "128px",
599            right: "30px",
600            left: "25px",
601        },
602    });
603    // What to do Now page
604    content1 = await pdfCompile23("homeFinal", jsonValues);
605    await page.setContent(content1);
606    await page.emulateMediaType("screen");
607    const h13 = await page.pdf({
608        // path: 'homeFinal.pdf',
609        printBackground: true,
610        format: "A4",
611        displayHeaderFooter: true,
612        headerTemplate: headerFinal,
613        footerTemplate: footeradr,
614        margin: {
615            top: "105px",
616            bottom: "128px",
617            right: "30px",
618            left: "25px",
619        },
620    });
621    // last page with home image
622    content1 = await pdfCompile23("homeFinal1", jsonValues);
623    await page.setContent(content1);
624    await page.emulateMediaType("screen");
625    const h14 = await page.pdf({
626        // path: 'homeFinal.pdf',
627        printBackground: true,
628        format: "A4",
629        displayHeaderFooter: true,
630        headerTemplate: headerFinal1,
631        footerTemplate: footeradr,
632        margin: {
633            top: "105px",
634            bottom: "128px",
635            right: "30px",
636            left: "25px",
637        },
638    });
639    await browser.close();
640    // Merge all pdf's
641    const combinePDFBuffers = async (array) => {
642        var outStream = new memoryStreams.WritableStream();
643
644        try {
645            var h1 = new hummus.PDFRStreamForBuffer(array[0]);
646            var pdfWriter = hummus.createWriterToModify(
647                h1,
648                new hummus.PDFStreamForResponse(outStream)
649            );
650            array.shift();
651            array.forEach((a1) => {
652                var a1 = new hummus.PDFRStreamForBuffer(a1);
653                pdfWriter.appendPDFPagesFromPDF(a1);
654            });
655            pdfWriter.end();
656            var newBuffer = await outStream.toBuffer();
657            outStream.end();
658            return newBuffer;
659        } catch (e) {
660            outStream.end();
661            console.log("Error during PDF combination: " + e.message);
662        }
663    };
664    var result = await combinePDFBuffers([
665        h1,
666        h2,
667        h3,
668        h4,
669        h5,
670        h6,
671        h7,
672        h8,
673        h9,
674        h10,
675        h11,
676        h12,
677        h13,
678        h14,
679    ]);
680    return result;
681};
682
683// pdf3  Puppetter compilation hbs files
684const pdf3Main = async (jsonValues) => {
685    // const browser = await puppeteer.launch({
686    //     args: [
687    //         "--no-sandbox",
688    //         "--disable-setuid-sandbox",
689    //         "--font-render-hinting=none",
690    //     ],
691    // });
692    const browser = await chromium.puppeteer.launch({
693        args: chromium.args,
694        defaultViewport: chromium.defaultViewport,
695        executablePath: await chromium.executablePath,
696        headless: chromium.headless,
697        ignoreHTTPSErrors: true,
698    });
699    const page = await browser.newPage();
700    // Add address value for property address in footer tag
701    var addr = {};
702    jsonValues.map((a) => {
703        a.name = a.name.replace(".", "S");
704        if (a.name === "A0S9") {
705            addr[a.name] = a.value.replace("\n", " ");
706        }
707    });
708
709    // Covert all images in base64 encode Stiring
710    var rics = await base64_encode("rics.jpg");
711    var ricshomebuyer = await base64_encode("RicsHomeuyerReport.jpg");
712    var B = await base64_encode("homebuyer/B.jpg");
713    var C = await base64_encode("homebuyer/C.jpg");
714    var D = await base64_encode("homebuyer/D.jpg");
715    var E = await base64_encode("homebuyer/E.png");
716    var F = await base64_encode("homebuyer/F.png");
717    var G = await base64_encode("homebuyer/G.jpg");
718    var H = await base64_encode("homebuyer/H.png");
719    var I = await base64_encode("homebuyer/I.png");
720    var J = await base64_encode("homebuyer/J.png");
721    var K = await base64_encode("homebuyer/K.jpg");
722    var L = await base64_encode("homebuyer/L.png");
723    var Fi1 = await base64_encode("homebuyer/homeFinal.jpg");
724    // Footer Tag for Home Survey pdf aka PDF 3
725    let footeradr = `
726  <div id="footer-template" style="font-size:10px !important;padding-left:10px">
727      
728  <table style="margin-left: 1.6em;">
729  <tr>
730  <td>
731      <P style="margin-left:-2em;text-align:left;padding-left:42px;color:#a0a4b0;font-size:11px;">Property address</P>
732  </td>
733  <td>
734      <div style="
735              border: 1px solid #a0a4b0;
736              width: 39em;height:2em;
737          margin-left: -7em;
738          ">
739          <p style="margin-top: -0em;padding-left: 1em;padding-top: 0.7em;font-size:8px;">${addr.A0S9}</p>
740      </div>
741  </td>
742  </tr>
743          <tr>
744              <td>
745                  <img src="data:image/jpeg;base64,${rics}" width="180em">
746              </td>
747              <td style="padding-left: 13em;">
748                  <img src="data:image/jpeg;base64,${ricshomebuyer}" width="230em">
749              </td>
750          </tr>
751      </table>
752  </div>
753  `;
754    // Header Tag for C page
755    const headerC = `
756  <div style="margin-top:15em;">
757                  <table style="margin:0em 70em 0em">
758                      <tr>
759                          <td>
760                              <img src="data:image/jpeg;base64,${C}" width="30em">
761                  </td>
762                              <td style="padding-left:30em;">
763                                  <div style="font-family: Arial, Helvetica, sans-serif;
764          line-height: 1.2em;
765          font-size:20px;">Overall opinion and summary of the condition ratings</div>
766                                  <div style="margin-top:6em;border-bottom: 0.5px solid #a0a4b0;border-width: medium;width: 400em;"></div>
767                              </td>
768              </tr>
769          </table>
770      </div>
771  `;
772    // All headers with specified args (image, width, font, Title)
773    const headerb = headerFunction(
774        B,
775        "30",
776        "70",
777        "20",
778        "30",
779        "About the Inspection"
780    );
781    const headerd = headerFunction(
782        D,
783        "30",
784        "70",
785        "20",
786        "30",
787        "About the property"
788    );
789    const headere = headerFunction(
790        E,
791        "25",
792        "70",
793        "20",
794        "40",
795        "Outside the property"
796    );
797    const headerf = headerFunction(
798        F,
799        "25",
800        "70",
801        "20",
802        "40",
803        "Inside the property"
804    );
805    const headerg = headerFunction(G, "30", "70", "19.5", "40", "Services");
806    const headerh = headerFunction(
807        H,
808        "30",
809        "70",
810        "20",
811        "30",
812        "Grounds (including shared areas for flats)"
813    );
814    const headeri = headerFunction(
815        I,
816        "14",
817        "70",
818        "21",
819        "30",
820        "Issues for your legal advisers"
821    );
822    const headerj = headerFunction(J, "16", "70", "20.5", "30", "Risks");
823    const headerk = headerFunction(
824        K,
825        "32",
826        "70",
827        "20",
828        "30",
829        "Energy efficiency"
830    );
831    const headerl = headerFunction(
832        L,
833        "32",
834        "60",
835        "20",
836        "40",
837        "Surveyor's declaration"
838    );
839    const headerFinal = headerFunction(
840        "",
841        "",
842        "90",
843        "20",
844        "40",
845        "What to do now"
846    );
847    const headerFinal1 = headerFunction(
848        "",
849        "",
850        "90",
851        "20",
852        "40",
853        "Typical house diagram"
854    );
855    console.log("third Page");
856    // Cover Page
857
858    let content1 = await pdfCompile23("homebuildercover", jsonValues, addr);
859    await page.setContent(content1);
860    await page.emulateMediaType("screen");
861    const h1 = await page.pdf({
862        // path: 'Survey.pdf',
863        printBackground: true,
864        format: "A4",
865    });
866    // Survey B
867    content1 = await pdfCompile23("surveyB", jsonValues);
868    await page.setContent(content1);
869    await page.emulateMediaType("screen");
870    const h2 = await page.pdf({
871        // path: 'surveyB.pdf',
872        printBackground: true,
873        format: "A4",
874        displayHeaderFooter: true,
875        headerTemplate: headerb,
876        footerTemplate: footeradr,
877        margin: {
878            top: "100px",
879            bottom: "128px",
880            right: "30px",
881            left: "25px",
882        },
883    });
884    // Survey C
885    content1 = await pdfCompile23("surveyC", jsonValues);
886    await page.setContent(content1);
887    await page.emulateMediaType("screen");
888    const h3 = await page.pdf({
889        // path: 'surveyC.pdf',
890        printBackground: true,
891        format: "A4",
892        displayHeaderFooter: true,
893        headerTemplate: headerC,
894        footerTemplate: footeradr,
895        margin: {
896            top: "125px",
897            bottom: "128px",
898            right: "30px",
899            left: "25px",
900        },
901    });
902    // Survey D
903    content1 = await pdfCompile23("surveyD", jsonValues);
904    await page.setContent(content1);
905    await page.emulateMediaType("screen");
906    const h4 = await page.pdf({
907        // path: 'surveyD.pdf',
908        printBackground: true,
909        format: "A4",
910        displayHeaderFooter: true,
911        headerTemplate: headerd,
912        footerTemplate: footeradr,
913        margin: {
914            top: "120px",
915            bottom: "128px",
916            right: "30px",
917            left: "25px",
918        },
919    });
920    // Survey E
921    content1 = await pdfCompile23("surveyE", jsonValues);
922    await page.setContent(content1);
923    await page.emulateMediaType("screen");
924    const h5 = await page.pdf({
925        // path: 'surveyE.pdf',
926        printBackground: true,
927        format: "A4",
928        displayHeaderFooter: true,
929        headerTemplate: headere,
930        footerTemplate: footeradr,
931        margin: {
932            top: "120px",
933            bottom: "128px",
934            right: "30px",
935            left: "25px",
936        },
937    });
938    // Survey F
939    content1 = await pdfCompile23("surveyF", jsonValues);
940    await page.setContent(content1);
941    await page.emulateMediaType("screen");
942    const h6 = await page.pdf({
943        // path: 'surveyF.pdf',
944        printBackground: true,
945        format: "A4",
946        displayHeaderFooter: true,
947        headerTemplate: headerf,
948        footerTemplate: footeradr,
949        margin: {
950            top: "120px",
951            bottom: "128px",
952            right: "30px",
953            left: "25px",
954        },
955    });
956    // Survey G
957    content1 = await pdfCompile23("surveyG", jsonValues);
958    await page.setContent(content1);
959    await page.emulateMediaType("screen");
960    const h7 = await page.pdf({
961        // path: 'surveyG.pdf',
962        printBackground: true,
963        format: "A4",
964        displayHeaderFooter: true,
965        headerTemplate: headerg,
966        footerTemplate: footeradr,
967        margin: {
968            top: "120px",
969            bottom: "128px",
970            right: "30px",
971            left: "25px",
972        },
973    });
974    // Survey H
975    content1 = await pdfCompile23("surveyH", jsonValues);
976    await page.setContent(content1);
977    await page.emulateMediaType("screen");
978    const h8 = await page.pdf({
979        // path: 'surveyH.pdf',
980        printBackground: true,
981        format: "A4",
982        displayHeaderFooter: true,
983        headerTemplate: headerh,
984        footerTemplate: footeradr,
985        margin: {
986            top: "120px",
987            bottom: "128px",
988            right: "30px",
989            left: "25px",
990        },
991    });
992    // Survey I
993    content1 = await pdfCompile23("surveyI", jsonValues);
994    await page.setContent(content1);
995    await page.emulateMediaType("screen");
996    const h9 = await page.pdf({
997        // path: 'surveyI.pdf',
998        printBackground: true,
999        format: "A4",
1000        displayHeaderFooter: true,
1001        headerTemplate: headeri,
1002        footerTemplate: footeradr,
1003        margin: {
1004            top: "120px",
1005            bottom: "128px",
1006            right: "30px",
1007            left: "25px",
1008        },
1009    });
1010    // Survey J
1011    content1 = await pdfCompile23("surveyJ", jsonValues);
1012    await page.setContent(content1);
1013    await page.emulateMediaType("screen");
1014    const h10 = await page.pdf({
1015        // path: 'surveyJ.pdf',
1016        printBackground: true,
1017        format: "A4",
1018        displayHeaderFooter: true,
1019        headerTemplate: headerj,
1020        footerTemplate: footeradr,
1021        margin: {
1022            top: "120px",
1023            bottom: "128px",
1024            right: "30px",
1025            left: "25px",
1026        },
1027    });
1028    // Survey K
1029    content1 = await pdfCompile23("surveyK", jsonValues);
1030    await page.setContent(content1);
1031    await page.emulateMediaType("screen");
1032    const h11 = await page.pdf({
1033        // path: 'surveyK.pdf',
1034        printBackground: true,
1035        format: "A4",
1036        displayHeaderFooter: true,
1037        headerTemplate: headerk,
1038        footerTemplate: footeradr,
1039        margin: {
1040            top: "120px",
1041            bottom: "128px",
1042            right: "30px",
1043            left: "25px",
1044        },
1045    });
1046    // Survey L
1047    content1 = await pdfCompile23("surveyL", jsonValues);
1048    await page.setContent(content1);
1049    await page.emulateMediaType("screen");
1050    const h12 = await page.pdf({
1051        // path: 'surveyL.pdf',
1052        printBackground: true,
1053        format: "A4",
1054        displayHeaderFooter: true,
1055        headerTemplate: headerl,
1056        footerTemplate: footeradr,
1057        margin: {
1058            top: "120px",
1059            bottom: "128px",
1060            right: "30px",
1061            left: "25px",
1062        },
1063    });
1064    // What to do now page
1065    content1 = await pdfCompile23("homeFinal", jsonValues);
1066    await page.setContent(content1);
1067    await page.emulateMediaType("screen");
1068    const h13 = await page.pdf({
1069        // path: 'homeFinal.pdf',
1070        printBackground: true,
1071        format: "A4",
1072        displayHeaderFooter: true,
1073        headerTemplate: headerFinal,
1074        footerTemplate: footeradr,
1075        margin: {
1076            top: "105px",
1077            bottom: "128px",
1078            right: "30px",
1079            left: "25px",
1080        },
1081    });
1082    // Last Page
1083    content1 = await pdfCompile23("homeFinal1", jsonValues);
1084    await page.setContent(content1);
1085    await page.emulateMediaType("screen");
1086    const h14 = await page.pdf({
1087        // path: 'homeFinal.pdf',
1088        printBackground: true,
1089        format: "A4",
1090        displayHeaderFooter: true,
1091        headerTemplate: headerFinal1,
1092        footerTemplate: footeradr,
1093        margin: {
1094            top: "105px",
1095            bottom: "128px",
1096            right: "30px",
1097            left: "25px",
1098        },
1099    });
1100    await browser.close();
1101    // Merge PDF's Using Buffer
1102    const combinePDFBuffers = async (array) => {
1103        var outStream = new memoryStreams.WritableStream();
1104
1105        try {
1106            var h1 = new hummus.PDFRStreamForBuffer(array[0]);
1107            var pdfWriter = hummus.createWriterToModify(
1108                h1,
1109                new hummus.PDFStreamForResponse(outStream)
1110            );
1111            array.shift();
1112            array.forEach((a1) => {
1113                var a1 = new hummus.PDFRStreamForBuffer(a1);
1114                pdfWriter.appendPDFPagesFromPDF(a1);
1115            });
1116            pdfWriter.end();
1117            var newBuffer = await outStream.toBuffer();
1118            outStream.end();
1119            return newBuffer;
1120        } catch (e) {
1121            outStream.end();
1122            console.log("Error during PDF combination: " + e.message);
1123        }
1124    };
1125    var result = await combinePDFBuffers([
1126        h1,
1127        h2,
1128        h3,
1129        h4,
1130        h5,
1131        h6,
1132        h7,
1133        h8,
1134        h9,
1135        h10,
1136        h11,
1137        h12,
1138        h13,
1139        h14,
1140    ]);
1141    return result;
1142};
1143
1144
1145
1146
1147
1148export {
1149    pdf1Main,
1150    pdf2Main,
1151    pdf3Main
1152}
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 Puppeteer 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)