Skip to content

Instantly share code, notes, and snippets.

@mstahv
Created August 30, 2023 05:33
Show Gist options
  • Save mstahv/dcf762e39877c4e7d9a564bcb7684a85 to your computer and use it in GitHub Desktop.
Save mstahv/dcf762e39877c4e7d9a564bcb7684a85 to your computer and use it in GitHub Desktop.
Example how to generate Barcodes in Vaadin apps
package org.example.views;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.EAN13Writer;
import com.vaadin.flow.component.html.Image;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.AbstractStreamResource;
import com.vaadin.flow.server.StreamResource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@Route
public class BarcodeView extends VerticalLayout {
public BarcodeView() {
String barcodeText = "123456789012";
Image barcode = new Image();
barcode.setSrc(asStreamResource(generateEAN13BarcodeImage(barcodeText)));
add(barcode);
// Barcode images are typically small
// & no need for caching, using as data URL is fine as well
Image asDataUrl = new Image();
asDataUrl.setSrc(toDataUrl(generateEAN13BarcodeImage(barcodeText)));
add(asDataUrl);
}
private AbstractStreamResource asStreamResource(BufferedImage bufferedImage) {
return new StreamResource("barcode.png", (output, session) -> {
try {
ImageIO.write(bufferedImage, "png", output);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
public static final int BARCODE_W = 300;
public static final int BARCODE_H = 50;
public static BufferedImage generateEAN13BarcodeImage(String barcodeText) {
EAN13Writer barcodeWriter = new EAN13Writer();
BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.EAN_13, BARCODE_W, BARCODE_H);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
public String toDataUrl(BufferedImage image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(image, "png", baos);
return "data:image/png;base64," + jakarta.xml.bind.DatatypeConverter.printBase64Binary(baos.toByteArray());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment