Generate a QR code in Java using a barcode generator library

QR codes have become an integral part of modern digital interactions, enabling seamless data sharing through scannable patterns. If you’re looking to generate QR codes in Java, the Spire.Barcode for Java library offers a robust, user-friendly solution.

This comprehensive guide will walk you through every aspect of creating QR code in Java, including setup, basic QR code generation, logo integration, advanced customization, and industry best practices.


Java Barcode Generator Library

Spire.Barcode for Java is a lightweight, high-performance library designed to generate and read 1D and 2D barcodes, including QR codes, Data Matrix, Code 128, and more. It stands out for its:

  • Ease of use: Minimal code required to generate barcodes.
  • Customization options: Adjust size, color, error correction, and add logos.
  • Compatibility: Supports Java SE 6.0 and above, and integrates with popular IDEs like IntelliJ and Eclipse.
  • Output flexibility: Export QR codes to common image formats (PNG, JPG, BMP, etc.).

Spire.Barcode simplifies QR code generation with pre-built classes for configuration and rendering. Download it to manually import or add it to your project using Maven:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.barcode</artifactId>
        <version>5.2.0</version>
    </dependency>
</dependencies>

Tip: Request a free trial license here to remove evaluation message and watermarks.

You can also use the Free Version to process barcodes:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.barcode.free</artifactId>
    <version>5.2.1</version>
</dependency>

How to Generate a QR Code in Java

Creating a standard QR code with Spire.Barcode for Java involves just a few steps. This example generates a QR code that encodes a URL and saves it as a PNG image.

Key Components:

  • BarcodeSettings: Configures all properties of the QR code.
  • setType(): Specifies the QR code type (other types like Code 128 are also supported).
  • setData(): Defines the content to encode (URL, text, numbers, etc.).
  • setX(): Sets the width of each "module" (the tiny squares in the QR code).
  • setQRCodeECL(): Defines error correction level.
  • generateImage(): Uses the settings to render the QR code as a BufferedImage.
  • ImageIO.write(): Saves the image to a file (PNG, JPG, or other formats).

Java code to create a QR code:

import com.spire.barcode.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class GenerateQRcode {
    public static void main(String[] args) throws IOException {

        // Create a BarcodeSettings object
        BarcodeSettings settings = new BarcodeSettings();

        // Set the barcode type to QR Code
        settings.setType(BarCodeType.QR_Code);

        // Set the QR code data 
        settings.setData("https://www.e-iceblue.com/");


        // Set to not display the encoded text (the URL)
        settings.setShowText(false);

        // Set width of the barcode module
        settings.setX(2);

        // Set the error correction level
        settings.setQRCodeECL(QRCodeECL.M);

        // Set the data mode
        settings.setQRCodeDataMode(QRCodeDataMode.Auto);

        // Create BarCodeGenerator object based on settings
        BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);

        // Generates QR code as a BufferedImage (in-memory image object)
        BufferedImage bufferedImage = barCodeGenerator.generateImage();

        // Save the generated QR code image in PNG format
        ImageIO.write(bufferedImage,"png",new File("QR_Code.png"));

    }
}

Output: A basic QR code image in PNG format. When scanned, the user will be directed to the specified URL address.

Generate a simple QR code using Java

Integrate with the Spire.PDF for Java library to add the QR code image to a PDF document.

Generate a QR Code with a Logo in Java

Adding a logo to a QR code enhances brand visibility while maintaining scannability. Spire.Barcode for Java simplifies this by allowing you to overlay an image onto the QR code via the setQRCodeLogoImage() method.​

Key Considerations:​

  • Use a small logo (10-20% of QR code size) to avoid disrupting data patterns.​
  • Ensure high contrast between the logo and QR code background.

Java code to generate a QR code with embedded logo:

