swissqrbill Java Library

repository·master·Indexed 41 days ago

https://github.com/manuelbl/swissqrbill

A Java library for generating and decoding Swiss QR bills in compliance with Swiss Payment Standards 2025. It supports PDF, SVG, and PNG formats and provides integration for Jasper Reports via the QrBillRenderer class. The library includes tools for validating bill data, handling structured addresses, and managing character sets like Extended Latin.

Tokens
3.7K
Snippets
11
Records
15
Agent score
52%

What's inside swissqrbill

  1. Handle structured vs unstructured addresses

    master

    According to the Swiss Payment Standards 2025, banks may only accept bills with structured addresses.

    While the library still supports unstructured (combined) address elements via deprecated methods for backward compatibility, these methods will be removed in version 4.0. It is recommended to use the structured Address object (setting name, street, houseNo, postalCode, town, and countryCode) for all new implementations.

  2. Build and run the Jasper Reports rendering example

    master

    The Jasper Reports rendering example requires Java 17 and Maven. The process involves compiling the .jrxml design files into .jasper files using a Maven plugin before execution.

    To build and run the project, use the following command:

    mvn clean package exec:java

    Note: If using IntelliJ IDEA, you may need to click 'Generate Source and Update Folders For All Projects' in the Maven tool window to ensure the compiled .jasper files are recognized.

    mvn clean package exec:java
  3. Install the Swiss QR Bill generator via Maven or Gradle

    master

    The library is available on Maven Central. Add the following dependency to your project to use the qrbill-generator artifact.

    Maven

    Add this to your pom.xml:

    Gradle

    Add this to your build.gradle:

    <!-- Maven -->
    <dependency>
        <groupId>net.codecrete.qrbill</groupId>
        <artifactId>qrbill-generator</artifactId>
        <version>[3.4.0,3.999999]</version>
    </dependency>
    
    <!-- Gradle -->
    implementation "net.codecrete.qrbill:qrbill-generator:3.4.0+"
  4. Generate a Swiss QR bill

    master

    To generate a QR bill, follow these steps:

    1. Instantiate a Bill object.
    2. Populate the Bill with account details (IBAN), amount, currency, and reference.
    3. Create Address objects for both the creditor and debtor and assign them to the bill.
    4. Configure the output format using BillFormat (e.g., setting GraphicsFormat, OutputSize, and Language).
    5. Call QRBill.generate(bill) to receive the generated content as a byte[].
    package net.codecrete.qrbill.examples;
    
    import net.codecrete.qrbill.generator.Address;
    import net.codecrete.qrbill.generator.Bill;
    import net.codecrete.qrbill.generator.QRBill;
    import net.codecrete.qrbill.generator.BillFormat;
    import net.codecrete.qrbill.generator.GraphicsFormat;
    import net.codecrete.qrbill.generator.OutputSize;
    import net.codecrete.qrbill.generator.Language;
    
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    
    public class QRBillExample {
    
        public static void main(String[] args) {
    
            // Setup bill
            Bill bill = new Bill();
            bill.setAccount("CH4431999123000889012");
            bill.setAmountFromDouble(199.95);
            bill.setCurrency("CHF");
    
            // Set creditor
            Address creditor = new Address();
            creditor.setName("Robert Schneider AG");
            creditor.setStreet("Rue du Lac");
            creditor.setHouseNo("1268/2/22");
            creditor.setPostalCode("2501");
            creditor.setTown("Biel");
            creditor.setCountryCode("CH");
            bill.setCreditor(creditor);
    
            // more bill data
            bill.setReference("210000000003139471430009017");
            bill.setUnstructuredMessage("Abonnement für 2020");
    
            // Set debtor
            Address debtor = new Address();
            debtor.setName("Pia-Maria Rutschmann-Schnyder");
            debtor.setStreet("Grosse Marktgasse");
            debtor.setHouseNo("28");
            debtor.setPostalCode("9400");
            debtor.setTown("Rorschach");
            debtor.setCountryCode("CH");
            bill.setDebtor(debtor);
    
            // Set output format
            BillFormat format = new BillFormat();
            format.setGraphicsFormat(GraphicsFormat.SVG);
            format.setOutputSize(OutputSize.QR_BILL_ONLY);
            format.setLanguage(Language.DE);
            bill.setFormat(format);
    
            // Generate QR bill
            byte[] svg = QRBill.generate(bill);
    
            // Save QR bill
            Path path = Paths.get("qrbill.svg");
            try {
                Files.write(path, svg);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
    
            System.out.println("QR bill saved at " + path.toAbsolutePath());
        }
    }
  5. Use the QrBillRenderer for Jasper Reports

    master

    To integrate Swiss QR bills into Jasper Reports efficiently, use the QrBillRenderer class instead of importing external SVG files. Using QrBillRenderer significantly reduces PDF file size (approximately 12KB per slip compared to 100KB when using SVGs) because it avoids the overhead of converting text into complex vector shapes.

    You can instantiate the renderer in two ways:

    1. Direct Integration: Use the QrBillRenderer(Bill) constructor to create an instance and pass it directly into your Jasper report data source.
    2. Data Source Wrapping: Use QrBillImageDataSource. This class wraps an existing data source and automatically adds a QrBillImage column. It retrieves necessary data (creditor, debtor, amount, etc.) from the wrapped data source using configurable field names.
    // Option 1: Direct constructor
    new QrBillRenderer(billInstance);
    
    // Option 2: Using the wrapper
    new QrBillImageDataSource(existingDataSource);
  6. Configure Jasper Reports for optimized QR Bill PDF output

    master

    To ensure the QrBillRenderer achieves its space-saving benefits and renders fonts correctly, you must apply the following configurations:

    1. Prevent Text-to-Shape Conversion

    Set the following property in your jasperreports.properties file to prevent Jasper Reports from converting text into vector shapes, which bloats PDF size: net.sf.jasperreports.export.pdf.force.svg.shapes=false

    2. Font Configuration

    To ensure bold font faces work and to maintain compatibility with the QR bill specification, configure your fonts (e.g., Liberation Sans). For PDF output, it is recommended to instruct Jasper Reports to replace these with standard PDF fonts like Helvetica and to not embed them. This ensures the PDF remains small and compatible with all viewers.

    net.sf.jasperreports.export.pdf.force.svg.shapes=false
  7. Configure character sets for Swiss Payment Standards 2025

    master

    As of version 3.4, the library defaults to the Extended Latin character set to comply with the Swiss Payment Standards 2025.

    If you need to revert to the older, more restricted Latin-1 Subset character set, use the setCharacterSet method on your Bill object with the SPSCharacterSet.LATIN_1_SUBSET constant.

    Note on Fonts: When using Extended Latin, the library automatically switches from Helvetica to Liberation Sans for PDF output to ensure all characters are supported and embedded.

    bill.setCharacterSet(SPSCharacterSet.LATIN_1_SUBSET);
  8. Generate a Swiss QR Bill using Maven

    master

    This example demonstrates how to use the swissqrbill library within a Maven project to generate a QR bill. It serves as a minimal starting point for integrating the library into a Java application managed by Maven.

    # Basic Code Example using Maven
    
    This minimal code example shows how to generate a QR bill. It uses the Maven build system.
  9. Append a QR bill to an existing PDF file

    master

    You can integrate a generated Swiss QR bill into an existing PDF document using two different approaches:

    1. Append to an existing page: The QR bill is overlaid or added to a page that already contains content. The resulting page will contain both the original content and the QR bill.
    2. Append as a new page: A new page is created at the end of the document specifically for the QR bill. This page will contain only the QR bill and no other content.
  10. Generate a Swiss QR bill using Kotlin

    master

    This example demonstrates the minimal steps required to generate a Swiss QR bill using the Kotlin API provided by the library. It serves as a starting point for integrating Swiss QR bill generation into Kotlin-based applications.

    # Basic Code Example using Kotlin
    
    This minimal code example shows how to generate a QR bill using Kotlin.
  11. Validate Swiss QR bill data with Validator.validate()

    master

    The Validator class provides a static method to validate a Bill object against official Swiss QR bill standards. This process performs two main functions:

    1. Validation: It checks for errors (e.g., invalid IBAN, incorrect currency, out-of-range amounts, or missing mandatory fields) and warnings (e.g., values that were clipped or contained unsupported characters).
    2. Cleaning: It produces a "cleaned" version of the bill (billOut) where whitespace is removed, text is normalized (e.g., uppercase currency), and values are clipped to meet length constraints.

    To use it, pass a Bill instance to Validator.validate(bill). The returned ValidationResult contains both the list of validation messages and the new, cleaned Bill object.

    // Assuming 'bill' is an existing Bill instance
    ValidationResult result = Validator.validate(bill);
    
    if (!result.getMessages().isEmpty()) {
        // Handle errors or warnings
        result.getMessages().forEach(msg -> {
            System.out.println(msg.getType() + ": " + msg.getMessage());
        });
    }
    
    // Use the cleaned bill for generation
    Bill cleanedBill = result.getCleanedBill();