Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate pdf with barcode in Node.js

I am using https://github.com/devongovett/pdfkit to generate PDF files which I can do simply with something like

app.get('/get-pdf', (req, res) => {
  const doc = new PDFDocument();
  const filename = 'my_pdf.pdf';

  res.setHeader('Content-disposition', 'attachment; filename="' + filename + '"');
  res.setHeader('Content-type', 'application/pdf');

  const content = "Some content";

  doc.y = 300;
  doc.text(content, 50, 50);
  doc.pipe(res);
  doc.end();
});

But I also want to generate an UPC-A barcode:

enter image description here

I have found the library https://github.com/lindell/JsBarcode which can generate such barcode from just the 12-digit code. However, it seems the library is mainly used in the client.

I want to generate a PDF with such barcode, but I don't know how to do it or if JsBarcode isn't too complex for just this single type of barcode.

Edit

As suggested in the comments, I did try to generate a the barcode with the UPC-A font:

app.get('/get-pdf', (req, res) => {
  const doc = new PDFDocument();
  const filename = 'my_pdf.pdf';

  res.setHeader('Content-disposition', 'attachment; filename="' + filename + '"');
  res.setHeader('Content-type', 'application/pdf');

  doc.font('/fonts/UPC-A.ttf').fontSize(50).text('012345678905');
  doc.pipe(res);
  doc.end();
});

from which I get

enter image description here

which does look good, but it doesn't look exactly like common UPC-A barcodes.

I used the font at http://www.fontpalace.com/font-download/UPC-A/.

like image 413
Jamgreen Avatar asked Nov 08 '22 00:11

Jamgreen


2 Answers

Download ttf font file for barcode from google font : https://fonts.google.com/?query=barcode (based on your requirements)

in my case i only want barcode without text , so im using https://fonts.google.com/specimen/Libre+Barcode+39

put this ttf font file in side public/fonts folder

  doc.font(__dirname+ "/../../public/fonts/LibreBarcode39-Regular.ttf").fontSize(20).text(012345678905);

it will generate below barcode :

enter image description here

if you want to use barcode with text then use this font : https://fonts.google.com/specimen/Libre+Barcode+39+Text

like image 183
Saurabh Mistry Avatar answered Nov 14 '22 21:11

Saurabh Mistry


I used JSBarcode and Canvas to generate Barcode within pdf.

You need to install JSBarcode for this:

npm install jsbarcode

Code to generate barcode inside PDF:

var canvas = document.createElement("canvas");
JsBarcode(canvas, "3000001", {
    format: "ean8", height: 20,
    displayValue: false
});
doc.image(canvas.toDataURL(), 10, 10, height:30, width:130);
like image 41
Darshan Jain Avatar answered Nov 14 '22 21:11

Darshan Jain