How to create a QR Code SVG using Zxing and JFreeSVG in Java?

In this article, we will look at how to use the Zxing QR code generation library and JFreeSVG library to create a QR Code SVG image in Java.

QR Code Generation

The below code creates a java.awt.image.BufferedImage object representing QR Code using Zxing library:

public static BufferedImage getQRCode(String targetUrl, int width, 
int height) {
try {
Hashtable<EncodeHintType, Object> hintMap = new Hashtable<>();

QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix byteMatrix = qrCodeWriter.encode(targetUrl,
BarcodeFormat.QR_CODE, width, height, hintMap);
int CrunchifyWidth = byteMatrix.getWidth();

BufferedImage image = new BufferedImage(CrunchifyWidth,
CrunchifyWidth, BufferedImage.TYPE_INT_RGB);

Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth);

for (int i = 0; i < CrunchifyWidth; i++) {
for (int j = 0; j < CrunchifyWidth; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
return image;
} catch (WriterException e) {
throw new RuntimeException("Error getting QR Code");


Conversion to SVG

The below code snippet converts the java.awt.image.BufferedImage object into SVG using JFreeSVG:

public static String getQRCodeSvg(String targetUrl, int width, 
int height, boolean withViewBox){
SVGGraphics2D g2 = new SVGGraphics2D(width, height);
BufferedImage qrCodeImage = getQRCode(targetUrl, width, height);
g2.drawImage(qrCodeImage, 0,0, width, height, null);

ViewBox viewBox = null;
if ( withViewBox ){
viewBox = new ViewBox(0,0,width,height);
return g2.getSVGElement(null, true, viewBox, null, null);

The complete code can be found here.

Categories: Java

Tags: , ,

2 replies

  1. Our present level of A.I. can not truly convert any PNG into SVG format.



  1. How to Create QRCode Using QRGen in Java – Experiences Unlimited

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: