How to use createPDFStream 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.

index.js

Source: index.js Github

copy
1const fs = require('fs-extra');
2const path = require('path');
3const fabric = require('fabric').fabric;
4const { createCanvas, loadImage } = require('canvas');
5
6const filePath = path.resolve(__dirname, 'photo');
7
8// const jsDomUtils = require('jsdom/lib/jsdom/living/generated/utils');
9// const pdfCanvas = createCanvas(200, 200, 'pdf');
10// const el = fabric.document.createElement('canvas');
11
12const can = new fabric.StaticCanvas(null, {
13	height: 200,
14	width: 200
15});
16
17const rect = new fabric.Rect({
18	top : 100,
19	left : 100,
20	width : 60,
21	height : 70,
22	fill : 'red'
23});
24
25const text = new fabric.Text('Hello!', {
26	fontFamily: 'Impact',
27	fontSize: 10,
28	left: 0.8 * can.getWidth() / 2,
29	top: 0.8 * can.getHeight() / 2
30});
31
32can.add(rect);
33can.add(text);
34
35// console.log(can.toDataURL());
36
37can.renderAll();
38
39const out = fs.createWriteStream(filePath + '.png');
40const stream = can.createPNGStream();
41stream.pipe(out);
42out.on('close', () => console.log('PNG saved!'));
43
44// const pdfOut = fs.createWriteStream(filePath + '.pdf');
45// const pdfStream = fabric.util.getNodeCanvas(can.lowerCanvasEl).createPDFStream();
46// pdfStream.pipe(pdfOut);
47// pdfOut.on('close', () => console.log('PDF saved!'));
48
49// const el = fabric.util.getNodeCanvas(can.toCanvasElement());
50// const pdfOut = fs.createWriteStream(filePath + '.pdf');
51// const pdfStream = el.createPDFStream();
52// pdfStream.pipe(pdfOut);
53// pdfOut.on('close', () => console.log('PDF saved!'));
54
55// const ctxFab = can.getContext('2d');
56const pdfCanvas = createCanvas(200, 200, 'pdf');
57const ctx = pdfCanvas.getContext('2d');
58
59// ctx.putImageData(
60// 	ctxFab.getImageData(0, 0, ctxFab.canvas.width, ctxFab.canvas.height),
61// 0, 0);
62
63loadImage(can.toDataURL()).then(img => {
64	ctx.drawImage(img, 0, 0);
65
66	const pdfOut = fs.createWriteStream(filePath + '.pdf');
67	const pdfStream = pdfCanvas.createPDFStream();
68	pdfStream.pipe(pdfOut);
69	pdfOut.on('close', () => console.log('PDF saved!'));
70});
Full Screen

createInvoiceUtil.js

Source: createInvoiceUtil.js Github

