Answer the question
In order to leave comments, you need to log in
How to create a 2D barcode as a vector image?
I'm generating 2D barcodes using the iText API, but they end up as bitmaps in the PDF document, and the quality of the barcode degrades when printed on low resolution printers. As a result, these barcodes cannot be scanned. Here is our code:
BarcodePDF417 pdf417 = new BarcodePDF417();
String text = "BarcodePDF417 barcode";
pdf417.setText(text);
Image img = pdf417.getImage();
document.add(img);
placeBarcode()
to create a vector image. We tried to use it like this:Rectangle pageSize = new Rectangle(w * 72, h * 72);
Document doc = new Document(pageSize, 1f, 1f, 1f, 1f);
PdfWriter writer = PdfWriter.getInstance(doc, getOutputStream());
doc.open();
PdfContentByte cb = writer.getDirectContent();
BarcodePDF417 pf = new BarcodePDF417();
pf.setText("BarcodePDF417 barcode");
Rectangle rc = pf.getBarcodeSize();
pf.placeBarcode(cb, BaseColor.BLACK, rc.getHeight(), rc.getWidth());
doc.close();
Answer the question
In order to leave comments, you need to log in
See the BarcodePlacement example. Here we generate three PDF417 barcodes:
Image img = createBarcode(1, 1, pdfDoc);
doc.add(new Paragraph(String.format("This barcode measures %s by %s user units",
img.getImageScaledWidth(), img.getImageScaledHeight())));
doc.add(img);
img = createBarcode(3, 3, pdfDoc);
doc.add(new Paragraph(String.format("This barcode measures %s by %s user units",
img.getImageScaledWidth(), img.getImageScaledHeight())));
doc.add(img);
img = createBarcode(3, 1, pdfDoc);
doc.add(new Paragraph(String.format("This barcode measures %s by %s user units",
img.getImageScaledWidth(), img.getImageScaledHeight())));
doc.add(img);
Image
should not confuse you. If you look at the method createBarcode(),
you will see what Image
is actually a vector image:public Image createBarcode(float mw, float mh, PdfDocument pdfDoc) {
BarcodePDF417 barcode = new BarcodePDF417();
barcode.setCode("BarcodePDF417 barcode");
return new Image(barcode.createFormXObject(Color.BLACK, pdfDoc)).scale(mw, mh);
}
scale()
determine the height and width of the small rectangles. On the inside of the barcode, you can see the following: Rectangle size = barcode.getBarcodeSize();
float width = mw * size.getWidth();
float height = mh * size.getHeight();
mw
and are mh
equal to 1
. PdfFormXObject
and move it to Image
. I can then add Image
to the document just like any other image. The main difference between this image and the usual ones is that it is vector.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question