Skip to content

Commit 70cfa00

Browse files
author
agent-aspose-barcode-examples
committed
feat(swiss-qr-code): Add 2 Aspose.BarCode .NET C# examples for Swiss Qr Code — Aspose.BarCode for .NET 26.6.0
1 parent b618675 commit 70cfa00

2 files changed

Lines changed: 121 additions & 102 deletions
Lines changed: 63 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,108 +1,116 @@
1-
// Title: Batch Generation of Swiss QR Code Images from CSV Invoices
2-
// Description: Generates Swiss QR Code barcodes for each invoice listed in a CSV file and saves them as PNG images.
3-
// Category-Description: This example demonstrates batch processing using Aspose.BarCode to create Swiss QR Code (QR‑Bill) images. It utilizes the ComplexBarcodeGenerator and SwissQRCodetext classes to encode creditor, account, amount, and reference data. Typical use cases include automating invoice QR‑Bill creation for Swiss payment standards, where developers need to read data sources (e.g., CSV) and produce barcode images in bulk.
1+
// Title: Generate Swiss QR Code Images from CSV Invoices
2+
// Description: Demonstrates batch creation of Swiss QR Code barcodes for invoice data read from a CSV file and saves them as PNG images.
3+
// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as Swiss QR Bill. It showcases using the SwissQRCodetext class and ComplexBarcodeGenerator to encode payment information into QR codes, a common requirement for financial applications and invoicing systems. Developers often need to automate QR code creation for multiple records, handling CSV input and image output.
44
// Prompt: Create a batch process to generate Swiss QR Code images for invoices listed in a CSV file.
5-
// Tags: swiss qr code, barcode generation, csv processing, aspose.barcode, png output, batch processing
5+
// Tags: swiss qr code, batch processing, png, aspose.barcode, complexbarcodegenerator, csv
66

77
using System;
88
using System.IO;
99
using System.Collections.Generic;
1010
using Aspose.BarCode;
11-
using Aspose.BarCode.Generation;
1211
using Aspose.BarCode.ComplexBarcode;
12+
using Aspose.Drawing;
1313