copy
1const fs = require("fs");
2const PDFDocument = require("pdfkit");
3const logger = require("./logger");
4const path = require("path");
5const filepath = "invoices.pdf";
6function createInvoiceUtil(orderDetails, path) {
7  logger.info("CREATE Invoice Start");
8  let doc = new PDFDocument({ size: "A4", margin: 50 });
9  doc.registerFont("Baloo", `${__dirname}/fonts/BalooTammudu2-Bold.ttf`);
10  doc.registerFont(
11    "Baloo-light",
12    `${__dirname}/fonts/BalooTammudu2-SemiBold.ttf`
13  );
14  let createPDFStream = fs.createWriteStream(path);
15  doc.pipe(createPDFStream);
16  //BalooTammudu2-Regular.ttf
17  generateHeader(doc);
18  generateCustomerInformation(doc, orderDetails);
19  generateAddress(doc, orderDetails);
20  generateInvoiceTable(doc, orderDetails);
21  generateNote(doc);
22  generateFooter(doc);
23  doc.end();
24  createPDFStream.on("finish", () => {
25    logger.info("Finished: writing close stream");
26  });
27}
28
29function generateHeader(doc) {
30  doc
31    .font("Baloo")
32    .image(`${__dirname}/invoice_logo.jpg`, 50, 45, { width: 50 })
33    .fillColor("#444444")
34    .fontSize(20)
35    .text("MeraBazzar", 110, 57)
36    .fontSize(10)
37    .text("GSTN: HADGHDFA745634GDF", 390, 120)
38    .fontSize(18)
39    .text("MeraBazzar Pvt LTD.", 200, 50, { align: "right" })
40    .text("Devghar", 200, 65, { align: "right" })
41    .text("Jharkhand", 200, 80, { align: "right" })
42    .moveDown();
43}
44
45function generateCustomerInformation(doc, orderDetails) {
46  doc.fillColor("#444444").fontSize(20).text("Invoice", 50, 160);
47  generateHr(doc, 190);
48
49  const customerInformationTop = 200;
50
51  doc
52    .fontSize(10)
53    .font("Baloo")
54    .text("Order Id:", 50, customerInformationTop)
55    .text(orderDetails.orderId, 150, customerInformationTop)
56
57    .text("Invoice Number:", 50, customerInformationTop + 15)
58    .font("Baloo")
59    .text(orderDetails._id, 150, customerInformationTop + 15)
60
61    .font("Baloo")
62    .text("Order Date:", 50, customerInformationTop + 30)
63    .text(
64      formatDate(new Date(orderDetails.orderDate)),
65      150,
66      customerInformationTop + 30
67    )
68    .text("Balance Due:", 50, customerInformationTop + 45)
69    .font("Baloo")
70    .text(
71      `${orderDetails.totalPrice} \u20B9  `,
72      150,
73      customerInformationTop + 45
74    )
75
76    .font("Baloo")
77    .text("Name:", 350, customerInformationTop)
78    .text(
79      orderDetails.userInfo === undefined
80        ? "Customer IMP"
81        : orderDetails.userInfo.name,
82      390,
83      customerInformationTop
84    )
85    .moveDown();
86  generateHr(doc, 270);
87}
88function generateAddress(doc, orderDetails) {
89  const invoiceAddressTop = 290;
90  doc
91    .fontSize(10)
92    .text("Address:", 50, invoiceAddressTop)
93    .font("Baloo")
94    .text(orderDetails.address, 150, invoiceAddressTop);
95  generateHr(doc, 350);
96}
97function generateInvoiceTable(doc, orderDetails) {
98  console.log("Generate Invoice table");
99
100  let i;
101  const invoiceTableTop = 400;
102
103  doc.font("Baloo");
104  generateTableRow(
105    doc,
106    invoiceTableTop,
107    "Item",
108    "",
109    "Unit Cost",
110    "Quantity",
111    "Total"
112  );
113  generateHr(doc, invoiceTableTop + 20);
114  doc.font("Helvetica");
115
116  for (i = 0; i < orderDetails.cart.length; i++) {
117    const item = orderDetails.cart[i].item;
118    const position = invoiceTableTop + (i + 1) * 30;
119    generateTableRow(
120      doc,
121      position,
122      item.name,
123      "",
124      item.price - item.discount,
125      orderDetails.cart[i].addedQuantity,
126      item.price - item.discount * orderDetails.cart[i].addedQuantity
127    );
128
129    generateHr(doc, position + 20);
130  }
131  // generate charges
132  const chargesPosition = invoiceTableTop + (i + 1) * 30;
133  generateTableRow(
134    doc,
135    chargesPosition,
136    "",
137    "",
138    "Additional Charges",
139    "",
140    orderDetails.charges
141  );
142  // generate discount
143  const discountPosition = invoiceTableTop + (i + 1) * 40;
144  generateTableRow(
145    doc,
146    discountPosition,
147    "",
148    "",
149    "Discount %",
150    "",
151    orderDetails.discount
152  );
153
154  //generate subtotal
155  const subtotalPosition = invoiceTableTop + (i + 1) * 50;
156  generateTableRow(
157    doc,
158    subtotalPosition,
159    "",
160    "",
161    "Subtotal",
162    "",
163    orderDetails.totalPrice
164  );
165}
166// generate footer
167function generateNote(doc) {
168  doc
169    .font("Baloo-light")
170    .fontSize(10)
171    .fillColor("red")
172    .text(
173      "*** This is a system generated invoice no signature required",
174      80,
175      680,
176      {
177        align: "right",
178        width: 500,
179      }
180    );
181}
182function generateFooter(doc) {
183  generateNote(doc);
184  doc
185    .fontSize(10)
186    .fillColor("blue")
187    .text("Thank you for your business.", 80, 550, {
188      align: "right",
189      width: 500,
190    })
191    .text("--   Team Merabazzar.", 70, 560, {
192      align: "right",
193      width: 500,
194    });
195}
196
197function generateTableRow(
198  doc,
199  y,
200  item,
201  description,
202  unitCost,
203  quantity,
204  lineTotal
205) {
206  doc
207    .font("Baloo-light")
208    .fontSize(10)
209    .text(item, 50, y)
210    .text(description, 100, y)
211    .text(`${unitCost} \u20B9`, 280, y, { width: 90, align: "right" })
212    .text(quantity, 370, y, { width: 90, align: "right" })
213    .text(`${lineTotal}\u20B9`, 0, y, { align: "right" });
214}
215
216function generateHr(doc, y) {
217  doc.strokeColor("#aaaaaa").lineWidth(1).moveTo(50, y).lineTo(550, y).stroke();
218}
219
220function formatDate(date) {
221  const day = date.getDate();
222  const month = date.getMonth() + 1;
223  const year = date.getFullYear();
224  return day + "-" + month + "-" + year;
225}
226
227module.exports = {
228  createInvoiceUtil,
229};
230
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)