import com.spire.barcode.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class QRcodeWithLogo {
    public static void main(String[] args) throws IOException {

        // Create a BarcodeSettings object
        BarcodeSettings settings = new BarcodeSettings();

        // Set the barcode type to QR Code
        settings.setType(BarCodeType.QR_Code);

        // Set the QR code data (URL, text, numbers, etc.)
        settings.setData("https://www.e-iceblue.com/");


        // Set to not display the encoded text (the URL)
        settings.setShowText(false);

        // Set width of the barcode module
        settings.setX(3);

        // Set the error correction level
        settings.setQRCodeECL(QRCodeECL.H);

        // Set the data mode
        settings.setQRCodeDataMode(QRCodeDataMode.Auto);

        // Load an image and set it as the logo image for the QR code
        BufferedImage image = ImageIO.read(new File("logo.png"));
        settings.setQRCodeLogoImage(image);

        // Create BarCodeGenerator object based on settings
        BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);

        // Generates QR code as a BufferedImage (in-memory image object)
        BufferedImage bufferedImage = barCodeGenerator.generateImage();

        // Save the generated QR code image in PNG format
        ImageIO.write(bufferedImage,"png",new File("QrCodeWithLogo.png"));

    }
}

Output: A PNG image file containing a scannable QR code with a centered logo.

Generate a QR code with logo using Java

Need to scan the QR code in Java? Refer to: How to Read Barcodes in Java Using Spire.Bacode


Customize QR Code Options

Spire.Barcode for Java lets you tailor QR codes to match your design requirements. Below are key customization options:

1. Add Display Text (Top/Bottom Labels)

Add descriptive text above or below the QR code and set its formatting (font, color, alignment).

// Enable top and bottom text
settings.setShowTopText(true);
settings.isShowBottomText(true);

// Set text content
settings.setTopText("Scan to Visit Our Site");
settings.setBottomText("Example Corp © 2025");

// Customize text appearance
settings.setTopTextFont("Arial", 14.0f);
settings.setTopTextColor(Color.BLUE);
settings.setTopTextMargin(1.0f);
settings.setBottomTextFont("Calibri", 12.0f, FontStyle.Italic);
settings.setBottomTextColor(Color.GRAY);

// Align text (Near, Center, Far)
settings.setTopTextAligment(StringAlignment.Center);
settings.setBottomTextAlignment(StringAlignment.Far);

Add top and bottom text to a QR code

2. Customize Borders & Quiet Zones

The "quiet zone" is a blank (usually white) area surrounding the QR code (and its border). It’s critical for scanners to recognize where the QR code starts and ends.

Spire.Barcode for Java allows you to set both the visible border and quiet zone:

// Enable border
settings.hasBorder(true);

// Set border properties
settings.setBorderColor(Color.BLUE); // Border color
settings.setBorderWidth(1); // Border thickness
settings.setBorderDashStyle(3); // Dashed border (options: Solid, Dash, Dot, etc.)

// Set border margins
// These margins create the "quiet zone" around the QR code
settings.setLeftMargin(8);
settings.setRightMargin(8);
settings.setTopMargin(8);
settings.setBottomMargin(8);

Set border and quiet zone for a QR code

3. Change Colors

Modify the QR code’s foreground (data) and background colors to match your brand:

// Set foreground color (black by default)
settings.setForeColor(Color.GRAY);
// Set background color (white by default)
settings.setBackColor(new Color(250, 243, 202));

Set foreground and background colors for a QR code


Best Practices for QR Code Generation

Follow these guidelines for professional QR implementations:

  1. Error Correction Level: Choose wisely:
    • L (Low): 7% data recovery
    • M (Medium): 15% recovery
    • Q (Quartile): 25% recovery
    • H (High): 30% recovery (best for logos)
  2. Optimal Size: Minimum 22 cm (0.8x0.8 in) for print, 200200 px for digital
  3. Contrast: Ensure high contrast between code and background
  4. Test Scannability: Always verify your QR codes with multiple devices/ scanner apps

Conclusion

Generating QR codes in Java is straightforward with libraries like Spire.Barcode. Whether you need a basic QR code encoding text/URL, a branded code with a logo, or a fully customized design, this library provides the tools to achieve it efficiently. By following the examples and best practices outlined in this guide, you’ll be able to integrate professional-grade QR codes into your Java applications, enhancing user experience and enabling seamless data sharing.

With Spire.XLS for .NET, we could easily add different kinds of charts to Excel worksheet, such as Pie Chart, Column Chart, bar chart, line chart, radar chart, Doughnut chart, pyramid chart, etc. In this article, we'll show you how to remove chart from Excel worksheet by using Spire.XLS.

Below is a sample document which contains a chart and table from the Excel worksheet, then we'll remove the chart from the slide.

How to remove chart from Excel worksheet in C#, VB.NET

C# Code Snippet of how to remove the chart from Excel:

Step 1: Create an instance of Excel workbook and load the document from file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