1414
/// <summary>
15-
/// Demonstrates batch generation of Swiss QR Code images from invoice data stored in a CSV file.
15+
/// Batch processor that reads invoice data from a CSV file and generates Swiss QR Code images.
1616
/// </summary>
1717
class Program
1818
{
1919
/// <summary>
20-
/// Entry point. Reads invoice records, builds Swiss QR codetext, and saves PNG barcode images.
20+
/// Entry point of the application. Reads invoices, creates QR codes, and saves them as PNG files.
2121
/// </summary>
2222
static void Main()
2323
{
24-
// Define the input CSV file path; create a sample file if it does not exist.
25-
string inputCsv = "invoices.csv";
26-
if (!File.Exists(inputCsv))
24+
// Path to the input CSV file containing invoice records
25+
string csvPath = "invoices.csv";
26+
27+
// Directory where generated QR code images will be stored
28+
string outputFolder = "output";
29+
30+
// Ensure the output directory exists; create it if necessary
31+
if (!Directory.Exists(outputFolder))
2732
{
28-
var sampleLines = new List<string>
29-
{
30-
"CreditorName,CountryCode,Account,Amount,Reference",
31-
"John Doe,CH,CH9300762011623852957,199.95,RF18539007547034",
32-
"Acme Corp,CH,CH5604835012345678009,2500.00,RF18000012345678",
33-
"Global Ltd,CH,CH3709000000304442225,123.45,RF19000098765432",
34-
"Tech Solutions,CH,CH6209000000001234567,999.99,RF20000123456789",
35-
"Finance AG,CH,CH9300762011623852957,75.00,RF21000111223344"
36-
};
37-
File.WriteAllLines(inputCsv, sampleLines);
33+
Directory.CreateDirectory(outputFolder);
3834
}
3935

40-
// Ensure the output directory exists for the generated QR images.
41-
string outputDir = "SwissQRImages";
42-
if (!Directory.Exists(outputDir))
36+
// If the CSV file is missing, create a sample file with example invoices
37+
if (!File.Exists(csvPath))
4338
{
44-
Directory.CreateDirectory(outputDir);
39+
var sampleLines = new List<string>
40+
{
41+
"Account,CreditorName,CountryCode,Amount,BillInformation",
42+
"CH9300762011623852957,John Doe,CH,199.95,Invoice 001",
43+
"CH9300762011623852957,Acme Corp,CH,350.00,Invoice 002",
44+
"CH9300762011623852957,Global Ltd,CH,1200.50,Invoice 003"
45+
};
46+
File.WriteAllLines(csvPath, sampleLines);
4547
}
4648

47-
// Read all lines from the CSV file.
48-
string[] allLines = File.ReadAllLines(inputCsv);
49-
if (allLines.Length <= 1)
49+
// Read all lines from the CSV file
50+
string[] lines = File.ReadAllLines(csvPath);
51+
if (lines.Length <= 1)
5052
{
51-
Console.WriteLine("No invoice data found.");
53+
Console.WriteLine("No invoice data found in the CSV file.");
5254
return;
5355
}
5456

55-
// Iterate over each invoice record, skipping the header line.
56-
for (int i = 1; i < allLines.Length; i++)
57+
// Process each invoice line, skipping the header row.
58+
// Limit processing to a maximum of 5 items for safety in this example.
59+
int maxItems = Math.Min(lines.Length - 1, 5);
60+
for (int i = 1; i <= maxItems; i++)
5761
{
58-
string line = allLines[i];
59-
if (string.IsNullOrWhiteSpace(line))
60-
continue; // Skip empty lines.
62+
string line = lines[i];
6163

62-
// Split the CSV line into its constituent fields.
64+
// Simple CSV split (assumes no commas inside fields)
6365
string[] parts = line.Split(',');
66+
67+
// Validate that the line contains all required columns
6468
if (parts.Length < 5)
6569
{
66-
Console.WriteLine($"Skipping malformed line {i + 1}.");
70+
Console.WriteLine($"Skipping line {i + 1}: insufficient columns.");
6771
continue;
6872
}
6973

70-
// Trim and assign each field to a variable.
71-
string creditorName = parts[0].Trim();
72-
string countryCode = parts[1].Trim();
73-
string account = parts[2].Trim();
74-
string amountStr = parts[3].Trim();
75-
string reference = parts[4].Trim();
74+
// Map CSV columns to local variables
75+
string account = parts[0].Trim();
76+
string creditorName = parts[1].Trim();
77+
string countryCode = parts[2].Trim();
7678

77-
// Parse the amount; if invalid, skip this record.
78-
if (!decimal.TryParse(amountStr, out decimal amount))
79+
// Parse the amount; skip the line if parsing fails
80+
if (!decimal.TryParse(parts[3].Trim(), out decimal amount))
7981
{
80-
Console.WriteLine($"Invalid amount on line {i + 1}, skipping.");
82+
Console.WriteLine($"Skipping line {i + 1}: invalid amount.");
8183
continue;
8284
}
8385

84-
// Build the Swiss QR codetext using the parsed data.
86+
string billInfo = parts[4].Trim();
87+
88+
// Build the Swiss QR bill data structure
8589
var swissQr = new SwissQRCodetext();
90+
swissQr.Bill.Account = account;
8691
swissQr.Bill.Creditor.Name = creditorName;
8792
swissQr.Bill.Creditor.CountryCode = countryCode;
88-
swissQr.Bill.Account = account;
8993
swissQr.Bill.Amount = amount;
94+
swissQr.Bill.BillInformation = billInfo;
9095
swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0;
91-
if (!string.IsNullOrEmpty(reference))
92-
swissQr.Bill.Reference = reference; // Optional reference.
9396

94-
// Define the output file name for this invoice's QR code.
95-
string outputFile = Path.Combine(outputDir, $"Invoice_{i}.png");
97+
// Define the output file path for the generated QR code image
98+
string outputPath = Path.Combine(outputFolder, $"invoice_{i}.png");
9699

97-
// Generate the QR code image and save it as PNG.
100+
// Generate and save the QR code image using ComplexBarcodeGenerator
98101
using (var generator = new ComplexBarcodeGenerator(swissQr))
99102
{
100-
// Example: set module size (X dimension) if desired.
101-
generator.Parameters.Barcode.XDimension.Point = 2f;
102-
generator.Save(outputFile, BarCodeImageFormat.Png);
103+
// Set barcode and background colors (optional)
104+
generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
105+
generator.Parameters.BackColor = Aspose.Drawing.Color.White;
106+
107+
// Save the QR code as a PNG file
108+
generator.Save(outputPath);
103109
}
110+
111+
Console.WriteLine($"Generated QR code for invoice {i} at: {outputPath}");
104112
}
105113

106-
Console.WriteLine("Swiss QR code generation completed.");
114+
Console.WriteLine("Batch processing completed.");
107115
}
108116
}
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,81 @@
1+
// Title: Barcode generation with audit logging using Aspose.BarCode
2+
// Description: Demonstrates creating a Code128 barcode image while logging generation parameters and outcomes to a file for audit purposes.
3+
// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to configure barcode settings, save the image, and record detailed audit information. It highlights key API classes such as BarcodeGenerator, BaseEncodeType, and EncodeTypes, which developers commonly use for automated barcode creation, compliance tracking, and troubleshooting in enterprise applications.
4+
// Prompt: Implement logging of barcode generation parameters and outcomes using .NET built‑in logging framework for audit trails.
5+
// Tags: barcode, code128, generation, audit, logging, aspose.barcode, image, .net
6+
17
using System;
28
using System.IO;
3-
using Aspose.BarCode;
49
using Aspose.BarCode.Generation;
510
using Aspose.Drawing;
6-
using Aspose.Drawing.Imaging;
711

12+
/// <summary>
13+
/// Generates a Code128 barcode image and logs the generation process for audit trails.
14+
/// </summary>
815
class Program
916
{
17+
/// <summary>
18+
/// Entry point of the application. Configures barcode parameters, generates the image, and records audit information.
19+
/// </summary>
1020
static void Main()
1121
{
12-
// Prepare output directory
13-
string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "output");
14-
if (!Directory.Exists(outputDir))
22+
// Define the path for the audit log file.
23+
string logFile = "barcode_audit.log";
24+
25+
// Ensure the audit log file exists; create it with a header if it does not.
26+
if (!File.Exists(logFile))
1527
{
16-
Directory.CreateDirectory(outputDir);
28+
File.WriteAllText(logFile, $"Barcode generation audit log - {DateTime.UtcNow:u}{Environment.NewLine}");
1729
}
1830

19-
string imagePath = Path.Combine(outputDir, "barcode.png");
20-
string logPath = Path.Combine(outputDir, "audit.log");
21-
22-
// Start log
23-
File.AppendAllText(logPath, $"--- Barcode generation started at {DateTime.UtcNow:u} ---{Environment.NewLine}");
24-
25-
// Define barcode settings
31+
// Barcode configuration: type, data, and output file.
2632
BaseEncodeType encodeType = EncodeTypes.Code128;
2733
string codeText = "123ABC";
34+
string outputPath = "code128.png";
2835

29-
try
30-
{
31-
using (var generator = new BarcodeGenerator(encodeType, codeText))
32-
{
33-
// Configure generation parameters
34-
generator.Parameters.Barcode.XDimension.Point = 2f;
35-
generator.Parameters.Barcode.BarHeight.Point = 50f;
36-
generator.Parameters.Barcode.FilledBars = false;
37-
generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue;
38-
generator.Parameters.BackColor = Aspose.Drawing.Color.White;
39-
generator.Parameters.AutoSizeMode = AutoSizeMode.None;
40-
generator.Parameters.Resolution = 300f;
36+
// Log the start of the barcode generation process with key parameters.
37+
File.AppendAllText(logFile,
38+
$"[{DateTime.UtcNow:u}] Starting barcode generation. Type: {encodeType.TypeName}, CodeText: \"{codeText}\"{Environment.NewLine}");
4139

42-
// Log parameters
43-
string paramLog = $"EncodeType: {encodeType.TypeName}, CodeText: {codeText}, XDimension: {generator.Parameters.Barcode.XDimension.Point}pt, BarHeight: {generator.Parameters.Barcode.BarHeight.Point}pt, FilledBars: {generator.Parameters.Barcode.FilledBars}, BarColor: {generator.Parameters.Barcode.BarColor}, BackColor: {generator.Parameters.BackColor}, Resolution: {generator.Parameters.Resolution}dpi";
44-
Console.WriteLine(paramLog);
45-
File.AppendAllText(logPath, paramLog + Environment.NewLine);
40+
// Create and configure the barcode generator.
41+
using (var generator = new BarcodeGenerator(encodeType, codeText))
42+
{
43+
// Set visual appearance and sizing options.
44+
generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; // Bar color
45+
generator.Parameters.BackColor = Aspose.Drawing.Color.White; // Background color
46+
generator.Parameters.Barcode.XDimension.Point = 2f; // Module size (points)
47+
generator.Parameters.Barcode.BarHeight.Point = 50f; // Bar height for 1D barcodes (points)
48+
generator.Parameters.AutoSizeMode = AutoSizeMode.None; // Disable auto-sizing
4649

47-
// Generate and save barcode image
48-
using (var bitmap = generator.GenerateBarCodeImage())
49-
{
50-
bitmap.Save(imagePath, Aspose.Drawing.Imaging.ImageFormat.Png);
51-
}
50+
// Log the configured generator parameters for traceability.
51+
File.AppendAllText(logFile,
52+
$"[{DateTime.UtcNow:u}] Configured parameters:{Environment.NewLine}" +
53+
$" BarColor: {generator.Parameters.Barcode.BarColor}{Environment.NewLine}" +
54+
$" BackColor: {generator.Parameters.BackColor}{Environment.NewLine}" +
55+
$" XDimension: {generator.Parameters.Barcode.XDimension.Point} pt{Environment.NewLine}" +
56+
$" BarHeight: {generator.Parameters.Barcode.BarHeight.Point} pt{Environment.NewLine}" +
57+
$" AutoSizeMode: {generator.Parameters.AutoSizeMode}{Environment.NewLine}");
5258

53-
// Log success
54-
string successLog = $"Barcode image saved to {imagePath}";
55-
Console.WriteLine(successLog);
56-
File.AppendAllText(logPath, successLog + Environment.NewLine);
59+
try
60+
{
61+
// Save the generated barcode image to the specified file.
62+
generator.Save(outputPath);
63+
// Log successful save operation.
64+
File.AppendAllText(logFile,
65+
$"[{DateTime.UtcNow:u}] Barcode saved successfully to \"{outputPath}\".{Environment.NewLine}");
66+
Console.WriteLine($"Barcode generated and saved to {outputPath}");
67+
}
68+
catch (Exception ex)
69+
{
70+
// Log any errors that occur during generation or saving.
71+
File.AppendAllText(logFile,
72+
$"[{DateTime.UtcNow:u}] Error during barcode generation: {ex.Message}{Environment.NewLine}");
73+
Console.WriteLine($"Error: {ex.Message}");
5774
}
58-
}
59-
catch (Exception ex)
60-
{
61-
// Log any errors
62-
string errorLog = $"Error during barcode generation: {ex.Message}";
63-
Console.WriteLine(errorLog);
64-
File.AppendAllText(logPath, errorLog + Environment.NewLine);
6575
}
6676

67-
// End log
68-
File.AppendAllText(logPath, $"--- Barcode generation finished at {DateTime.UtcNow:u} ---{Environment.NewLine}");
77+
// Log the completion of the entire barcode generation workflow.
78+
File.AppendAllText(logFile,
79+
$"[{DateTime.UtcNow:u}] Barcode generation process completed.{Environment.NewLine}");
6980
}
7081
}

0 commit comments

Comments
 (0)