Step 2: Get the first worksheet from the workbook.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Get the first chart from the first worksheet.

IChartShape chart = sheet.Charts[0];

Step 4: Remove the chart.

chart.Remove();

Step 5: Save the document to file.

workbook.SaveToFile("RemoveChart.xlsx");

Effective screenshot:

How to remove chart from Excel worksheet in C#, VB.NET

Full code:

[C#]
using Spire.Xls;
using Spire.Xls.Core;
namespace RemoveChart
{

    class Program
    {

        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");
            Worksheet sheet = workbook.Worksheets[0];
            IChartShape chart = sheet.Charts[0];
            chart.Remove();
            workbook.SaveToFile("RemoveChart.xlsx");

        }

    }
}
[VB.NET]
Imports Spire.Xls
Imports Spire.Xls.Core
Namespace RemoveChart

	Class Program

		Private Shared Sub Main(args As String())
			Dim workbook As New Workbook()
			workbook.LoadFromFile("Sample.xlsx")
			Dim sheet As Worksheet = workbook.Worksheets(0)
			Dim chart As IChartShape = sheet.Charts(0)
			chart.Remove()
			workbook.SaveToFile("RemoveChart.xlsx")

		End Sub

	End Class
End Namespace

In Word, textbox can contain multiple elements such as text, image and table. This article demonstrates how to insert table into word textbox, and read and delete existing table from word textbox using Spire.Doc.

Insert table

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace InsertTable
{
    class Program
    {

        static void Main(string[] args)
        {

            //Create a Document instance
            Document document = new Document();

            //Add a section
            Section section = document.AddSection();
            //Add a paragraph to the section
            Paragraph paragraph = section.AddParagraph();

            //Add textbox to the paragraph
            TextBox textbox = paragraph.AppendTextBox(300, 100);

            //Add text to textbox
            Paragraph textboxParagraph = textbox.Body.AddParagraph();
            TextRange textboxRange = textboxParagraph.AppendText("Table 1");
            textboxRange.CharacterFormat.FontName = "Arial";

            //Insert table to textbox
            Table table = textbox.Body.AddTable(true);
            //Specify the number of rows and columns of the table
            table.ResetCells(4, 4);

            string[,] data = new string[,]  
{  
{"Name","Age","Gender","ID" },  
{"John","28","Male","0023" },  
{"Steve","30","Male","0024" },  
{"Lucy","26","female","0025" }  
};

            //Add data to table 
            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    TextRange tableRange = table[i, j].AddParagraph().AppendText(data[i, j]);
                    tableRange.CharacterFormat.FontName = "Arial";
                }
            }

            //Apply style to table
            table.ApplyStyle(DefaultTableStyle.LightGridAccent3);

            //Save the document
            document.SaveToFile("Output.docx", FileFormat.Docx2013);

        }
    }
}

Insert, Read and Delete Table from Word Textbox in C#

Read table

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.IO;
using System.Text;
namespace ReadTable
{
    class Program
    {

        static void Main(string[] args)
        {
            //Create a Document instance and load the word document
            Document document = new Document("Output.docx");

            //Get the first textbox
            TextBox textbox = document.TextBoxes[0];

            //Get the first table in the textbox
            Table table = textbox.Body.Tables[0] as Table;

            StringBuilder sb = new StringBuilder();

            //Loop through the paragraphs of the table and extract text to a .txt file
            foreach (TableRow row in table.Rows)
            {
                foreach (TableCell cell in row.Cells)
                {
                    foreach (Paragraph paragraph in cell.Paragraphs)
                    {
                        sb.AppendLine(paragraph.Text);
                    }
                }
            }
            File.WriteAllText("text.txt", sb.ToString());

        }
    }
}

Insert, Read and Delete Table from Word Textbox in C#

Delete table

using Spire.Doc;
using Spire.Doc.Fields;
namespace DeleteTable
{
    class Program
    {

        static void Main(string[] args)
        {
            //Create a Document instance and load the word document
            Document document = new Document("Output.docx");

            //Get the first textbox
            TextBox textbox = document.TextBoxes[0];

            //Remove the first table from the textbox
            textbox.Body.Tables.RemoveAt(0);

            //Save the document
            document.SaveToFile("RemoveTable.docx", FileFormat.Docx2013);


        }
    }
}

Insert, Read and Delete Table from Word Textbox in C#

page 198