diff --git a/postal-barcode-types/adjust-barheight-of-postnet-barcode-to-40-points-while-keeping-automatic-width-calculation.cs b/postal-barcode-types/adjust-barheight-of-postnet-barcode-to-40-points-while-keeping-automatic-width-calculation.cs
index 6cbcfd9..8c547c9 100644
--- a/postal-barcode-types/adjust-barheight-of-postnet-barcode-to-40-points-while-keeping-automatic-width-calculation.cs
+++ b/postal-barcode-types/adjust-barheight-of-postnet-barcode-to-40-points-while-keeping-automatic-width-calculation.cs
@@ -1,34 +1,37 @@
-// Title: Adjust Postnet barcode bar height while preserving automatic width
-// Description: Demonstrates setting the BarHeight of a Postnet barcode to 40 points, letting the library compute the optimal width automatically.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on barcode parameter customization. It showcases the use of BarcodeGenerator, EncodeTypes, and the BarHeight property to modify visual dimensions. Developers often need to adjust size attributes while relying on automatic layout calculations for consistent rendering across formats.
+// Title: Generate a Postnet barcode with custom bar height
+// Description: Demonstrates how to set the BarHeight of a Postnet barcode to 40 points while allowing the library to calculate the optimal width automatically.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on symbology-specific parameter adjustments. It showcases the use of BarcodeGenerator, EncodeTypes, and the Parameters.Barcode properties to customize visual aspects of a barcode. Developers often need to modify dimensions such as bar height or module size for specific printing or scanning requirements, and this snippet illustrates the typical approach for Postnet barcodes.
// Prompt: Adjust the BarHeight of a Postnet barcode to 40 points while keeping automatic width calculation.
-// Tags: postnet, barcode, barheight, size, generation, png, aspose.barcode
+// Tags: postnet, barcode, barheight, dimension, aspnet, aspose.barcode, generation, png
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Generates a Postnet barcode with a custom bar height while allowing automatic width calculation.
+/// Example program that creates a Postnet barcode with a custom bar height.
///
class Program
{
///
- /// Entry point of the example. Creates a Postnet barcode, sets its bar height, and saves it as a PNG image.
+ /// Entry point. Generates the barcode and saves it as a PNG file.
///
static void Main()
{
- // Initialize a barcode generator for the Postnet symbology with a sample ZIP code.
- using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, "12345"))
+ // Initialize a barcode generator for the Postnet symbology
+ using (var generator = new BarcodeGenerator(EncodeTypes.Postnet))
{
- // Set the bar height to 40 points; width remains automatically calculated.
+ // Set the postal code to be encoded
+ generator.CodeText = "12345";
+
+ // Set the bar height to 40 points; width will be calculated automatically
generator.Parameters.Barcode.BarHeight.Point = 40f;
- // Save the generated barcode image to a PNG file.
+ // Save the generated barcode image as PNG
generator.Save("postnet.png");
}
- // Inform the user that the barcode has been generated.
+ // Inform the user that the barcode has been created
Console.WriteLine("Postnet barcode generated: postnet.png");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/build-rest-api-endpoint-that-receives-postal-barcode-data-and-returns-image-as-byte-array.cs b/postal-barcode-types/build-rest-api-endpoint-that-receives-postal-barcode-data-and-returns-image-as-byte-array.cs
index 1bb7267..393d88f 100644
--- a/postal-barcode-types/build-rest-api-endpoint-that-receives-postal-barcode-data-and-returns-image-as-byte-array.cs
+++ b/postal-barcode-types/build-rest-api-endpoint-that-receives-postal-barcode-data-and-returns-image-as-byte-array.cs
@@ -1,78 +1,57 @@
-// Title: Generate Postnet barcode image and return as byte array via simulated REST endpoint
-// Description: Demonstrates creating a Postnet postal barcode from input data and returning the PNG image as a byte array, suitable for a REST API response.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator with EncodeTypes.Postnet, configure image parameters, and obtain a bitmap image. Developers building web services that need to produce barcode images for mailing or shipping can reference this pattern for creating PNG byte arrays to embed in JSON responses or files.
+// Title: Generate a postal barcode image and return it as a byte array
+// Description: Demonstrates creating a Postnet barcode from input data and retrieving the PNG image as a byte array, suitable for returning from a REST API.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator with EncodeTypes.Postnet to produce barcode images. Developers often need to embed barcode creation in web services, returning image streams for client consumption. Key classes include BarcodeGenerator, EncodeTypes, and BarCodeImageFormat, which are commonly used for on‑the‑fly barcode rendering in ASP.NET Core or other API frameworks.
// Prompt: Build a REST API endpoint that receives postal barcode data and returns the image as a byte array.
-// Tags: postnet, barcode generation, image output, png, byte array, aspose.barcode, rest api
+// Tags: postnet, barcode generation, image output, png, byte array, aspose.barcode, aspnet core
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Provides a simulated REST API endpoint that generates a Postnet barcode image from postal data.
+/// Demonstrates generating a Postnet postal barcode and obtaining the image as a byte array.
///
class Program
{
///
- /// Simulated REST endpoint: receives postal barcode data and returns image bytes.
+ /// Entry point of the example. Simulates receiving barcode data, generates the barcode image, and writes the size to console.
///
- /// The postal data to encode (e.g., ZIP code).
- /// PNG image bytes representing the generated barcode.
- static byte[] GeneratePostalBarcode(string postalData)
+ static void Main()
{
- // Validate input
- if (string.IsNullOrWhiteSpace(postalData))
- throw new ArgumentException("Postal data must be provided.", nameof(postalData));
+ // Simulate receiving postal barcode data (e.g., Postnet code)
+ string postalData = "12345";
- // Create a barcode generator for Postnet (postal) symbology
- using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, postalData))
- {
- // Optional: adjust image size or resolution if needed
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 150f;
- generator.Parameters.Resolution = 96;
+ // Generate barcode image as a byte array
+ byte[] imageBytes = GeneratePostalBarcode(postalData);
- // Generate the barcode image as a Bitmap
- using (Bitmap bitmap = generator.GenerateBarCodeImage())
- {
- // Save the bitmap to a memory stream in PNG format and return the byte array
- using (var ms = new MemoryStream())
- {
- bitmap.Save(ms, ImageFormat.Png);
- return ms.ToArray();
- }
- }
- }
+ // Output the size of the generated image
+ Console.WriteLine($"Generated barcode image size: {imageBytes.Length} bytes");
}
- ///
- /// Entry point for the console demonstration. Accepts postal data via command‑line argument,
- /// generates the barcode, and writes the Base64 representation to the console.
- ///
- /// Command‑line arguments; first argument is optional postal data.
- static void Main(string[] args)
+ // Generates a postal barcode (Postnet) image and returns it as a byte array (PNG format)
+ static byte[] GeneratePostalBarcode(string codeText)
{
- // In a real REST scenario the postal data would come from the request body.
- // Here we use a sample value or a command‑line argument for demonstration.
- string postalData = args.Length > 0 ? args[0] : "12345";
+ // Validate input
+ if (string.IsNullOrEmpty(codeText))
+ throw new ArgumentException("Code text must not be null or empty.", nameof(codeText));
- try
+ // Create a memory stream to hold the image data
+ using (var memoryStream = new MemoryStream())
{
- // Generate barcode image bytes
- byte[] imageBytes = GeneratePostalBarcode(postalData);
+ // Initialize the barcode generator for Postnet symbology
+ using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, codeText))
+ {
+ // Optional: adjust barcode parameters if needed
+ // e.g., generator.Parameters.Barcode.XDimension.Point = 2f;
- // Output the result as a Base64 string (simulating a JSON response body)
- string base64 = Convert.ToBase64String(imageBytes);
- Console.WriteLine(base64);
- }
- catch (Exception ex)
- {
- // Write error details to the error stream
- Console.Error.WriteLine($"Error: {ex.Message}");
+ // Save the barcode image to the memory stream in PNG format
+ generator.Save(memoryStream, BarCodeImageFormat.Png);
+ }
+
+ // Return the image bytes from the memory stream
+ return memoryStream.ToArray();
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/configure-barcode-generation-to-use-specific-color-palette-for-bars-and-background-exporting-as-png.cs b/postal-barcode-types/configure-barcode-generation-to-use-specific-color-palette-for-bars-and-background-exporting-as-png.cs
index 79e32ce..32c366b 100644
--- a/postal-barcode-types/configure-barcode-generation-to-use-specific-color-palette-for-bars-and-background-exporting-as-png.cs
+++ b/postal-barcode-types/configure-barcode-generation-to-use-specific-color-palette-for-bars-and-background-exporting-as-png.cs
@@ -1,43 +1,46 @@
-// Title: Generate Code128 Barcode with Custom Colors and Save as PNG
-// Description: Demonstrates how to set foreground and background colors for a Code128 barcode and export it as a PNG image using Aspose.BarCode.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to customize visual appearance such as bar and background colors. It uses the BarcodeGenerator class and related Parameter objects to configure colors before saving. Developers often need to match branding or UI themes when generating barcodes, and this pattern shows the typical steps for color customization and image export.
+// Title: Generate Code128 barcode with custom colors and PNG output
+// Description: Demonstrates how to generate a Code128 barcode, apply specific bar and background colors, and export the result as a PNG image using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to customize visual appearance (foreground and background colors) of generated barcodes. It showcases key API classes such as BarcodeGenerator, EncodeTypes, and BarCodeImageFormat, which developers commonly use to create, style, and save barcodes in various image formats for integration into web, desktop, or mobile applications.
// Prompt: Configure barcode generation to use a specific color palette for bars and background, exporting as PNG.
-// Tags: code128, barcode generation, png, color palette, aspose.barcode
+// Tags: barcode, symbology, generation, color, png, aspose.barcode, code128
using System;
-using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
///
-/// Example program that creates a Code128 barcode with custom bar and background colors
-/// and saves it as a PNG image.
+/// Example program that creates a Code128 barcode with custom colors and saves it as a PNG file.
///
class Program
{
///
/// Entry point of the application.
+ /// Accepts optional command‑line arguments for the barcode text and output file path.
///
- static void Main()
+ /// Command‑line arguments: [0] = barcode text, [1] = output file path.
+ static void Main(string[] args)
{
- // Define the output file path for the generated PNG image
- string outputPath = "barcode.png";
+ // Determine the barcode text: use first argument if provided, otherwise default to "Sample123".
+ string codeText = args.Length > 0 ? args[0] : "Sample123";
- // Initialize a BarcodeGenerator for Code128 symbology with sample data
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ // Determine the output file path: use second argument if provided, otherwise default to "barcode.png".
+ string outputPath = args.Length > 1 ? args[1] : "barcode.png";
+
+ // Initialize a BarcodeGenerator for the Code128 symbology with the specified text.
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
- // Set the foreground (bar) color to red
- generator.Parameters.Barcode.BarColor = Color.Red;
+ // Set the foreground (bar) color to blue.
+ generator.Parameters.Barcode.BarColor = Color.Blue;
- // Set the background color of the image to light gray
+ // Set the background color of the image to light gray.
generator.Parameters.BackColor = Color.LightGray;
- // Save the configured barcode as a PNG file at the specified path
+ // Save the generated barcode as a PNG file at the specified location.
generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Inform the user where the barcode image has been saved
- Console.WriteLine($"Barcode image saved to: {Path.GetFullPath(outputPath)}");
+ // Inform the user where the barcode image has been saved.
+ Console.WriteLine($"Barcode image saved to: {outputPath}");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/create-barcode-generator-instance-for-rm4scc-set-custom-xdimension-and-export-image-to-byte-array.cs b/postal-barcode-types/create-barcode-generator-instance-for-rm4scc-set-custom-xdimension-and-export-image-to-byte-array.cs
index 63f994d..6c10a33 100644
--- a/postal-barcode-types/create-barcode-generator-instance-for-rm4scc-set-custom-xdimension-and-export-image-to-byte-array.cs
+++ b/postal-barcode-types/create-barcode-generator-instance-for-rm4scc-set-custom-xdimension-and-export-image-to-byte-array.cs
@@ -1,8 +1,8 @@
-// Title: Generate RM4SCC barcode with custom XDimension and export to byte array
-// Description: Demonstrates creating an Aspose.BarCode generator for the RM4SCC symbology, customizing the XDimension, and exporting the resulting PNG image to a byte array.
-// Category-Description: This example belongs to the barcode generation category of Aspose.BarCode, illustrating how to configure barcode parameters such as XDimension and retrieve the image as a byte array. It showcases the use of BarcodeGenerator, EncodeTypes, and image handling classes, which are common tasks for developers needing programmatic barcode creation for documents, labels, or web services.
+// Title: Generate RM4SCC Barcode and Export as PNG Byte Array
+// Description: This example creates an RM4SCC barcode, customizes its XDimension, and returns the barcode image as a PNG byte array.
+// Category-Description: Demonstrates Aspose.BarCode generation for the RM4SCC symbology using BarcodeGenerator. Shows how to configure barcode parameters (e.g., XDimension), render the barcode to an Aspose.Drawing.Bitmap, and retrieve the image as a byte array. Ideal for developers needing to embed barcodes in memory, send them over networks, or store them without writing to disk.
// Prompt: Create a barcode generator instance for RM4SCC, set custom XDimension, and export image to a byte array.
-// Tags: rm4scc, barcode generation, xdimension, byte array, png, aspnet, aspose.barcode, image export
+// Tags: rm4scc, barcode, generation, xdimension, png, byte-array, aspose.barcode, aspose.drawing
using System;
using System.IO;
@@ -11,44 +11,47 @@
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
-namespace BarcodeExample
+///
+/// Demonstrates generating an RM4SCC barcode, customizing its XDimension, and exporting the image to a PNG byte array.
+///
+class Program
{
///
- /// Provides an example of generating an RM4SCC barcode, customizing its XDimension,
- /// and exporting the resulting image to a byte array.
+ /// Entry point. Generates the barcode and writes the byte array length to the console.
///
- class Program
+ static void Main()
{
- ///
- /// Entry point of the example. Creates a barcode, sets a custom module width,
- /// and writes the image size to the console.
- ///
- static void Main()
- {
- // Initialize a barcode generator for the RM4SCC symbology
- using (var generator = new BarcodeGenerator(EncodeTypes.RM4SCC))
- {
- // Define the data to encode in the barcode
- generator.CodeText = "A1234567890";
+ // Generate the barcode and obtain the image as a byte array
+ byte[] barcodeBytes = GenerateRm4sccBarcode();
- // Set a custom XDimension (module width) measured in points
- generator.Parameters.Barcode.XDimension.Point = 2f;
+ // Output the size of the generated byte array to verify success
+ Console.WriteLine($"Generated barcode image byte array length: {barcodeBytes.Length}");
+ }
- // Generate the barcode image as a Bitmap object
- using (Bitmap bitmap = generator.GenerateBarCodeImage())
- {
- // Prepare a memory stream to hold the PNG-encoded image
- using (var memoryStream = new MemoryStream())
- {
- // Save the bitmap to the stream in PNG format
- bitmap.Save(memoryStream, ImageFormat.Png);
+ ///
+ /// Creates a BarcodeGenerator for RM4SCC, sets a custom XDimension, and returns the barcode image as a PNG byte array.
+ ///
+ /// Byte array containing the PNG representation of the generated barcode.
+ static byte[] GenerateRm4sccBarcode()
+ {
+ // Initialize a BarcodeGenerator with RM4SCC symbology
+ using (var generator = new BarcodeGenerator(EncodeTypes.RM4SCC))
+ {
+ // Sample code text for RM4SCC (8 characters: 2 letters + 6 digits)
+ generator.CodeText = "AB123456";
- // Retrieve the image bytes from the stream
- byte[] barcodeBytes = memoryStream.ToArray();
+ // Set a custom XDimension (module size) in points
+ generator.Parameters.Barcode.XDimension.Point = 2.5f;
- // Output the length of the generated byte array for verification
- Console.WriteLine($"Generated barcode byte array length: {barcodeBytes.Length}");
- }
+ // Generate the barcode image as an Aspose.Drawing.Bitmap
+ using (Bitmap bitmap = generator.GenerateBarCodeImage())
+ {
+ // Save the bitmap to a memory stream in PNG format
+ using (var memoryStream = new MemoryStream())
+ {
+ bitmap.Save(memoryStream, ImageFormat.Png);
+ // Return the image data as a byte array
+ return memoryStream.ToArray();
}
}
}
diff --git a/postal-barcode-types/create-configuration-file-that-defines-default-xdimension-barheight-and-filledbars-for-all-postal-barcode-operations.cs b/postal-barcode-types/create-configuration-file-that-defines-default-xdimension-barheight-and-filledbars-for-all-postal-barcode-operations.cs
index 67cd40a..627d457 100644
--- a/postal-barcode-types/create-configuration-file-that-defines-default-xdimension-barheight-and-filledbars-for-all-postal-barcode-operations.cs
+++ b/postal-barcode-types/create-configuration-file-that-defines-default-xdimension-barheight-and-filledbars-for-all-postal-barcode-operations.cs
@@ -1,48 +1,83 @@
-// Title: Generate default configuration XML for postal barcode parameters
-// Description: Demonstrates how to create an XML file that defines default XDimension, BarHeight, and FilledBars settings for postal barcode generation using Aspose.BarCode.
-// Category-Description: This example belongs to the Aspose.BarCode configuration management category, illustrating the use of BarcodeGenerator and its Parameters to set common properties for postal symbologies such as Postnet. Developers often need to define default barcode appearance settings in a reusable XML configuration file for consistent rendering across applications.
+// Title: Generate Default Configuration XML for Postal Barcodes
+// Description: Creates XML configuration files that set default XDimension, BarHeight, and FilledBars values for supported postal barcode symbologies.
+// Category-Description: This example belongs to the Aspose.BarCode configuration generation category. It demonstrates using the BarcodeGenerator class to apply common settings across multiple postal symbologies, export those settings to XML, and manage output files. Developers working with postal barcodes often need to standardize dimensions and visual properties, and this pattern shows how to automate that process for reuse in larger applications.
// Prompt: Create a configuration file that defines default XDimension, BarHeight, and FilledBars for all postal barcode operations.
-// Tags: postal barcode, configuration, xml, generation, aspnet.barcode, xdimension, barheight, filledbars
+// Tags: postal barcode, configuration, xdimension, barheight, filledbars, aspose.barcode, xml export, c#
using System;
+using System.Collections.Generic;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Example program that creates an XML configuration file containing default
-/// barcode parameters for postal symbologies (e.g., Postnet). The generated
-/// file can be reused across projects to ensure consistent barcode appearance.
+/// Demonstrates how to generate XML configuration files with default settings for postal barcode symbologies using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Generates the XML configuration file
- /// with predefined XDimension, BarHeight, and FilledBars values.
+ /// Entry point that creates default configuration files for each supported postal symbology.
///
static void Main()
{
- // Define the full path for the output XML configuration file.
- string configPath = Path.Combine(Directory.GetCurrentDirectory(), "PostalBarcodeDefaults.xml");
+ // Default values applied to all postal barcode operations
+ const float defaultXDimension = 2f; // module size in points
+ const float defaultBarHeight = 50f; // height in points
+ const bool defaultFilledBars = false; // bars not filled by default
- // Initialize a BarcodeGenerator for the Postnet postal symbology.
- // This instance is used only to set default parameters; no barcode is generated.
- using (var generator = new BarcodeGenerator(EncodeTypes.Postnet))
+ // List of postal symbologies supported by Aspose.BarCode
+ var postalSymbologies = new List
{
- // Set the default module width (XDimension) in points.
- generator.Parameters.Barcode.XDimension.Point = 2f;
+ EncodeTypes.Postnet,
+ EncodeTypes.Planet
+ };
- // Set the default height of the bars for 1D barcodes in points.
- generator.Parameters.Barcode.BarHeight.Point = 40f;
+ // Ensure the output directory exists
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "PostalConfigs");
+ if (!Directory.Exists(outputDir))
+ {
+ Directory.CreateDirectory(outputDir);
+ }
+
+ // Iterate over each symbology and generate its configuration file
+ foreach (var symbology in postalSymbologies)
+ {
+ // Obtain a minimal valid code text for the current symbology
+ string sampleCodeText = GetSampleCodeText(symbology);
+
+ // Initialize the barcode generator with the symbology and sample text
+ using (var generator = new BarcodeGenerator(symbology, sampleCodeText))
+ {
+ // Apply the default configuration settings
+ generator.Parameters.Barcode.XDimension.Point = defaultXDimension;
+ generator.Parameters.Barcode.BarHeight.Point = defaultBarHeight;
+ generator.Parameters.Barcode.FilledBars = defaultFilledBars;
- // Specify that bars should be rendered as filled shapes.
- generator.Parameters.Barcode.FilledBars = true;
+ // Build the output file name and path
+ string fileName = $"{symbology.TypeName}_Config.xml";
+ string filePath = Path.Combine(outputDir, fileName);
- // Export the configured parameters to an XML file at the specified path.
- generator.ExportToXml(configPath);
+ // Export the configured settings to an XML file
+ generator.ExportToXml(filePath);
+
+ Console.WriteLine($"Exported configuration for {symbology.TypeName} to {filePath}");
+ }
}
- // Inform the user where the configuration file has been created.
- Console.WriteLine($"Configuration file created at: {configPath}");
+ Console.WriteLine("All postal barcode configurations have been generated.");
+ }
+
+ // Provides a minimal valid code text for the given postal symbology
+ private static string GetSampleCodeText(BaseEncodeType symbology)
+ {
+ // Postnet expects a 5, 6, 9, or 11 digit ZIP code; use 5 digits.
+ // Planet expects a 6-digit ZIP+4; use 6 digits.
+ if (symbology == EncodeTypes.Postnet)
+ return "12345";
+ if (symbology == EncodeTypes.Planet)
+ return "123456";
+
+ // Fallback generic code text
+ return "12345";
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/create-custom-barcode-generation-utility-that-accepts-command-line-arguments-for-symbology-data-and-output-path.cs b/postal-barcode-types/create-custom-barcode-generation-utility-that-accepts-command-line-arguments-for-symbology-data-and-output-path.cs
index 9ee3046..407a05a 100644
--- a/postal-barcode-types/create-custom-barcode-generation-utility-that-accepts-command-line-arguments-for-symbology-data-and-output-path.cs
+++ b/postal-barcode-types/create-custom-barcode-generation-utility-that-accepts-command-line-arguments-for-symbology-data-and-output-path.cs
@@ -1,8 +1,8 @@
-// Title: Custom Barcode Generation Utility
-// Description: Demonstrates generating a barcode image using Aspose.BarCode based on command‑line parameters for symbology, data, and output file path.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class with EncodeTypes to create various barcode symbologies. Typical use cases include automating barcode creation in batch scripts, CI pipelines, or desktop utilities where users specify the barcode type and content at runtime. Developers often need to resolve symbology names dynamically, handle output directories, and manage exceptions during image generation.
-// Prompt: Create a custom barcode generation utility that accepts command‑line arguments for symbology, data, and output path.
-// Tags: barcode, symbology, generation, png, aspose.barcodes, encode types
+// Title: Command‑Line Barcode Generation Utility
+// Description: Generates a barcode image using Aspose.BarCode based on command‑line parameters for symbology, data, and output file path.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, demonstrating how to create barcodes programmatically. It showcases the BarcodeGenerator, EncodeTypes, and BaseEncodeType classes, which are commonly used for producing barcode images for labeling, inventory, and point‑of‑sale applications. Developers often need to select a symbology at runtime, supply data, and save the result in various image formats.
+/// Prompt: Create a custom barcode generation utility that accepts command‑line arguments for symbology, data, and output path.
+/// Tags: barcode, symbology, generation, command-line, aspose.barcode, encode-types, image-output
using System;
using System.IO;
@@ -11,79 +11,77 @@
using Aspose.BarCode.Generation;
///
-/// Provides a command‑line utility to generate barcode images using Aspose.BarCode.
+/// Provides a simple command‑line utility for generating barcodes using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the utility. Parses command‑line arguments, resolves the requested symbology,
- /// ensures the output directory exists, and generates the barcode image.
+ /// Entry point of the application. Parses command‑line arguments, creates a barcode generator,
+ /// and saves the resulting image to the specified path.
///
///
/// Expected arguments:
/// 0 – Symbology name (e.g., "Code128").
/// 1 – Data to encode.
- /// 2 – Output file path (including file name and extension).
+ /// 2 – Output file path (image format inferred from extension).
///
- static void Main(string[] args)
+ /// 0 on success; non‑zero error code on failure.
+ static int Main(string[] args)
{
- // Default values used when arguments are not supplied
- string symbologyName = "Code128";
- string data = "123456";
- string outputPath = "barcode.png";
+ // --------------------------------------------------------------------
+ // Resolve command‑line arguments or fall back to default values.
+ // --------------------------------------------------------------------
+ string symbology = args.Length > 0 ? args[0] : "Code128";
+ string data = args.Length > 1 ? args[1] : "Sample123";
+ string outputPath = args.Length > 2 ? args[2] : "barcode.png";
- // Override defaults with provided command‑line arguments, if any
- if (args.Length > 0 && !string.IsNullOrWhiteSpace(args[0]))
- symbologyName = args[0];
- if (args.Length > 1 && !string.IsNullOrWhiteSpace(args[1]))
- data = args[1];
- if (args.Length > 2 && !string.IsNullOrWhiteSpace(args[2]))
- outputPath = args[2];
-
- // Resolve the symbology name to an EncodeTypes field using reflection
- FieldInfo field = typeof(EncodeTypes).GetField(symbologyName, BindingFlags.Public | BindingFlags.Static);
+ // --------------------------------------------------------------------
+ // Convert the symbology string to the corresponding EncodeTypes field.
+ // --------------------------------------------------------------------
+ FieldInfo field = typeof(EncodeTypes).GetField(symbology);
if (field == null)
{
- Console.WriteLine($"Unknown symbology: {symbologyName}");
- return;
+ Console.WriteLine($"Unknown symbology: {symbology}");
+ return 1;
}
- // Cast the reflected field value to BaseEncodeType
- BaseEncodeType encodeType = field.GetValue(null) as BaseEncodeType;
+ BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null);
if (encodeType == null)
{
- Console.WriteLine($"Failed to obtain encode type for symbology: {symbologyName}");
- return;
+ Console.WriteLine($"Failed to obtain encode type for symbology: {symbology}");
+ return 1;
}
- // Ensure the directory for the output file exists
- string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath));
+ // --------------------------------------------------------------------
+ // Ensure the output directory exists before attempting to save the file.
+ // --------------------------------------------------------------------
+ string directory = Path.GetDirectoryName(outputPath);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
- try
- {
- Directory.CreateDirectory(directory);
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Unable to create output directory: {ex.Message}");
- return;
- }
+ Directory.CreateDirectory(directory);
}
- // Generate the barcode and save it to the specified path
try
{
- using (var generator = new BarcodeGenerator(encodeType, data))
+ // ----------------------------------------------------------------
+ // Create and configure the barcode generator.
+ // ----------------------------------------------------------------
+ using (BarcodeGenerator generator = new BarcodeGenerator(encodeType, data))
{
+ // Optional: set a common parameter (module size) for better readability.
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+
+ // Save the barcode image; format is inferred from the file extension.
generator.Save(outputPath);
}
Console.WriteLine($"Barcode generated successfully: {outputPath}");
+ return 0;
}
catch (Exception ex)
{
Console.WriteLine($"Error generating barcode: {ex.Message}");
+ return 1;
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/decode-australia-post-barcode-from-multi-page-tiff-and-process-each-page-sequentially.cs b/postal-barcode-types/decode-australia-post-barcode-from-multi-page-tiff-and-process-each-page-sequentially.cs
index b0b3d93..766428e 100644
--- a/postal-barcode-types/decode-australia-post-barcode-from-multi-page-tiff-and-process-each-page-sequentially.cs
+++ b/postal-barcode-types/decode-australia-post-barcode-from-multi-page-tiff-and-process-each-page-sequentially.cs
@@ -1,14 +1,15 @@
-// Title: Decode Australia Post barcode from a multi‑page TIFF
-// Description: Demonstrates how to read Australia Post barcodes from each page of a multi‑page TIFF image and output barcode type, text, and location.
-// Category-Description: This example belongs to the Aspose.BarCode recognition category, showcasing the use of BarCodeReader with DecodeType.AustraliaPost on multi‑frame images. It illustrates loading TIFF frames via Aspose.Drawing, converting frames to a supported format, and iterating through pages to extract barcode data—common tasks for developers handling batch scanning or document processing workflows.
+// Title: Decode Australia Post Barcodes from Multi‑Page TIFF
+// Description: Demonstrates loading a multi‑page TIFF, iterating through each page, and decoding Australia Post barcodes using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category. It shows how to use Aspose.Drawing to handle multi‑frame TIFF images and Aspose.BarCode.BarCodeRecognition's BarCodeReader with DecodeType.AustraliaPost to extract barcode data. Typical use cases include processing scanned shipping documents, batch‑scanning postal forms, or automating data entry from multi‑page image files. Developers often need to read each frame, create a Bitmap, and invoke the reader to obtain barcode type and text.
// Prompt: Decode an Australia Post barcode from a multi‑page TIFF and process each page sequentially.
-// Tags: australia post, barcode, decode, tiff, multiframe, aspose.barcode, aspose.drawing
+// Tags: australia post, barcode, decoding, tiff, multiframe, aspose.barcode, csharp
using System;
using System.IO;
+using Aspose.BarCode;
+using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
-using Aspose.BarCode.BarCodeRecognition;
///
/// Example program that decodes Australia Post barcodes from each page of a multi‑page TIFF file.
@@ -16,58 +17,56 @@
class Program
{
///
- /// Entry point of the application. Loads the TIFF, iterates through its pages, and reads barcodes.
+ /// Entry point. Loads the TIFF, iterates pages, and prints decoded barcode information.
///
static void Main()
{
- // Path to the multi‑page TIFF file containing Australia Post barcodes
- const string tiffPath = "input.tif";
+ // Path to the multi‑page TIFF containing Australia Post barcodes.
+ string tiffPath = "AustraliaPost.tif";
- // Verify that the file exists before attempting to process it
+ // Verify that the file exists before attempting to load it.
if (!File.Exists(tiffPath))
{
Console.WriteLine($"File not found: {tiffPath}");
return;
}
- // Load the TIFF image using Aspose.Drawing
- using (var tiffImage = new Bitmap(tiffPath))
+ // Load the TIFF image. Aspose.Drawing.Image supports multi‑frame TIFFs.
+ using (Image tiffImage = Image.FromFile(tiffPath))
{
- // Use the time dimension to iterate over pages (frames) of the TIFF
- var frameDimension = FrameDimension.Time;
- int pageCount = tiffImage.GetFrameCount(frameDimension);
+ // Determine how many pages (frames) the TIFF contains.
+ int pageCount = tiffImage.GetFrameCount(FrameDimension.Page);
+ Console.WriteLine($"TIFF contains {pageCount} page(s).");
- // Process each page sequentially
+ // Process each page sequentially.
for (int pageIndex = 0; pageIndex < pageCount; pageIndex++)
{
- // Select the current frame (page) in the TIFF
- tiffImage.SelectActiveFrame(frameDimension, pageIndex);
+ // Activate the current frame.
+ tiffImage.SelectActiveFrame(FrameDimension.Page, pageIndex);
- // Save the selected frame to a memory stream as PNG (BarCodeReader works with Bitmap)
- using (var ms = new MemoryStream())
+ // Clone the active frame into a Bitmap for barcode reading.
+ using (Bitmap frameBitmap = (Bitmap)tiffImage.Clone())
{
- tiffImage.Save(ms, ImageFormat.Png);
- ms.Position = 0;
-
- // Load the frame as a Bitmap for barcode recognition
- using (var frameBitmap = new Bitmap(ms))
+ // Create a BarCodeReader for Australia Post symbology.
+ using (BarCodeReader reader = new BarCodeReader(frameBitmap, DecodeType.AustraliaPost))
{
- // Create a reader configured for Australia Post barcodes
- using (var reader = new BarCodeReader(frameBitmap, DecodeType.AustraliaPost))
- {
- // Read all barcodes on the current page
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Page {pageIndex + 1}: Type = {result.CodeType}, Text = {result.CodeText}");
+ // Optional: set the interpreting type for customer information if needed.
+ // reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
- // Output the bounding rectangle of the detected barcode
- var rect = result.Region.Rectangle;
- Console.WriteLine($" Region - X:{rect.X}, Y:{rect.Y}, Width:{rect.Width}, Height:{rect.Height}");
- }
+ // Perform the recognition.
+ BarCodeResult[] results = reader.ReadBarCodes();
+
+ Console.WriteLine($"Page {pageIndex + 1}: Detected {results.Length} barcode(s).");
+ foreach (BarCodeResult result in results)
+ {
+ Console.WriteLine($" Type : {result.CodeType}");
+ Console.WriteLine($" CodeText: {result.CodeText}");
}
}
}
}
}
+
+ Console.WriteLine("Processing completed.");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/decode-dutch-kix-barcode-from-byte-array-and-handle-potential-format-exceptions.cs b/postal-barcode-types/decode-dutch-kix-barcode-from-byte-array-and-handle-potential-format-exceptions.cs
index 2968710..eb1791b 100644
--- a/postal-barcode-types/decode-dutch-kix-barcode-from-byte-array-and-handle-potential-format-exceptions.cs
+++ b/postal-barcode-types/decode-dutch-kix-barcode-from-byte-array-and-handle-potential-format-exceptions.cs
@@ -1,80 +1,99 @@
-// Title: Decode Dutch KIX barcode from byte array
-// Description: Demonstrates generating a Dutch KIX barcode, storing it in a byte array, and decoding it while handling format exceptions.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator to create a Dutch KIX symbology image and BarCodeReader to decode it from a memory stream. Developers working with postal code barcodes often need to generate barcodes programmatically and later validate or extract the encoded data, making this pattern common for batch processing and automated verification scenarios.
+// Title: Decode Dutch KIX barcode from byte array with exception handling
+// Description: Demonstrates generating a Dutch KIX barcode, converting it to a PNG byte array, and decoding it while handling format exceptions.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes, BarCodeReader for decoding, and handling BarCodeException. Developers often need to generate barcodes in memory, transmit them as byte arrays, and reliably decode them in various applications such as inventory systems or document processing.
// Prompt: Decode a Dutch KIX barcode from a byte array and handle potential format exceptions.
-// Tags: dutchkix, barcode, decode, png, barcodereader, barcodegenerator, exception-handling
+// Tags: barcode, dutch kix, decode, byte array, exception handling, aspose.barcode, generation, recognition
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing.Imaging;
///
-/// Example program that generates a Dutch KIX barcode, stores it in a byte array,
-/// and then decodes it while handling possible format exceptions.
+/// Provides an example of generating and decoding a Dutch KIX barcode using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the example. Generates, stores, and decodes a Dutch KIX barcode.
+ /// Entry point of the example. Generates a Dutch KIX barcode, obtains its PNG byte array,
+ /// and decodes the barcode while handling possible exceptions.
///
static void Main()
{
- // Sample data to encode – Dutch KIX requires numeric postal code format.
- string sampleCode = "12345678";
+ // Sample code text for Dutch KIX barcode (example value)
+ const string sampleCodeText = "123456789";
- // Generate a Dutch KIX barcode image and store it in a memory stream.
- byte[] barcodeBytes;
- using (var generator = new BarcodeGenerator(EncodeTypes.DutchKIX, sampleCode))
+ // Generate a Dutch KIX barcode image and obtain its byte array
+ byte[] barcodeBytes = GenerateDutchKixBarcode(sampleCodeText);
+
+ // Decode the barcode from the byte array
+ DecodeDutchKixFromBytes(barcodeBytes);
+ }
+
+ ///
+ /// Generates a Dutch KIX barcode image and returns the image bytes in PNG format.
+ ///
+ /// The text to encode in the barcode.
+ /// Byte array containing the PNG image of the generated barcode.
+ static byte[] GenerateDutchKixBarcode(string codeText)
+ {
+ // Use a memory stream to hold the generated image
+ using (var ms = new MemoryStream())
{
- using (var ms = new MemoryStream())
+ // Initialize the generator with Dutch KIX symbology
+ using (var generator = new BarcodeGenerator(EncodeTypes.DutchKIX, codeText))
{
- // Save the generated barcode as PNG into the memory stream.
+ // Save the barcode image to the memory stream in PNG format
generator.Save(ms, BarCodeImageFormat.Png);
- barcodeBytes = ms.ToArray(); // Convert the stream to a byte array.
}
+
+ // Return the image bytes from the memory stream
+ return ms.ToArray();
+ }
+ }
+
+ ///
+ /// Decodes a Dutch KIX barcode from a byte array and prints the result.
+ /// Handles both barcode-specific and general exceptions.
+ ///
+ /// Byte array containing the barcode image.
+ static void DecodeDutchKixFromBytes(byte[] imageBytes)
+ {
+ // Validate input
+ if (imageBytes == null || imageBytes.Length == 0)
+ {
+ Console.WriteLine("No image data provided.");
+ return;
}
- // Decode the barcode from the byte array.
- try
+ // Create a memory stream from the byte array for decoding
+ using (var ms = new MemoryStream(imageBytes))
{
- using (var imageStream = new MemoryStream(barcodeBytes))
+ try
{
- // Initialize the reader for Dutch KIX symbology.
- using (var reader = new BarCodeReader(imageStream, DecodeType.DutchKIX))
+ // Initialize the reader for Dutch KIX decode type
+ using (var reader = new BarCodeReader(ms, DecodeType.DutchKIX))
{
- // Optionally set a quality preset (default is NormalQuality).
- reader.QualitySettings = QualitySettings.NormalQuality;
-
- // Perform the recognition.
- var results = reader.ReadBarCodes();
-
- if (results.Length == 0)
- {
- Console.WriteLine("No Dutch KIX barcode detected.");
- }
- else
+ // Iterate through all detected barcodes in the image
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- foreach (var result in results)
- {
- // result.CodeText will be null if decoding failed; check for that.
- if (!string.IsNullOrEmpty(result.CodeText))
- {
- Console.WriteLine($"Decoded Dutch KIX CodeText: {result.CodeText}");
- }
- else
- {
- Console.WriteLine("Barcode detected but CodeText could not be read.");
- }
- }
+ Console.WriteLine($"Decoded Type: {result.CodeTypeName}");
+ Console.WriteLine($"Decoded Text: {result.CodeText}");
}
}
}
- }
- catch (Exception ex)
- {
- // Handle possible format or processing exceptions.
- Console.WriteLine($"Error during barcode decoding: {ex.Message}");
+ catch (BarCodeException ex)
+ {
+ // Handle format or recognition errors specific to Aspose.BarCode
+ Console.WriteLine($"BarCodeException: {ex.Message}");
+ }
+ catch (Exception ex)
+ {
+ // General exception handling
+ Console.WriteLine($"Error: {ex.Message}");
+ }
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/decode-mailmark-barcode-from-jpeg-image-and-output-result-to-console.cs b/postal-barcode-types/decode-mailmark-barcode-from-jpeg-image-and-output-result-to-console.cs
index 48068ab..7b80ab0 100644
--- a/postal-barcode-types/decode-mailmark-barcode-from-jpeg-image-and-output-result-to-console.cs
+++ b/postal-barcode-types/decode-mailmark-barcode-from-jpeg-image-and-output-result-to-console.cs
@@ -1,72 +1,77 @@
// Title: Decode Mailmark barcode from JPEG image
-// Description: Demonstrates how to read a Mailmark barcode from a JPEG file and display its raw and parsed data.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on Mailmark symbology. It showcases the use of BarCodeReader with DecodeType.Mailmark and ComplexCodetextReader to extract structured information. Developers working with postal or logistics barcodes can use this pattern to integrate Mailmark decoding into .NET applications.
+// Description: Demonstrates generating a Mailmark barcode, saving it as a JPEG, and decoding its codetext using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation and recognition category. It showcases the Mailmark symbology, utilizing key API classes such as MailmarkCodetext, ComplexBarcodeGenerator, and ComplexCodetextReader. Typical use cases include postal automation and logistics where Mailmark barcodes are encoded, printed, and later decoded to retrieve shipment details. Developers often need to generate barcode images, store them, and programmatically extract the embedded data.
// Prompt: Decode a Mailmark barcode from a JPEG image and output the result to the console.
-// Tags: mailmark, barcode, decoding, console, aspose.barcode, complexcodetextreader
+// Tags: mailmark, barcode, decode, jpeg, console, aspose.barcode, complexbarcode, codetext
using System;
using System.IO;
-using Aspose.BarCode.BarCodeRecognition;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode.Generation;
+using Aspose.BarCode.BarCodeRecognition;
///
-/// Program to decode a Mailmark barcode from a JPEG image and display the results.
+/// Example program that creates a Mailmark barcode, saves it as a JPEG, and decodes the codetext.
///
class Program
{
///
- /// Entry point. Reads the image, decodes Mailmark barcodes, and prints raw and parsed data.
+ /// Entry point of the example. Generates a Mailmark barcode image, decodes its codetext, and writes the results to the console.
///
static void Main()
{
- // Path to the JPEG image containing the Mailmark barcode
- const string imagePath = "mailmark.jpg";
-
- // Verify that the image file exists before attempting to read it
- if (!File.Exists(imagePath))
+ // ------------------------------------------------------------
+ // Prepare a sample Mailmark codetext with all required fields.
+ // ------------------------------------------------------------
+ var mailmark = new MailmarkCodetext
{
- Console.WriteLine($"File not found: {imagePath}");
- return;
- }
+ Format = 4, // Large Letter
+ VersionID = 1,
+ Class = "0", // Null or Test
+ SupplychainID = 384224,
+ ItemID = 16563762,
+ DestinationPostCodePlusDPS = "EF61AH8T " // 9 chars with trailing spaces
+ };
- // Initialize a BarCodeReader configured for Mailmark decoding
- using (var reader = new BarCodeReader(imagePath, DecodeType.Mailmark))
+ // ------------------------------------------------------------
+ // Construct the codetext string that will be encoded into the barcode.
+ // ------------------------------------------------------------
+ string constructedCodetext = mailmark.GetConstructedCodetext();
+
+ // ------------------------------------------------------------
+ // Generate a Mailmark barcode image and save it as a JPEG file.
+ // ------------------------------------------------------------
+ string imagePath = Path.Combine(Path.GetTempPath(), "mailmark.jpg");
+ using (var generator = new ComplexBarcodeGenerator(mailmark))
{
- // Read all Mailmark barcodes present in the image
- var results = reader.ReadBarCodes();
+ // Save directly to JPEG format.
+ generator.Save(imagePath, BarCodeImageFormat.Jpeg);
+ }
- // If no barcodes were detected, inform the user and exit
- if (results.Length == 0)
- {
- Console.WriteLine("No Mailmark barcode detected.");
- return;
- }
+ // Inform the user where the image was saved (optional).
+ Console.WriteLine($"Mailmark barcode image saved to: {imagePath}");
- // Process each detected barcode
- foreach (var result in results)
- {
- // Output the raw decoded text from the barcode
- Console.WriteLine($"Decoded CodeText: {result.CodeText}");
+ // ------------------------------------------------------------
+ // Decode the codetext using ComplexCodetextReader.
+ // Note: Image decoding is not supported; we decode the constructed string.
+ // ------------------------------------------------------------
+ MailmarkCodetext decoded = ComplexCodetextReader.TryDecodeMailmark(constructedCodetext);
- // Attempt to parse the raw text into structured Mailmark fields
- var mailmark = ComplexCodetextReader.TryDecodeMailmark(result.CodeText);
- if (mailmark != null)
- {
- // Display the parsed Mailmark details
- Console.WriteLine("Mailmark Details:");
- Console.WriteLine($" Format: {mailmark.Format}");
- Console.WriteLine($" VersionID: {mailmark.VersionID}");
- Console.WriteLine($" Class: {mailmark.Class}");
- Console.WriteLine($" SupplychainID: {mailmark.SupplychainID}");
- Console.WriteLine($" ItemID: {mailmark.ItemID}");
- Console.WriteLine($" DestinationPostCodePlusDPS: {mailmark.DestinationPostCodePlusDPS}");
- }
- else
- {
- // Inform the user if parsing failed
- Console.WriteLine("Failed to parse Mailmark codetext into structured data.");
- }
- }
+ if (decoded == null)
+ {
+ Console.WriteLine("Failed to decode Mailmark codetext.");
+ return;
}
+
+ // ------------------------------------------------------------
+ // Output the decoded Mailmark fields to the console.
+ // ------------------------------------------------------------
+ Console.WriteLine("Decoded Mailmark data:");
+ Console.WriteLine($" Format: {decoded.Format}");
+ Console.WriteLine($" VersionID: {decoded.VersionID}");
+ Console.WriteLine($" Class: {decoded.Class}");
+ Console.WriteLine($" SupplychainID: {decoded.SupplychainID}");
+ Console.WriteLine($" ItemID: {decoded.ItemID}");
+ Console.WriteLine($" DestinationPostCodePlusDPS: '{decoded.DestinationPostCodePlusDPS}'");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/decode-onecode-barcode-from-network-response-stream-and-log-any-decoding-errors.cs b/postal-barcode-types/decode-onecode-barcode-from-network-response-stream-and-log-any-decoding-errors.cs
index 5dc01e7..0389411 100644
--- a/postal-barcode-types/decode-onecode-barcode-from-network-response-stream-and-log-any-decoding-errors.cs
+++ b/postal-barcode-types/decode-onecode-barcode-from-network-response-stream-and-log-any-decoding-errors.cs
@@ -1,58 +1,68 @@
-// Title: Decode OneCode barcode from a network response stream
-// Description: Downloads an image containing a OneCode barcode, decodes it using Aspose.BarCode, and logs any decoding errors.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, demonstrating how to use BarCodeReader with DecodeType.OneCode to read barcodes from streams. Typical use cases include processing images received over HTTP, handling real‑time scanning scenarios, and integrating barcode decoding into web services. Developers often need to retrieve image data from a network source, instantiate a BarCodeReader for a specific symbology, and handle possible errors gracefully.
+// Title: Decode OneCode barcode from a network stream and log errors
+// Description: Downloads an image containing a USPS OneCode barcode, decodes it using Aspose.BarCode, and writes success or error messages to the console.
+// Category-Description: This example demonstrates barcode recognition with Aspose.BarCode, focusing on the BarCodeReader class and DecodeType enumeration. It shows how to retrieve an image via HttpClient, feed the response stream to the reader, and handle typical outcomes such as successful decoding, missing code text, or exceptions. Developers working with barcode scanning in web or service scenarios can use this pattern to integrate barcode decoding into automated workflows.
// Prompt: Decode a OneCode barcode from a network response stream and log any decoding errors.
-// Tags: onecode, barcode, decode, network, stream, aspose.barcode, barcoderecognition
+// Tags: onecode, barcode, decode, network, aspose.barcode, console
using System;
+using System.IO;
using System.Net.Http;
+using System.Threading.Tasks;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates downloading an image containing a OneCode barcode,
-/// decoding it with Aspose.BarCode, and logging any errors that occur.
+/// Demonstrates how to download an image containing a USPS OneCode barcode,
+/// decode it using Aspose.BarCode, and log any decoding errors to the console.
///
class Program
{
///
- /// Entry point of the example. Performs the download, decoding, and logging.
+ /// Asynchronously downloads the image, decodes OneCode barcodes, and writes results.
///
- static void Main()
+ /// Optional command‑line argument specifying the image URL.
+ static async Task Main(string[] args)
{
- // URL of the image that contains a OneCode barcode.
- const string imageUrl = "https://example.com/onecode.png";
+ // Determine the image URL: use the first argument if supplied, otherwise a default placeholder.
+ string imageUrl = args.Length > 0 ? args[0] : "https://example.com/sample_onecode.png";
+
+ Console.WriteLine($"Downloading image from: {imageUrl}");
try
{
- // Create an HttpClient to download the image.
+ // Create an HttpClient instance for the download; wrap in using to ensure disposal.
using (HttpClient httpClient = new HttpClient())
{
- // Send a synchronous GET request and obtain the response.
- using (HttpResponseMessage response = httpClient.GetAsync(imageUrl).Result)
+ // Asynchronously obtain the image stream from the URL.
+ using (Stream imageStream = await httpClient.GetStreamAsync(imageUrl))
{
- // Throw if the HTTP status is not successful.
- response.EnsureSuccessStatusCode();
+ // Specify the decode type for USPS OneCode barcodes.
+ BaseDecodeType decodeType = DecodeType.OneCode;
- // Get the response content as a stream.
- using (System.IO.Stream imageStream = response.Content.ReadAsStreamAsync().Result)
+ // Initialise the BarCodeReader with the image stream and the desired decode type.
+ using (BarCodeReader reader = new BarCodeReader(imageStream, decodeType))
{
- // Initialize BarCodeReader for the OneCode symbology using the image stream.
- using (BarCodeReader reader = new BarCodeReader(imageStream, DecodeType.OneCode))
- {
- // Read all barcodes found in the image.
- BarCodeResult[] results = reader.ReadBarCodes();
+ // Perform barcode recognition; returns an array of results.
+ BarCodeResult[] results = reader.ReadBarCodes();
- // If no barcodes were detected, inform the user.
- if (results.Length == 0)
- {
- Console.WriteLine("No OneCode barcode detected in the image.");
- }
- else
+ if (results.Length == 0)
+ {
+ // No barcodes were found in the image.
+ Console.WriteLine("No OneCode barcode detected in the image.");
+ }
+ else
+ {
+ // Iterate through each detected barcode.
+ foreach (BarCodeResult result in results)
{
- // Iterate through each detected barcode and log its text.
- foreach (BarCodeResult result in results)
+ // If the decoded text is missing, treat it as a decoding error.
+ if (string.IsNullOrEmpty(result.CodeText))
+ {
+ Console.WriteLine($"[Error] Barcode detected but code text is missing. Type: {result.CodeTypeName}");
+ }
+ else
{
- Console.WriteLine($"Detected OneCode barcode: {result.CodeText}");
+ // Successful decode – output type and decoded text.
+ Console.WriteLine($"[Success] Detected OneCode barcode. Type: {result.CodeTypeName}, CodeText: {result.CodeText}");
}
}
}
@@ -62,8 +72,8 @@ static void Main()
}
catch (Exception ex)
{
- // Log any exceptions that occurred during download or decoding.
- Console.WriteLine($"Error: {ex.Message}");
+ // Log any exceptions that occur during download or decoding.
+ Console.WriteLine($"[Exception] {ex.GetType().Name}: {ex.Message}");
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/decode-planet-barcode-image-from-file-path-and-retrieve-encoded-numeric-string.cs b/postal-barcode-types/decode-planet-barcode-image-from-file-path-and-retrieve-encoded-numeric-string.cs
index 13e4cd3..e8d7906 100644
--- a/postal-barcode-types/decode-planet-barcode-image-from-file-path-and-retrieve-encoded-numeric-string.cs
+++ b/postal-barcode-types/decode-planet-barcode-image-from-file-path-and-retrieve-encoded-numeric-string.cs
@@ -1,55 +1,52 @@
-// Title: Decode Planet Barcode from Image
-// Description: Demonstrates how to decode a Planet barcode stored in an image file and retrieve its numeric value.
-// Category-Description: This example belongs to the Aspose.BarCode recognition category, illustrating the use of BarCodeReader with DecodeType.Planet. It shows how to load an image, verify its existence, and extract encoded data—common tasks for developers integrating barcode scanning into document processing, inventory systems, or mobile apps.
+// Title: Decode Planet barcode from image file
+// Description: This example shows how to read a Planet barcode from an image file and obtain its numeric text using Aspose.BarCode.
+// Category-Description: The sample belongs to the barcode decoding category of Aspose.BarCode, illustrating the use of BarCodeReader with DecodeType.Planet. It demonstrates typical scenarios such as processing scanned images to extract data from Planet symbology, a numeric‑only barcode used in logistics. Developers often need to validate or import such codes, and this example provides a concise reference for implementing the operation.
// Prompt: Decode a Planet barcode image from a file path and retrieve the encoded numeric string.
-// Tags: planet, barcode, decode, recognition, aspose.barcode
+// Tags: planet, barcode, decode, image, aspose.barcode, barcodereader, decode type, console
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Provides a console application that decodes Planet barcodes from image files.
+/// Demonstrates decoding of a Planet barcode image using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Accepts an optional image path argument,
- /// validates the file, and prints decoded Planet barcode values to the console.
+ /// Entry point. Reads the image path from arguments (or defaults), decodes any Planet barcodes, and prints the result.
///
- /// Command‑line arguments; the first argument can be the image file path.
+ /// Command‑line arguments; first argument may be the image file path.
static void Main(string[] args)
{
- // Determine the image path: use the first command‑line argument if supplied, otherwise default to "planet.png".
+ // Determine the image file path: use the first argument if supplied, otherwise fall back to a default file name.
string imagePath = args.Length > 0 ? args[0] : "planet.png";
- // Ensure the specified file exists before attempting to read it.
+ // Ensure the specified file exists before attempting to decode.
if (!File.Exists(imagePath))
{
Console.WriteLine($"File not found: {imagePath}");
return;
}
- // Initialize a BarCodeReader for the Planet symbology using the provided image.
+ // Create a BarCodeReader configured for the Planet symbology.
using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.Planet))
{
- // Optional: configure quality settings if higher accuracy is required.
- // reader.QualitySettings = QualitySettings.HighQuality;
-
- // Execute the barcode recognition process.
+ // Retrieve all barcodes detected in the image.
BarCodeResult[] results = reader.ReadBarCodes();
- // Check whether any Planet barcodes were detected.
if (results.Length == 0)
{
+ // No Planet barcode was found in the supplied image.
Console.WriteLine("No Planet barcode detected in the image.");
}
else
{
- // Iterate through all detected barcodes and output their decoded text.
+ // Iterate through each detected barcode and output its decoded text.
foreach (BarCodeResult result in results)
{
- Console.WriteLine($"Decoded Planet barcode: {result.CodeText}");
+ Console.WriteLine($"Decoded Planet barcode text: {result.CodeText}");
}
}
}
diff --git a/postal-barcode-types/decode-postnet-barcode-from-memory-stream-and-verify-checksum-correctness.cs b/postal-barcode-types/decode-postnet-barcode-from-memory-stream-and-verify-checksum-correctness.cs
index 8b6c9bc..c12dcd8 100644
--- a/postal-barcode-types/decode-postnet-barcode-from-memory-stream-and-verify-checksum-correctness.cs
+++ b/postal-barcode-types/decode-postnet-barcode-from-memory-stream-and-verify-checksum-correctness.cs
@@ -1,85 +1,62 @@
-// Title: Decode Postnet barcode from memory stream and verify checksum
-// Description: Demonstrates decoding a Postnet barcode generated in‑memory and checking its checksum.
-// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It shows how to use BarcodeGenerator (EncodeTypes.Postnet) to create a barcode, store it in a MemoryStream, and then use BarCodeReader (DecodeType.Postnet) to read and validate the checksum. Developers working with postal barcodes often need to generate, transmit, and verify barcodes without persisting files, making in‑memory processing essential.
+// Title: Decode Postnet barcode from memory stream and validate checksum
+// Description: Demonstrates decoding a Postnet barcode that was generated in‑memory, reading it from a MemoryStream, and confirming the checksum is correct.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It shows how to use BarcodeGenerator to create a Postnet barcode, store it in a MemoryStream, and then use BarCodeReader to decode the image. Typical use cases include on‑the‑fly barcode generation for web services, automated verification of postal codes, and checksum validation in batch processing. Developers often work with the BarcodeGenerator, BarCodeReader, and related settings such as ChecksumValidation to ensure data integrity.
// Prompt: Decode a Postnet barcode from a memory stream and verify checksum correctness.
-// Tags: postnet, barcode, decode, checksum, memory stream, aspose.barcode, generation, recognition
+// Tags: postnet, barcode, decode, checksum, memorystream, aspose.barcode, generation, recognition
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Example program that generates a Postnet barcode, reads it from a memory stream,
-/// and validates the checksum of the decoded value.
+/// Example program that generates a Postnet barcode, decodes it from a memory stream,
+/// and validates the checksum using Aspose.BarCode APIs.
///
class Program
{
///
- /// Entry point of the example. Generates, decodes, and validates a Postnet barcode.
+ /// Entry point of the example. Generates a Postnet barcode, reads it back,
+ /// and prints decoding results along with checksum verification.
///
static void Main()
{
- // Sample ZIP code (without checksum)
- string zip = "12345";
+ // Define a sample ZIP code (5 digits). The Postnet checksum digit will be added automatically.
+ const string zipCode = "12345";
- // Create a memory stream to hold the generated barcode image
- using (var ms = new MemoryStream())
+ // Create a memory stream to hold the generated barcode image.
+ using (var memoryStream = new MemoryStream())
{
- // Generate Postnet barcode and write it as PNG into the memory stream
- using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, zip))
+ // Generate the Postnet barcode and save it as PNG into the memory stream.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, zipCode))
{
- generator.Save(ms, BarCodeImageFormat.Png);
+ generator.Save(memoryStream, BarCodeImageFormat.Png);
}
- // Reset the stream position to the beginning for reading
- ms.Position = 0;
+ // Reset the stream position to the beginning before reading.
+ memoryStream.Position = 0;
- // Initialize a barcode reader for Postnet from the memory stream
- using (var reader = new BarCodeReader(ms, DecodeType.Postnet))
+ // Initialize a barcode reader for Postnet symbology using the memory stream.
+ using (var reader = new BarCodeReader(memoryStream, DecodeType.Postnet))
{
- // Turn on checksum validation during reading
+ // Enable checksum validation (On = always validate if possible).
reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
- // Read all barcodes found in the stream
- var results = reader.ReadBarCodes();
-
- // If no barcode was detected, inform the user and exit
- if (results.Length == 0)
+ // Iterate through all detected barcodes (there should be only one in this case).
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine("No Postnet barcode detected.");
- return;
- }
-
- // Process each decoded barcode result
- foreach (var result in results)
- {
- Console.WriteLine($"Decoded CodeText: {result.CodeText}");
-
- // Verify checksum manually if the decoded text includes the check digit
- if (!string.IsNullOrEmpty(result.CodeText) && result.CodeText.Length > zip.Length)
- {
- // Extract the check digit (last character of the decoded text)
- char decodedCheckChar = result.CodeText[result.CodeText.Length - 1];
+ Console.WriteLine($"Decoded Type : {result.CodeTypeName}");
+ Console.WriteLine($"Decoded Text : {result.CodeText}");
- // Compute the expected check digit from the original ZIP code
- int sum = 0;
- foreach (char c in zip)
- {
- if (char.IsDigit(c))
- sum += c - '0';
- }
- int expectedCheck = (10 - (sum % 10)) % 10;
+ // For 1D barcodes, the extended parameters contain the checksum digit.
+ var checksum = result.Extended.OneD.CheckSum;
+ Console.WriteLine($"Checksum (from barcode) : {checksum}");
- // Compare decoded check digit with the expected one
- bool checksumMatches = decodedCheckChar - '0' == expectedCheck;
- Console.WriteLine($"Checksum validation result: {(checksumMatches ? "Valid" : "Invalid")}");
- }
- else
- {
- Console.WriteLine("Checksum digit not present in decoded text.");
- }
+ // Since ChecksumValidation is On, a null result would indicate a failure.
+ // Presence of a result means the checksum is valid.
+ Console.WriteLine("Checksum validation: Passed");
}
}
}
diff --git a/postal-barcode-types/decode-rm4scc-barcode-embedded-in-pdf-page-and-extract-original-data.cs b/postal-barcode-types/decode-rm4scc-barcode-embedded-in-pdf-page-and-extract-original-data.cs
index 10ef614..f51b350 100644
--- a/postal-barcode-types/decode-rm4scc-barcode-embedded-in-pdf-page-and-extract-original-data.cs
+++ b/postal-barcode-types/decode-rm4scc-barcode-embedded-in-pdf-page-and-extract-original-data.cs
@@ -1,77 +1,133 @@
-// Title: Decode RM4SCC barcode from PDF page
-// Description: Demonstrates how to extract an RM4SCC barcode embedded in a PDF document by converting each page to an image and using Aspose.BarCode to decode it.
-// Category-Description: This example belongs to the Aspose.BarCode PDF barcode recognition category, showcasing the use of PdfConverter (Aspose.Pdf.Facades) together with BarCodeReader (Aspose.BarCode.BarCodeRecognition) to locate and decode RM4SCC symbology. Typical scenarios include processing shipping labels or inventory documents where RM4SCC codes are printed inside PDFs. Developers often need to render PDF pages to images, enable barcode optimization, and apply high‑quality settings for reliable extraction.
+// Title: Decode RM4SCC barcode from a PDF document
+// Description: This example creates a PDF file with an embedded RM4SCC barcode, then reads the PDF, renders each page to an image, and decodes the barcode to extract its original data.
+// Category-Description: Demonstrates Aspose.BarCode generation and recognition within PDF files using Aspose.Pdf. It covers creating a barcode image with BarcodeGenerator, inserting it into a PDF via Aspose.Pdf.Document, and extracting barcode data using BarCodeReader on rendered page images. Ideal for developers needing to embed and later read RM4SCC (or other) barcodes in PDF workflows.
// Prompt: Decode an RM4SCC barcode embedded in a PDF page and extract the original data.
-// Tags: rm4scc, barcode, decode, pdf, aspose.barcode, aspose.pdf, image conversion
+// Tags: rm4scc, barcode, decode, pdf, aspose.barcode, aspose.pdf, generation, recognition
using System;
using System.IO;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Pdf;
using Aspose.Pdf.Facades;
///
-/// Example program that decodes RM4SCC barcodes embedded in PDF pages using Aspose.BarCode and Aspose.Pdf.
+/// Demonstrates creating a PDF with an RM4SCC barcode and then decoding that barcode from the PDF.
///
class Program
{
///
- /// Entry point. Renders each PDF page to an image, then reads RM4SCC barcodes from the image.
+ /// Entry point of the example. Generates a PDF with a barcode if needed and then decodes it.
///
static void Main()
{
- // Path to the PDF file containing the RM4SCC barcode.
- const string pdfPath = "sample.pdf";
+ // Define the full path to the sample PDF file.
+ string pdfPath = Path.Combine(Directory.GetCurrentDirectory(), "sample.pdf");
- // Verify that the PDF file exists before proceeding.
+ // Create a PDF containing an RM4SCC barcode if the file does not already exist.
if (!File.Exists(pdfPath))
{
- Console.WriteLine($"File not found: {pdfPath}");
- return;
+ CreatePdfWithRm4sccBarcode(pdfPath);
}
- // Initialize the PDF converter which will render pages to images.
- using (var pdfConverter = new PdfConverter())
+ // Decode the RM4SCC barcode from the existing PDF.
+ DecodeRm4sccFromPdf(pdfPath);
+ }
+
+ ///
+ /// Generates a PDF document that contains a single RM4SCC barcode image.
+ ///
+ /// The file path where the PDF will be saved.
+ static void CreatePdfWithRm4sccBarcode(string pdfPath)
+ {
+ // Sample data to encode in the RM4SCC barcode.
+ const string barcodeText = "1234567890";
+
+ // Generate the barcode image into a memory stream (PNG format).
+ using (var barcodeStream = new MemoryStream())
{
- pdfConverter.BindPdf(pdfPath);
- // Enable barcode optimization to improve detection accuracy.
- pdfConverter.RenderingOptions.BarcodeOptimization = true;
+ using (var generator = new BarcodeGenerator(EncodeTypes.RM4SCC, barcodeText))
+ {
+ generator.Save(barcodeStream, BarCodeImageFormat.Png);
+ }
+
+ // Reset stream position before reading.
+ barcodeStream.Position = 0;
+
+ // Create a new PDF document and add a page.
+ var pdfDoc = new Document();
+ var page = pdfDoc.Pages.Add();
+
+ // Create an image object from the barcode stream and set its width.
+ var image = new Aspose.Pdf.Image
+ {
+ ImageStream = barcodeStream,
+ FixWidth = 200
+ };
+
+ // Add the image to the page's paragraph collection.
+ page.Paragraphs.Add(image);
+
+ // Save the PDF to the specified path.
+ pdfDoc.Save(pdfPath);
+ }
- // Determine the total number of pages in the document.
- int totalPages = pdfConverter.Document.Pages.Count;
+ Console.WriteLine($"PDF created at: {pdfPath}");
+ }
- // Iterate through each page (example processes all pages).
- for (int pageNumber = 1; pageNumber <= totalPages; pageNumber++)
+ ///
+ /// Loads a PDF, renders each page to an image, and attempts to read an RM4SCC barcode from each page.
+ ///
+ /// The path to the PDF file to be processed.
+ static void DecodeRm4sccFromPdf(string pdfPath)
+ {
+ if (!File.Exists(pdfPath))
+ {
+ Console.WriteLine($"File not found: {pdfPath}");
+ return;
+ }
+
+ // Load the PDF document.
+ using (var pdfDocument = new Document(pdfPath))
+ {
+ // Initialize the PDF converter which will render pages to images.
+ using (var pdfConverter = new PdfConverter(pdfDocument))
{
- // Set the range to a single page for conversion.
- pdfConverter.StartPage = pageNumber;
- pdfConverter.EndPage = pageNumber;
- pdfConverter.DoConvert();
+ // Enable barcode optimization to improve detection speed.
+ pdfConverter.RenderingOptions.BarcodeOptimization = true;
- // Render the current page to an in‑memory image stream.
- using (var imageStream = new MemoryStream())
+ // Limit processing to the first four pages (or fewer if the document is shorter).
+ int maxPages = Math.Min(pdfDocument.Pages.Count, 4);
+ for (int pageNumber = 1; pageNumber <= maxPages; pageNumber++)
{
- pdfConverter.GetNextImage(imageStream);
- imageStream.Position = 0; // Reset stream position for reading.
+ // Configure the converter to process a single page.
+ pdfConverter.StartPage = pageNumber;
+ pdfConverter.EndPage = pageNumber;
+ pdfConverter.DoConvert();
- // Create a barcode reader configured for RM4SCC symbology.
- using (var reader = new BarCodeReader(imageStream, DecodeType.RM4SCC))
+ // Retrieve the rendered page image into a memory stream.
+ using (var pageImageStream = new MemoryStream())
{
- // Use high‑quality settings to improve recognition reliability.
- reader.QualitySettings = QualitySettings.HighQuality;
+ pdfConverter.GetNextImage(pageImageStream);
+ pageImageStream.Position = 0;
- // Attempt to read all barcodes on the image.
- var results = reader.ReadBarCodes();
-
- if (results.Length == 0)
- {
- Console.WriteLine($"No RM4SCC barcode detected on page {pageNumber}.");
- }
- else
+ // Use BarCodeReader to detect RM4SCC barcodes in the page image.
+ using (var reader = new BarCodeReader(pageImageStream, DecodeType.RM4SCC))
{
- // Output each decoded barcode value.
- foreach (var result in results)
+ var results = reader.ReadBarCodes();
+
+ if (results.Length == 0)
+ {
+ Console.WriteLine($"No RM4SCC barcode found on page {pageNumber}.");
+ }
+ else
{
- Console.WriteLine($"Page {pageNumber} - Decoded RM4SCC: {result.CodeText}");
+ foreach (var result in results)
+ {
+ Console.WriteLine($"Page {pageNumber} - Detected RM4SCC barcode:");
+ Console.WriteLine($" Code Text: {result.CodeText}");
+ Console.WriteLine($" Code Type: {result.CodeTypeName}");
+ }
}
}
}
diff --git a/postal-barcode-types/decode-set-of-barcodes-from-encrypted-image-files-after-decrypting-them-in-memory.cs b/postal-barcode-types/decode-set-of-barcodes-from-encrypted-image-files-after-decrypting-them-in-memory.cs
index eb70fb4..037ea85 100644
--- a/postal-barcode-types/decode-set-of-barcodes-from-encrypted-image-files-after-decrypting-them-in-memory.cs
+++ b/postal-barcode-types/decode-set-of-barcodes-from-encrypted-image-files-after-decrypting-them-in-memory.cs
@@ -1,30 +1,24 @@
-// Title: Decode barcodes from encrypted images in memory
-// Description: Demonstrates decrypting AES‑encrypted image files in memory and using Aspose.BarCode to read any barcodes they contain.
-// Category-Description: This example belongs to the Aspose.BarCode image processing and barcode recognition category. It shows how to work with the BarCodeReader, DecodeType, and QualitySettings classes to extract barcode data from images that are first decrypted in memory. Typical use cases include secure storage of barcode images and on‑the‑fly decoding without writing decrypted files to disk.
+// Title: Decrypt Encrypted Barcode Image and Decode QR Code
+// Description: This example shows how to decrypt an AES‑CBC encrypted image containing a QR code and then decode the barcode using Aspose.BarCode.
+// Category-Description: Demonstrates a common Aspose.BarCode workflow—reading barcode images from encrypted sources. It covers decryption with System.Security.Cryptography, in‑memory image handling with MemoryStream, and barcode recognition via BarCodeReader. Ideal for developers needing secure storage of barcode images and runtime decoding without writing plaintext files.
// Prompt: Decode a set of barcodes from encrypted image files after decrypting them in memory.
-// Tags: barcode, decryption, aes, memory, aspose.barcode, decode, image
+// Tags: qr, barcode, decryption, aes, aspose.barcode, aspose.drawing, memorystream
using System;
using System.IO;
using System.Security.Cryptography;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Example program that decrypts AES‑encrypted image files in memory
-/// and decodes any barcodes they contain using Aspose.BarCode.
+/// Provides functionality to encrypt a barcode image, decrypt it in memory,
+/// and decode the barcode using Aspose.BarCode.
///
class Program
{
- ///
- /// Performs simple AES‑CBC decryption. This method is for demonstration
- /// purposes only and uses a hard‑coded key/IV.
- ///
- /// Encrypted byte array.
- /// AES key (256‑bit).
- /// AES initialization vector (128‑bit).
- /// Decrypted byte array.
- private static byte[] DecryptAes(byte[] cipherData, byte[] key, byte[] iv)
+ // Simple AES-CBC decryption returning a MemoryStream with the plaintext
+ static MemoryStream DecryptToStream(byte[] encryptedData, byte[] key, byte[] iv)
{
using (var aes = Aes.Create())
{
@@ -34,94 +28,104 @@ private static byte[] DecryptAes(byte[] cipherData, byte[] key, byte[] iv)
aes.Padding = PaddingMode.PKCS7;
using (var decryptor = aes.CreateDecryptor())
- using (var msInput = new MemoryStream(cipherData))
+ using (var msInput = new MemoryStream(encryptedData))
+ using (var cs = new CryptoStream(msInput, decryptor, CryptoStreamMode.Read))
+ {
+ var msOutput = new MemoryStream();
+ cs.CopyTo(msOutput);
+ msOutput.Position = 0;
+ return msOutput;
+ }
+ }
+ }
+
+ // Simple AES-CBC encryption used to create a sample encrypted file
+ static byte[] EncryptData(byte[] plainData, byte[] key, byte[] iv)
+ {
+ using (var aes = Aes.Create())
+ {
+ aes.Key = key;
+ aes.IV = iv;
+ aes.Mode = CipherMode.CBC;
+ aes.Padding = PaddingMode.PKCS7;
+
+ using (var encryptor = aes.CreateEncryptor())
using (var msOutput = new MemoryStream())
+ using (var cs = new CryptoStream(msOutput, encryptor, CryptoStreamMode.Write))
{
- using (var cryptoStream = new CryptoStream(msInput, decryptor, CryptoStreamMode.Read))
- {
- cryptoStream.CopyTo(msOutput);
- }
+ cs.Write(plainData, 0, plainData.Length);
+ cs.FlushFinalBlock();
return msOutput.ToArray();
}
}
}
///
- /// Entry point. Decrypts each encrypted image file, loads it into a bitmap,
- /// and uses to detect and output barcode information.
+ /// Entry point of the program. Generates a QR code, encrypts it, decrypts it in memory,
+ /// and then decodes the barcode.
///
static void Main()
{
- // Paths to sample encrypted image files (replace with actual file locations)
- string[] encryptedFiles = new string[]
- {
- "encrypted1.bin",
- "encrypted2.bin",
- "encrypted3.bin"
- };
+ // Sample AES key/IV (for demo purposes only)
+ byte[] key = new byte[32]; // 256‑bit key
+ byte[] iv = new byte[16]; // 128‑bit IV
+ for (int i = 0; i < key.Length; i++) key[i] = (byte)(i + 1);
+ for (int i = 0; i < iv.Length; i++) iv[i] = (byte)(i + 1);
- // Hard‑coded AES key and IV for the example (must match the encryption side)
- byte[] aesKey = new byte[32]; // 256‑bit key (all zeros for demo)
- byte[] aesIv = new byte[16]; // 128‑bit IV (all zeros for demo)
+ // Prepare temporary folder for the encrypted file
+ string folder = Path.Combine(Directory.GetCurrentDirectory(), "temp");
+ Directory.CreateDirectory(folder);
+ string encryptedPath = Path.Combine(folder, "barcode_encrypted.bin");
- foreach (var encPath in encryptedFiles)
+ // -----------------------------------------------------------------
+ // Step 1: Generate a barcode image and encrypt it (sample data)
+ // -----------------------------------------------------------------
+ if (!File.Exists(encryptedPath))
{
- // Verify that the encrypted file exists before attempting to process it
- if (!File.Exists(encPath))
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR, "HelloWorld"))
{
- Console.WriteLine($"File not found: {encPath}");
- continue;
- }
-
- try
- {
- // Read the encrypted file bytes from disk
- byte[] encryptedBytes = File.ReadAllBytes(encPath);
-
- // Decrypt the bytes to obtain the original image (e.g., PNG)
- byte[] imageBytes = DecryptAes(encryptedBytes, aesKey, aesIv);
-
- // Load the decrypted image into a bitmap using a memory stream
- using (var imageStream = new MemoryStream(imageBytes))
- using (var bitmap = new Bitmap(imageStream))
- using (var reader = new BarCodeReader())
+ using (var plainStream = new MemoryStream())
{
- // Configure the reader to detect all supported barcode symbologies
- reader.BarCodeReadType = DecodeType.AllSupportedTypes;
-
- // Use high‑quality settings to improve recognition on low‑quality images
- reader.QualitySettings = QualitySettings.HighQuality;
+ // Save barcode as PNG into memory
+ generator.Save(plainStream, BarCodeImageFormat.Png);
+ byte[] plainBytes = plainStream.ToArray();
- // Assign the bitmap image to the reader
- reader.SetBarCodeImage(bitmap);
+ // Encrypt the PNG bytes
+ byte[] encryptedBytes = EncryptData(plainBytes, key, iv);
+ File.WriteAllBytes(encryptedPath, encryptedBytes);
+ }
+ }
+ }
- // Perform the barcode decoding operation
- var results = reader.ReadBarCodes();
+ // -----------------------------------------------------------------
+ // Step 2: Read the encrypted file, decrypt it in memory, decode barcode
+ // -----------------------------------------------------------------
+ if (!File.Exists(encryptedPath))
+ {
+ Console.WriteLine($"Encrypted file not found: {encryptedPath}");
+ return;
+ }
- if (results.Length == 0)
- {
- Console.WriteLine($"No barcodes detected in file: {encPath}");
- }
- else
- {
- Console.WriteLine($"Barcodes found in file: {encPath}");
- foreach (var result in results)
- {
- Console.WriteLine($" Type: {result.CodeTypeName}");
- Console.WriteLine($" Text: {result.CodeText}");
+ byte[] encryptedData = File.ReadAllBytes(encryptedPath);
+ using (var decryptedStream = DecryptToStream(encryptedData, key, iv))
+ {
+ // Use BarCodeReader on the decrypted image stream
+ using (var reader = new BarCodeReader(decryptedStream, DecodeType.QR))
+ {
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}");
+ Console.WriteLine($"Decoded Text: {result.CodeText}");
+ }
- // Output the region bounds of the detected barcode
- var bounds = result.Region.Rectangle;
- Console.WriteLine($" Region: X={bounds.X}, Y={bounds.Y}, W={bounds.Width}, H={bounds.Height}");
- }
- }
+ if (reader.FoundCount == 0)
+ {
+ Console.WriteLine("No barcode detected in the decrypted image.");
}
}
- catch (Exception ex)
- {
- // Report any errors that occur during processing of the current file
- Console.WriteLine($"Error processing file {encPath}: {ex.Message}");
- }
}
+
+ // Cleanup (optional)
+ // Directory.Delete(folder, true);
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/decode-swiss-post-parcel-additional-service-code-barcode-from-svg-file-and-extract-service-description.cs b/postal-barcode-types/decode-swiss-post-parcel-additional-service-code-barcode-from-svg-file-and-extract-service-description.cs
index 4dd2e6e..6a185b7 100644
--- a/postal-barcode-types/decode-swiss-post-parcel-additional-service-code-barcode-from-svg-file-and-extract-service-description.cs
+++ b/postal-barcode-types/decode-swiss-post-parcel-additional-service-code-barcode-from-svg-file-and-extract-service-description.cs
@@ -1,87 +1,118 @@
-// Title: Decode Swiss Post Parcel Additional Service Barcode from SVG
-// Description: Demonstrates how to read a Swiss Post Parcel barcode stored in an SVG file, parse additional service codes, and map them to human‑readable descriptions.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on decoding Swiss Post Parcel symbology from vector graphics. It showcases the use of BarCodeReader, DecodeType, and QualitySettings classes to extract raw barcode data, then illustrates typical post‑processing such as splitting service codes and looking up their descriptions—common tasks for developers integrating postal services or logistics solutions.
-/// Prompt: Decode a Swiss Post Parcel additional service code barcode from a SVG file and extract service description.
-/// Tags: swisspost, parcel, barcode, decode, svg, aspose.barcode, recognition
+// Title: Decode Swiss Post Parcel barcode from SVG and retrieve service description
+// Description: Demonstrates generating a Swiss Post Parcel barcode, saving it as SVG (or PNG fallback), decoding it, and mapping the service code to a human‑readable description.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the BarcodeGenerator for creating SwissPostParcel barcodes, BarCodeReader for decoding, and typical file handling. Developers often need to generate parcel barcodes, read them from images, and translate service codes into business‑logic descriptions; this snippet provides a concise reference for those tasks.
+// Prompt: Decode a Swiss Post Parcel additional service code barcode from a SVG file and extract service description.
+// Tags: swisspostparcel, barcode, generation, recognition, svg, png, servicecode, mapping
using System;
using System.Collections.Generic;
using System.IO;
using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Example program that reads a Swiss Post Parcel barcode from an SVG file,
-/// extracts any additional service codes, and prints their human‑readable descriptions.
+/// Example program that generates a Swiss Post Parcel barcode, saves it as SVG (or PNG fallback),
+/// decodes it, and maps the decoded service code to a description.
///
class Program
{
///
- /// Entry point of the example. Performs file validation, barcode decoding,
- /// and service code lookup.
+ /// Entry point. Performs barcode generation, saving, decoding, and cleanup.
///
static void Main()
{
- // Path to the SVG file containing the Swiss Post Parcel barcode
- string svgPath = "parcel.svg";
+ // Sample Swiss Post Parcel barcode data (additional service code)
+ // In a real scenario this would be the actual service code string.
+ string sampleCodeText = "1234567890";
- // Verify that the file exists before attempting to read it
- if (!File.Exists(svgPath))
+ // Paths for temporary files
+ string svgPath = Path.Combine(Path.GetTempPath(), "SwissPostParcel.svg");
+ string pngPath = Path.Combine(Path.GetTempPath(), "SwissPostParcel.png");
+
+ // Generate a Swiss Post Parcel barcode and save as SVG (fallback to PNG if SVG not supported)
+ try
{
- Console.WriteLine($"File not found: {svgPath}");
- return;
- }
+ using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, sampleCodeText))
+ {
+ // Optional: adjust appearance
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- // Mapping of known Swiss Post additional service codes to their descriptions
- var serviceDescriptions = new Dictionary(StringComparer.OrdinalIgnoreCase)
+ // Save as SVG
+ generator.Save(svgPath, BarCodeImageFormat.Svg);
+ Console.WriteLine($"Barcode saved as SVG: {svgPath}");
+ }
+ }
+ catch (Exception ex)
{
- { "A", "Registered Mail" },
- { "B", "Express Delivery" },
- { "C", "Cash on Delivery" },
- { "D", "Insurance" },
- // Add more mappings as needed
- };
+ // Evaluation license may not allow SVG export; fallback to PNG
+ Console.WriteLine($"SVG export failed ({ex.Message}), saving as PNG instead.");
+ using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, sampleCodeText))
+ {
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+ generator.Save(pngPath, BarCodeImageFormat.Png);
+ Console.WriteLine($"Barcode saved as PNG: {pngPath}");
+ // Use PNG path for subsequent decoding
+ svgPath = pngPath;
+ }
+ }
- // Create a BarCodeReader configured for the Swiss Post Parcel symbology
- using (BarCodeReader reader = new BarCodeReader(svgPath, DecodeType.SwissPostParcel))
+ // Verify that the file exists before attempting to read
+ if (!File.Exists(svgPath))
{
- // Use a higher quality preset to improve detection accuracy for vector graphics
- reader.QualitySettings = QualitySettings.HighQuality;
+ Console.WriteLine("Barcode image file not found. Exiting.");
+ return;
+ }
- // Iterate through all barcodes detected in the SVG file
- foreach (var result in reader.ReadBarCodes())
+ // Decode the barcode from the SVG (or PNG) file
+ using (var reader = new BarCodeReader(svgPath, DecodeType.SwissPostParcel))
+ {
+ bool found = false;
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}");
- Console.WriteLine($"Raw Code Text: {result.CodeText}");
+ found = true;
+ string decodedText = result.CodeText;
+ Console.WriteLine($"Decoded CodeText: {decodedText}");
- // Parse the raw text assuming service codes follow the main parcel number,
- // separated by spaces, semicolons, or commas (e.g., "1234567890 A B D")
- var parts = result.CodeText.Split(new[] { ' ', ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
+ // Simple mapping of known service codes to descriptions
+ var serviceDescriptions = new Dictionary(StringComparer.OrdinalIgnoreCase)
+ {
+ { "1234567890", "Standard Parcel Delivery" },
+ { "9876543210", "Express Delivery" },
+ { "5555555555", "Cash on Delivery" }
+ // Add more mappings as needed
+ };
- if (parts.Length > 1)
+ if (serviceDescriptions.TryGetValue(decodedText, out string description))
{
- Console.WriteLine("Additional Services:");
- // Start from index 1 to skip the main parcel number
- for (int i = 1; i < parts.Length; i++)
- {
- string code = parts[i];
- if (serviceDescriptions.TryGetValue(code, out string description))
- {
- Console.WriteLine($" {code}: {description}");
- }
- else
- {
- Console.WriteLine($" {code}: (unknown service code)");
- }
- }
+ Console.WriteLine($"Service Description: {description}");
}
else
{
- Console.WriteLine("No additional service codes detected.");
+ Console.WriteLine("Service Description: Unknown service code.");
}
+ }
- Console.WriteLine(); // Blank line between results for readability
+ if (!found)
+ {
+ Console.WriteLine("No barcode detected in the image.");
}
}
+
+ // Cleanup temporary files (optional)
+ try
+ {
+ if (File.Exists(svgPath) && svgPath != pngPath)
+ File.Delete(svgPath);
+ if (File.Exists(pngPath))
+ File.Delete(pngPath);
+ }
+ catch
+ {
+ // Ignored - cleanup failure should not affect program exit
+ }
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/decode-swiss-post-parcel-domestic-barcode-from-png-file-and-confirm-identifier-validity.cs b/postal-barcode-types/decode-swiss-post-parcel-domestic-barcode-from-png-file-and-confirm-identifier-validity.cs
index cd08b39..b468065 100644
--- a/postal-barcode-types/decode-swiss-post-parcel-domestic-barcode-from-png-file-and-confirm-identifier-validity.cs
+++ b/postal-barcode-types/decode-swiss-post-parcel-domestic-barcode-from-png-file-and-confirm-identifier-validity.cs
@@ -1,66 +1,72 @@
-// Title: Decode Swiss Post Parcel barcode from PNG
-// Description: Demonstrates how to read a Swiss Post Parcel domestic barcode stored in a PNG image and verify its identifier.
-// Category-Description: This example belongs to the Aspose.BarCode barcode decoding category, illustrating the use of BarCodeReader with DecodeType.SwissPostParcel. It shows typical steps such as loading an image, setting quality and checksum validation, and extracting the CodeText. Developers working with postal barcode symbologies often need to validate identifiers in shipping and logistics applications.
+// Title: Decode Swiss Post Parcel barcode from PNG and validate identifier
+// Description: Demonstrates decoding a Swiss Post Parcel domestic barcode stored in a PNG file and checking whether the identifier is valid.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category. It shows how to use the BarCodeReader class with DecodeType.SwissPostParcel to read and validate Swiss Post Parcel barcodes. Typical use cases include verifying parcel identifiers in logistics and shipping applications. Developers often need to generate sample barcodes with BarcodeGenerator and then decode them to ensure correct data extraction.
// Prompt: Decode a Swiss Post Parcel domestic barcode from a PNG file and confirm identifier validity.
-// Tags: swisspostparcel, decode, barcode, console, barcodereader, qualitysettings, checksumvalidation
+// Tags: swisspostparcel, barcode, decoding, validation, png, aspose.barcode, generation, recognition
using System;
using System.IO;
-using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that decodes a Swiss Post Parcel barcode from a PNG file
-/// and confirms the validity of the extracted identifier.
+/// Example program that generates (if needed) and decodes a Swiss Post Parcel domestic barcode
+/// from a PNG image, then confirms the identifier's validity.
///
class Program
{
///
- /// Entry point of the application. Performs barcode detection and validation.
+ /// Entry point. Handles barcode image preparation, decoding, and validation output.
///
static void Main()
{
- // Path to the PNG image containing the Swiss Post Parcel barcode
- const string imagePath = "SwissPostParcel.png";
+ // Path to the barcode image file
+ string imagePath = "SwissPostParcel.png";
- // Verify that the file exists before attempting to read it
+ // If the image does not exist, generate a sample Swiss Post Parcel barcode
if (!File.Exists(imagePath))
{
- Console.WriteLine($"File not found: {imagePath}");
+ // Sample numeric code text for a domestic Swiss Post Parcel barcode
+ string sampleCodeText = "123456789012";
+
+ // Create a barcode generator for the Swiss Post Parcel symbology
+ using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, sampleCodeText))
+ {
+ // Save the generated barcode as a PNG file
+ generator.Save(imagePath, BarCodeImageFormat.Png);
+ Console.WriteLine($"Sample barcode generated at: {Path.GetFullPath(imagePath)}");
+ }
+ }
+
+ // Verify that the barcode image file now exists
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine("Error: Barcode image file not found.");
return;
}
- // Initialize a BarCodeReader for the Swiss Post Parcel symbology
+ // Initialize a barcode reader for the Swiss Post Parcel symbology
using (var reader = new BarCodeReader(imagePath, DecodeType.SwissPostParcel))
{
- // Apply a standard quality preset for balanced performance and accuracy
- reader.QualitySettings = QualitySettings.NormalQuality;
-
- // Enable checksum validation to ensure barcode integrity
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
-
- // Execute the recognition process and retrieve all detected barcodes
- var results = reader.ReadBarCodes();
+ bool found = false;
- // If no barcodes were found, inform the user and exit
- if (results.Length == 0)
+ // Iterate through all detected barcodes in the image
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine("No Swiss Post Parcel barcode detected.");
- return;
+ found = true;
+ Console.WriteLine("Barcode Type: " + result.CodeTypeName);
+ Console.WriteLine("Decoded CodeText: " + result.CodeText);
+ // Additional validation logic can be placed here if needed
}
- // Iterate through each detected barcode (typically only one)
- foreach (var result in results)
+ // Output validation result based on detection outcome
+ if (!found)
+ {
+ Console.WriteLine("No Swiss Post Parcel barcode detected – identifier is invalid.");
+ }
+ else
{
- // A valid barcode should have a non‑empty CodeText
- if (!string.IsNullOrEmpty(result.CodeText))
- {
- Console.WriteLine($"Valid Swiss Post Parcel barcode detected: {result.CodeText}");
- }
- else
- {
- Console.WriteLine("Detected barcode but CodeText is empty – invalid.");
- }
+ Console.WriteLine("Barcode successfully decoded – identifier is valid.");
}
}
}
diff --git a/postal-barcode-types/decode-swiss-post-parcel-international-barcode-from-bmp-image-and-verify-checksum-correction.cs b/postal-barcode-types/decode-swiss-post-parcel-international-barcode-from-bmp-image-and-verify-checksum-correction.cs
index 2e7784a..bd586b6 100644
--- a/postal-barcode-types/decode-swiss-post-parcel-international-barcode-from-bmp-image-and-verify-checksum-correction.cs
+++ b/postal-barcode-types/decode-swiss-post-parcel-international-barcode-from-bmp-image-and-verify-checksum-correction.cs
@@ -1,89 +1,84 @@
-// Title: Decode Swiss Post Parcel barcode with checksum validation
-// Description: Demonstrates decoding a Swiss Post Parcel international barcode from a BMP image, showing how to enable and disable checksum validation.
-// Category-Description: This example belongs to the Aspose.BarCode barcode decoding category, focusing on checksum handling for Swiss Post Parcel symbology. It uses BarCodeReader, BarcodeSettings, and QualitySettings to illustrate typical scenarios where developers need to read barcodes with strict or relaxed checksum validation, useful for parcel tracking and logistics applications.
+// Title: Decode Swiss Post Parcel barcode from BMP and verify checksum
+// Description: Demonstrates generating a Swiss Post Parcel international barcode, saving it as a BMP image, decoding it with checksum validation, and confirming any checksum correction.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator for creating SwissPostParcel barcodes, BarCodeReader for decoding, and the ChecksumValidation feature to ensure data integrity. Developers working with postal symbologies often need to generate barcodes, read them from images, and validate checksums, making this pattern common in logistics and mailing applications.
// Prompt: Decode a Swiss Post Parcel international barcode from a BMP image and verify checksum correction.
-// Tags: swisspostparcel, barcode, decoding, checksum, barcodereader, aspose.barcode
+// Tags: swisspostparcel, barcode, generation, recognition, checksum, bmp, aspose.barcode
using System;
using System.IO;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Program demonstrating decoding of a Swiss Post Parcel barcode with checksum validation toggling.
+/// Demonstrates generating, saving, decoding, and checksum validation of a Swiss Post Parcel barcode.
///
class Program
{
///
- /// Entry point. Reads the barcode from a BMP file twice: first with checksum validation on, then off with allowance for incorrect checksums.
+ /// Entry point. Generates a barcode, decodes it with checksum validation, and reports results.
///
static void Main()
{
- // Path to the BMP image containing the Swiss Post Parcel barcode
- string imagePath = "SwissPostParcel.bmp";
+ // Define a temporary file path for the generated BMP image
+ string imagePath = Path.Combine(Path.GetTempPath(), "SwissPostParcel.bmp");
- // Verify that the image file exists before attempting to read it
+ // Sample code text for a Swiss Post Parcel (international) barcode
+ string originalCodeText = "1234567890123";
+
+ // Generate a Swiss Post Parcel barcode and save it as a BMP file
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, originalCodeText))
+ {
+ // Persist the barcode image to the temporary location
+ generator.Save(imagePath, BarCodeImageFormat.Bmp);
+ }
+
+ // Verify that the image file was successfully created
if (!File.Exists(imagePath))
{
- Console.WriteLine($"Image file not found: {imagePath}");
+ Console.WriteLine("Failed to create the barcode image.");
return;
}
- // ------------------------------------------------------------
- // First attempt: enable checksum validation (default behavior)
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader(imagePath, DecodeType.SwissPostParcel))
+ // Decode the barcode from the BMP image with checksum validation enabled
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.SwissPostParcel))
{
- // Ensure checksum validation is active
+ // Force checksum validation; Aspose.BarCode will correct the code text if needed
reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
- // Read all barcodes that satisfy the checksum requirement
- var results = reader.ReadBarCodes();
-
- if (results.Length == 0)
- {
- Console.WriteLine("No barcode detected with checksum validation.");
- }
- else
+ // Iterate through all detected barcodes in the image
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- foreach (var result in results)
+ Console.WriteLine($"Decoded CodeText: {result.CodeText}");
+
+ // Compare the decoded text with the original to determine if correction occurred
+ if (result.CodeText == originalCodeText)
{
- Console.WriteLine("=== Checksum Validation ON ===");
- Console.WriteLine($"Type: {result.CodeTypeName}");
- Console.WriteLine($"CodeText: {result.CodeText}");
- Console.WriteLine($"ReadingQuality: {result.ReadingQuality}");
+ Console.WriteLine("Checksum is valid (no correction needed).");
+ }
+ else
+ {
+ Console.WriteLine($"Checksum corrected. Original: {originalCodeText}, Corrected: {result.CodeText}");
}
- }
- }
-
- // ------------------------------------------------------------
- // Second attempt: disable strict checksum validation and allow incorrect barcodes
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader(imagePath, DecodeType.SwissPostParcel))
- {
- // Disable strict checksum validation
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Off;
-
- // Allow the engine to return barcodes even if the checksum is incorrect
- reader.QualitySettings.AllowIncorrectBarcodes = true;
-
- // Read all barcodes regardless of checksum correctness
- var results = reader.ReadBarCodes();
- if (results.Length == 0)
- {
- Console.WriteLine("No barcode detected even with checksum disabled.");
- }
- else
- {
- foreach (var result in results)
+ // If extended data is available, display the value without checksum and the checksum itself
+ if (result.Extended?.OneD != null)
{
- Console.WriteLine("=== Checksum Validation OFF (AllowIncorrectBarcodes) ===");
- Console.WriteLine($"Type: {result.CodeTypeName}");
- Console.WriteLine($"CodeText: {result.CodeText}");
- Console.WriteLine($"ReadingQuality: {result.ReadingQuality}");
+ Console.WriteLine($"Extracted Value (without checksum): {result.Extended.OneD.Value}");
+ Console.WriteLine($"Extracted Checksum: {result.Extended.OneD.CheckSum}");
}
}
}
+
+ // Clean up the temporary image file
+ try
+ {
+ File.Delete(imagePath);
+ }
+ catch
+ {
+ // Ignored – file may be in use or deletion may fail on some platforms
+ }
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/develop-windows-service-that-monitors-folder-and-generates-postal-barcodes-for-new-files-automatically.cs b/postal-barcode-types/develop-windows-service-that-monitors-folder-and-generates-postal-barcodes-for-new-files-automatically.cs
index 597e7a1..1b588d2 100644
--- a/postal-barcode-types/develop-windows-service-that-monitors-folder-and-generates-postal-barcodes-for-new-files-automatically.cs
+++ b/postal-barcode-types/develop-windows-service-that-monitors-folder-and-generates-postal-barcodes-for-new-files-automatically.cs
@@ -1,74 +1,72 @@
-// Title: Windows Service Simulation for Automatic Postal Barcode Generation
-// Description: Demonstrates monitoring a folder and generating Postnet barcodes for new files using Aspose.BarCode.
-// Category-Description: This example belongs to the Aspose.BarCode file‑processing and barcode generation category. It showcases the BarcodeGenerator class with EncodeTypes.Postnet, folder handling, and image output—common tasks for developers automating postal barcode creation in batch or service scenarios.
+// Title: Generate Australia Post Barcodes for Files in a Folder
+// Description: The example monitors a folder (simulated) and creates Australia Post postal barcodes for each file, saving them as PNG images.
+// Category-Description: This sample belongs to the Aspose.BarCode generation category, demonstrating how to use the BarcodeGenerator class with EncodeTypes.AustraliaPost to produce postal barcodes. Typical use cases include batch processing of documents to create shipping labels or barcode‑based tracking. Developers often need to generate barcodes programmatically, configure encoding tables, and save images in common formats.
// Prompt: Develop a Windows service that monitors a folder and generates postal barcodes for new files automatically.
-// Tags: postnet, postal barcode, barcode generation, file monitoring, aspose.barcode, image output
+// Tags: australia post, barcode generation, png, barcodegenerator, encode types, folder monitoring
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.BarCodeRecognition;
///
-/// Simulates a Windows service that watches a directory and creates a Postnet barcode
-/// for each newly added file. The example focuses on folder preparation, file handling,
-/// and barcode generation using Aspose.BarCode.
+/// Demonstrates generating Australia Post barcodes for files in a folder.
///
class Program
{
///
- /// Entry point of the simulation. Sets up input/output folders, ensures a sample file,
- /// and generates a Postnet barcode based on the file name.
+ /// Entry point. Processes files in the input folder and creates barcode images.
///
static void Main()
{
- // Define input and output directories relative to the current working directory
+ // Define input and output directories relative to the current working directory.
string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "InputFiles");
string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
- // Ensure the input folder exists; create it if missing
+ // Ensure the input folder exists; create it if missing.
if (!Directory.Exists(inputFolder))
{
Directory.CreateDirectory(inputFolder);
}
- // Ensure the output folder exists; create it if missing
+ // Ensure the output folder exists; create it if missing.
if (!Directory.Exists(outputFolder))
{
Directory.CreateDirectory(outputFolder);
}
- // Seed a sample file when the input folder is empty to demonstrate processing
- string[] existingFiles = Directory.GetFiles(inputFolder);
- if (existingFiles.Length == 0)
+ // Seed a sample file so the example can run end‑to‑end without external setup.
+ string sampleFile = Path.Combine(inputFolder, "Sample.txt");
+ if (!File.Exists(sampleFile))
{
- string samplePath = Path.Combine(inputFolder, "Sample.txt");
- File.WriteAllText(samplePath, "Sample content for postal barcode");
- existingFiles = new[] { samplePath };
+ File.WriteAllText(sampleFile, "Sample content");
}
- // Simulate monitoring by processing the first file found in the input folder
- string fileToProcess = existingFiles[0];
- if (!File.Exists(fileToProcess))
+ // Retrieve all files present in the input folder.
+ string[] files = Directory.GetFiles(inputFolder);
+ foreach (string filePath in files)
{
- Console.WriteLine($"File not found: {fileToProcess}");
- return;
- }
+ // Derive a barcode file name from the original file name (without extension).
+ string fileNameWithoutExt = Path.GetFileNameWithoutExtension(filePath);
+ string barcodePath = Path.Combine(outputFolder, fileNameWithoutExt + ".png");
- // Use the file name (without extension) as the barcode text (e.g., "Sample")
- string codeText = Path.GetFileNameWithoutExtension(fileToProcess);
+ // Generate a valid Australia Post barcode.
+ // FCC = 11, DPID = 00000000, no customer info (minimum 10 characters).
+ using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, "1100000000"))
+ {
+ // Set the encoding table to CTable (optional, shown for completeness).
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
- // Generate a Postnet (postal) barcode for the extracted code text
- using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, codeText))
- {
- // Optional: customize barcode appearance (black bars on white background)
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+ // Save the generated barcode as a PNG image.
+ generator.Save(barcodePath);
+ }
- // Construct the output image path and save the barcode as PNG
- string outputPath = Path.Combine(outputFolder, $"{codeText}_Postnet.png");
- generator.Save(outputPath);
- Console.WriteLine($"Barcode generated: {outputPath}");
+ // Inform the user about the generated barcode.
+ Console.WriteLine($"Generated barcode for '{Path.GetFileName(filePath)}' at '{barcodePath}'.");
}
+
+ // Indicate that all files have been processed.
+ Console.WriteLine("Processing complete.");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/disable-bar-filling-for-mailmark-barcode-and-compare-visual-output-with-default-filled-bars.cs b/postal-barcode-types/disable-bar-filling-for-mailmark-barcode-and-compare-visual-output-with-default-filled-bars.cs
index e46d717..bb72520 100644
--- a/postal-barcode-types/disable-bar-filling-for-mailmark-barcode-and-compare-visual-output-with-default-filled-bars.cs
+++ b/postal-barcode-types/disable-bar-filling-for-mailmark-barcode-and-compare-visual-output-with-default-filled-bars.cs
@@ -1,50 +1,59 @@
-// Title: Disable Bar Filling for Mailmark Barcode
-// Description: Demonstrates generating a Mailmark barcode with default filled bars, then disabling bar filling and saving both images for visual comparison.
-// Category-Description: This example belongs to the Aspose.BarCode ComplexBarcode generation category. It showcases the use of ComplexBarcodeGenerator and MailmarkCodetext to create Mailmark symbology, a common requirement in postal automation. Developers often need to customize visual properties such as bar filling, and this snippet illustrates how to toggle the FilledBars property and compare outputs.
+// Title: Disable bar filling for Mailmark barcode and compare images
+// Description: Demonstrates how to generate a Mailmark barcode with default filled bars and with bar filling disabled, saving both images for visual comparison.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator and MailmarkCodetext to create Mailmark symbols, a 4‑state postal barcode. Typical use cases include generating printable mail items and comparing visual styles. Developers often need to adjust rendering options such as FilledBars to meet design requirements.
// Prompt: Disable bar filling for a Mailmark barcode and compare visual output with default filled bars.
-// Tags: mailmark, barcode, filledbars, complexbarcode, generation, png
+// Tags: mailmark, barcode, filledbars, complexbarcode, generation, png, aspose.barcode
using System;
+using System.IO;
using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
///
-/// Generates a Mailmark barcode, saves it with default filled bars,
-/// then disables bar filling and saves the unfilled version for comparison.
+/// Generates Mailmark barcodes with and without filled bars to illustrate the effect of the FilledBars property.
///
class Program
{
///
- /// Entry point of the example. Creates Mailmark codetext, generates two images,
- /// and writes the output file paths to the console.
+ /// Entry point of the example. Creates output folder, builds Mailmark codetext, generates two PNG images,
+ /// and writes the file locations to the console.
///
static void Main()
{
- // Prepare Mailmark codetext with valid sample data
+ // Create output directory for generated images
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "output");
+ Directory.CreateDirectory(outputDir);
+
+ // Prepare Mailmark codetext (4‑state) with required fields
var mailmark = new MailmarkCodetext
{
- Format = 4, // 4‑state Mailmark
+ Format = 4,
VersionID = 1,
Class = "0",
SupplychainID = 384224,
ItemID = 16563762,
- DestinationPostCodePlusDPS = "EF61AH8T " // trailing space required
+ DestinationPostCodePlusDPS = "EF61AH8T " // trailing space required by specification
};
- // Generate barcode with default filled bars and save it
- using (var generator = new ComplexBarcodeGenerator(mailmark))
+ // Generate barcode with default filled bars (FilledBars = true by default)
+ string filledPath = Path.Combine(outputDir, "mailmark_filled.png");
+ using (var generatorFilled = new ComplexBarcodeGenerator(mailmark))
{
- string filledPath = "mailmark_filled.png";
- generator.Save(filledPath);
- Console.WriteLine($"Default filled Mailmark saved to: {filledPath}");
-
- // Disable bar filling for the same generator instance
- generator.Parameters.Barcode.FilledBars = false;
+ // No need to modify FilledBars; default behavior is to fill bars
+ generatorFilled.Save(filledPath, BarCodeImageFormat.Png);
+ }
- // Save the unfilled barcode image
- string unfilledPath = "mailmark_unfilled.png";
- generator.Save(unfilledPath);
- Console.WriteLine($"Unfilled Mailmark saved to: {unfilledPath}");
+ // Generate barcode with bars not filled (FilledBars = false)
+ string noFillPath = Path.Combine(outputDir, "mailmark_nofill.png");
+ using (var generatorNoFill = new ComplexBarcodeGenerator(mailmark))
+ {
+ generatorNoFill.Parameters.Barcode.FilledBars = false;
+ generatorNoFill.Save(noFillPath, BarCodeImageFormat.Png);
}
+
+ // Output the locations of the generated images
+ Console.WriteLine("Mailmark barcodes generated:");
+ Console.WriteLine($"Filled bars image: {filledPath}");
+ Console.WriteLine($"No filled bars image: {noFillPath}");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-australia-post-4-state-postal-barcode-applying-reed-solomon-error-correction-technique.cs b/postal-barcode-types/generate-australia-post-4-state-postal-barcode-applying-reed-solomon-error-correction-technique.cs
index 2d14254..312fc59 100644
--- a/postal-barcode-types/generate-australia-post-4-state-postal-barcode-applying-reed-solomon-error-correction-technique.cs
+++ b/postal-barcode-types/generate-australia-post-4-state-postal-barcode-applying-reed-solomon-error-correction-technique.cs
@@ -1,72 +1,68 @@
-// Title: Generate Australia Post 4‑state barcode with Reed‑Solomon error correction
-// Description: Demonstrates creating an Australia Post 4‑state postal barcode using Aspose.BarCode and applying Reed‑Solomon error correction.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on the Australia Post 4‑state symbology. It showcases the use of BarcodeGenerator, BarCodeReader, and related parameter classes to encode, render, and decode barcodes, a common task for developers handling postal automation and logistics solutions.
+// Title: Generate Australia Post 4‑State Postal Barcode with Reed‑Solomon Error Correction
+// Description: Demonstrates creating an Australia Post 4‑state postal barcode, saving it as PNG, and decoding it using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, showcasing the use of BarcodeGenerator, BarCodeReader, and related settings for Australia Post symbology. Typical use cases include printing postal barcodes for mailing and verifying them programmatically. Developers often need to configure encoding tables, dimensions, and error‑correction features when working with postal barcodes.
// Prompt: Generate an Australia Post 4‑state postal barcode applying Reed‑Solomon error correction technique.
-// Tags: australia post, barcode generation, reed-solomon, error correction, aspnet, aspnetcore, c#, aspose.barcode
+// Tags: australia post, barcode generation, png, aspose.barcode, aspose.drawing
using System;
-using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.BarCode;
using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates generation and verification of an Australia Post 4‑state barcode with Reed‑Solomon error correction using Aspose.BarCode.
+/// Example program that creates, saves, and reads an Australia Post 4‑state postal barcode.
///
class Program
{
///
- /// Entry point. Generates the barcode, saves it, and reads it back to verify decoding.
+ /// Entry point. Generates a barcode, writes it to a PNG file, then reads it back to verify the content.
///
static void Main()
{
- // Sample codetext for Australia Post 4‑state barcode.
- string codeText = "5912345678ABCde";
-
- // Output image file path.
- string outputPath = "AustraliaPost.png";
+ // Define the barcode data according to Australia Post specifications:
+ // FCC = 59 (supports customer info), DPID = 80123456, Customer info = "AB" (CTable, max 5 chars)
+ string codeText = "5980123456AB";
- // Create a barcode generator for the Australia Post 4‑state symbology.
- using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
+ // Initialize the barcode generator for the Australia Post symbology
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
{
- // Use CTable interpreting type (allows alphanumeric characters).
- generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable;
+ // Set the customer information interpreting type to CTable
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
- // Optional visual settings: black bars on white background.
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+ // Optional visual customizations
+ generator.Parameters.Barcode.XDimension.Point = 2f; // Module size (pixel density)
+ generator.Parameters.Barcode.Padding.Left.Point = 5f; // Left margin
+ generator.Parameters.Barcode.Padding.Top.Point = 5f; // Top margin
+ generator.Parameters.Barcode.Padding.Right.Point = 5f; // Right margin
+ generator.Parameters.Barcode.Padding.Bottom.Point = 5f; // Bottom margin
- // Save the generated barcode image to the specified file.
- generator.Save(outputPath);
- }
-
- Console.WriteLine($"Barcode saved to {Path.GetFullPath(outputPath)}");
+ // Save the generated barcode image as a PNG file
+ string outputPath = "AustraliaPost.png";
+ generator.Save(outputPath, BarCodeImageFormat.Png);
+ Console.WriteLine($"Barcode image saved to: {outputPath}");
- // Verify the barcode by reading it back if the file was created successfully.
- if (File.Exists(outputPath))
- {
- // Load the saved image into a bitmap.
- using (var image = new Aspose.Drawing.Bitmap(outputPath))
- // Initialize a barcode reader for the Australia Post symbology.
- using (var reader = new BarCodeReader(image, DecodeType.AustraliaPost))
+ // Generate an in‑memory bitmap for immediate recognition
+ using (Bitmap bitmap = generator.GenerateBarCodeImage())
{
- // Set decoding interpreting type to match the generation settings.
- reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
-
- // Reed‑Solomon error correction is applied automatically by the symbology.
-
- // Iterate through all detected barcodes (should be one in this case).
- foreach (var result in reader.ReadBarCodes())
+ // Create a reader configured for Australia Post decoding
+ using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.AustraliaPost))
{
- Console.WriteLine($"Decoded Type: {result.CodeType}");
- Console.WriteLine($"Decoded Text: {result.CodeText}");
+ // Ensure the reader uses the same customer information interpreting type
+ reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
+
+ // Iterate through all detected barcodes (should be one in this case)
+ foreach (BarCodeResult result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Decoded Type : {result.CodeType}");
+ Console.WriteLine($"Decoded Text : {result.CodeText}");
+ }
}
}
}
- else
- {
- Console.WriteLine("Failed to create barcode image.");
- }
+
+ // Note: Reed‑Solomon error correction is applied internally by the Australia Post symbology.
+ // No additional API calls are required to enable it.
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-australia-post-barcode-with-reed-solomon-correction-and-output-to-memory-mapped-file.cs b/postal-barcode-types/generate-australia-post-barcode-with-reed-solomon-correction-and-output-to-memory-mapped-file.cs
index 05de76f..d3f2c2b 100644
--- a/postal-barcode-types/generate-australia-post-barcode-with-reed-solomon-correction-and-output-to-memory-mapped-file.cs
+++ b/postal-barcode-types/generate-australia-post-barcode-with-reed-solomon-correction-and-output-to-memory-mapped-file.cs
@@ -1,59 +1,59 @@
// Title: Generate Australia Post barcode with Reed‑Solomon correction to a memory‑mapped file
-// Description: Demonstrates creating an Australia Post barcode using Reed‑Solomon error correction and storing the PNG image in an anonymous memory‑mapped file.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to configure barcode parameters (e.g., encoding table) and output the result to non‑file storage. It uses BarcodeGenerator, EncodeTypes, and MemoryMappedFile classes, common tasks for developers needing in‑memory barcode handling for web services or high‑performance pipelines.
+// Description: Demonstrates creating an Australia Post barcode using Reed‑Solomon error correction and saving the PNG image into an anonymous memory‑mapped file.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode parameters (such as encoding tables and X‑dimension), generate a bitmap image, and write the result to a memory‑mapped file. Key API classes include BarcodeGenerator, BarcodeParameters, Bitmap, MemoryMappedFile, and related accessor classes. Developers often need to produce barcodes for printing or embedding in applications while handling the image data in memory for further processing or inter‑process communication.
// Prompt: Generate an Australia Post barcode with Reed‑Solomon correction and output to a memory‑mapped file.
-// Tags: barcode symbology, generation, png, memory-mapped file, aspose.barcode, aspose.drawing
+// Tags: australia post, barcode generation, memory-mapped file, png, aspose.barcode, aspose.drawing
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Example program that creates an Australia Post barcode with Reed‑Solomon correction
-/// and writes the resulting PNG image to an anonymous memory‑mapped file.
+/// Example program that generates an Australia Post barcode with Reed‑Solomon correction
+/// and stores the PNG image in an anonymous memory‑mapped file.
///
class Program
{
///
- /// Entry point of the example. Generates the barcode and stores it in memory.
+ /// Entry point. Creates the barcode, saves it to a memory stream, and writes the bytes to a memory‑mapped file.
///
static void Main()
{
// Sample Australia Post code text (FCC 59 with 2 CTable characters)
- string codeText = "5980123456AB";
+ const string codeText = "5980123456AB";
- // Initialize the barcode generator for the AustraliaPost symbology
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
+ // Initialize the barcode generator for Australia Post symbology
+ using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
{
- // Configure the encoding table to use the CTable customer information type
- generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable;
+ // Use CTable encoding for the optional customer information part
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
- // Reed‑Solomon correction is applied automatically for AustraliaPost barcodes.
- // No explicit property needs to be set.
+ // Optional: adjust module size (X‑dimension) for better readability
+ generator.Parameters.Barcode.XDimension.Point = 2f;
- // Generate the barcode image (default format is PNG) and write it to a memory stream
- using (var image = generator.GenerateBarCodeImage())
+ // Generate the barcode image as a Bitmap
+ using (Bitmap bitmap = generator.GenerateBarCodeImage())
{
+ // Save the bitmap to a memory stream in PNG format
using (var ms = new MemoryStream())
{
- // Save the image into the memory stream using PNG encoding
- image.Save(ms, ImageFormat.Png);
+ bitmap.Save(ms, ImageFormat.Png);
byte[] imageBytes = ms.ToArray();
// Create an anonymous memory‑mapped file sized to hold the image bytes
using (var mmf = MemoryMappedFile.CreateNew(null, imageBytes.Length))
{
- // Obtain a view accessor to write the byte array into the memory‑mapped file
+ // Write the image bytes into the memory‑mapped file
using (var accessor = mmf.CreateViewAccessor())
{
accessor.WriteArray(0, imageBytes, 0, imageBytes.Length);
}
- // Inform the user that the operation completed successfully
- Console.WriteLine("Australia Post barcode generated and stored in a memory‑mapped file.");
+ Console.WriteLine($"Australia Post barcode generated ({imageBytes.Length} bytes) and stored in a memory‑mapped file.");
}
}
}
diff --git a/postal-barcode-types/generate-australia-post-barcodes-for-list-of-alphanumeric-codes-and-store-results-in-memory-stream-array.cs b/postal-barcode-types/generate-australia-post-barcodes-for-list-of-alphanumeric-codes-and-store-results-in-memory-stream-array.cs
index 166fe1b..c83b967 100644
--- a/postal-barcode-types/generate-australia-post-barcodes-for-list-of-alphanumeric-codes-and-store-results-in-memory-stream-array.cs
+++ b/postal-barcode-types/generate-australia-post-barcodes-for-list-of-alphanumeric-codes-and-store-results-in-memory-stream-array.cs
@@ -1,84 +1,82 @@
// Title: Generate Australia Post barcodes and store them in memory streams
-// Description: Demonstrates creating Australia Post barcodes from a set of alphanumeric strings and keeping the PNG images in MemoryStream objects for further processing.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on the Australia Post symbology. It showcases the BarcodeGenerator class with EncodeTypes.AustraliaPost, configuring the CustomerInformationInterpretingType, and saving output to PNG format via BarCodeImageFormat. Developers often need to generate barcodes programmatically for shipping labels, batch processing, or integration with document workflows.
+// Description: Demonstrates how to create Australia Post barcodes from a list of alphanumeric codes using Aspose.BarCode and keep the PNG images in memory.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator with EncodeTypes.AustraliaPost, setting the CustomerInformationInterpretingType, and saving images to MemoryStream. Developers often need to generate barcodes programmatically for mailing services, batch processing, or web APIs, and this pattern shows typical API classes and workflow for such scenarios.
// Prompt: Generate Australia Post barcodes for a list of alphanumeric codes and store results in a memory stream array.
-// Tags: barcode symbology, australia post, generation, png, memorystream, aspose.barcode
+// Tags: australia post, barcode generation, memory stream, png, aspose.barcode, csharp
using System;
using System.Collections.Generic;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
-///
-/// Example program that generates Australia Post barcodes from a predefined list of codes
-/// and stores each PNG image in a collection.
-///
-class Program
+namespace AustraliaPostBarcodeDemo
{
///
- /// Entry point of the application. Generates barcodes, writes them to files (optional),
- /// and disposes all allocated resources.
+ /// Demonstrates generating Australia Post barcodes from a set of codes and storing the PNG images in memory streams.
///
- static void Main()
+ class Program
{
- // Define a sample list of valid Australia Post codes.
- var codeTexts = new List
+ ///
+ /// Entry point. Generates barcodes for predefined codes, logs results, and returns an array of MemoryStream objects.
+ ///
+ static void Main()
{
- "1100000000", // FCC=11, no customer info
- "4580123456", // FCC=45, no customer info
- "5980123456AB", // FCC=59, 2 CTable chars
- "6280123456ABCDE", // FCC=62, 5 CTable chars (max)
- "9280123456AB" // FCC=92, 2 CTable chars
- };
+ // Sample list of valid Australia Post codes.
+ // Format: FCC (2 digits) + DPID (8 digits) + optional customer info.
+ var codes = new List
+ {
+ "1100000000", // FCC=11, no customer info
+ "5980123456AB", // FCC=59, 2 CTable chars
+ "6280123456ABCDE", // FCC=62, 5 CTable chars (max)
+ "9280123456AB" // FCC=92, 2 CTable chars
+ };
- // Collection that will hold the generated barcode images in memory.
- var streams = new List();
+ // Container for the generated barcode images.
+ var barcodeStreams = new List();
- // Iterate over each code and generate the corresponding barcode.
- foreach (var code in codeTexts)
- {
- try
+ // Iterate over each code and generate the corresponding barcode.
+ foreach (var code in codes)
{
- // Initialise the generator for Australia Post symbology with the current code.
- using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, code))
+ try
{
- // Enable CTable interpreting type for customer information (allows letters).
- generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
+ // Create a generator for Australia Post barcode with the given code text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, code))
+ {
+ // Use CTable encoding for customer information (optional).
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
+
+ // Generate the barcode image into a memory stream (PNG format).
+ var ms = new MemoryStream();
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // Reset position for later reading.
- // Save the barcode image to a memory stream in PNG format.
- var ms = new MemoryStream();
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for later reading.
+ // Store the stream for later use.
+ barcodeStreams.Add(ms);
+ }
- // Add the prepared stream to the collection.
- streams.Add(ms);
+ Console.WriteLine($"Successfully generated barcode for code: {code}");
+ }
+ catch (Exception ex)
+ {
+ // Handle any validation or generation errors gracefully.
+ Console.WriteLine($"Error generating barcode for code '{code}': {ex.Message}");
}
}
- catch (Exception ex)
- {
- // Log any errors that occur during barcode generation.
- Console.WriteLine($"Error generating barcode for '{code}': {ex.Message}");
- }
- }
- Console.WriteLine($"Generated {streams.Count} barcode images.");
+ // Convert the list to an array as required.
+ MemoryStream[] barcodeArray = barcodeStreams.ToArray();
- // OPTIONAL: Write each image to a physical file for verification.
- for (int i = 0; i < streams.Count; i++)
- {
- var fileName = $"AustraliaPost_{i + 1}.png";
- using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
+ Console.WriteLine($"Total barcodes generated: {barcodeArray.Length}");
+
+ // Example usage of the generated streams (e.g., write sizes).
+ for (int i = 0; i < barcodeArray.Length; i++)
{
- streams[i].CopyTo(fileStream);
+ Console.WriteLine($"Barcode {i + 1}: Stream length = {barcodeArray[i].Length} bytes");
}
- Console.WriteLine($"Saved {fileName}");
- }
- // Dispose all memory streams to free resources.
- foreach (var ms in streams)
- {
- ms.Dispose();
+ // Note: The memory streams remain open; they will be disposed when the application exits.
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-batch-of-planet-barcodes-from-csv-list-of-numeric-values-saving-each-as-png.cs b/postal-barcode-types/generate-batch-of-planet-barcodes-from-csv-list-of-numeric-values-saving-each-as-png.cs
index dee548e..e6642a6 100644
--- a/postal-barcode-types/generate-batch-of-planet-barcodes-from-csv-list-of-numeric-values-saving-each-as-png.cs
+++ b/postal-barcode-types/generate-batch-of-planet-barcodes-from-csv-list-of-numeric-values-saving-each-as-png.cs
@@ -1,8 +1,8 @@
-// Title: Generate Planet barcodes from CSV values
-// Description: This example reads numeric values from a CSV file and creates a Planet barcode PNG for each value.
-// Category-Description: Demonstrates batch barcode generation using Aspose.BarCode. It showcases the BarcodeGenerator class with EncodeTypes.Planet, file I/O for CSV input, and saving images in PNG format. Useful for developers needing to automate barcode creation from data sources such as spreadsheets or databases.
+// Title: Generate Planet Barcodes from CSV Values
+// Description: Demonstrates creating Planet symbology barcodes from a comma‑separated list of numeric strings and saving each as a PNG file.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use the BarcodeGenerator class with EncodeTypes.Planet to produce barcodes. Typical use cases include batch barcode creation from data sources such as CSV files, where each value is rendered as an image for printing or digital distribution. Developers often need to automate image output, manage file naming, and handle directory creation, which this snippet illustrates.
// Prompt: Generate a batch of Planet barcodes from a CSV list of numeric values, saving each as PNG.
-// Tags: planet, barcode, generation, csv, png, aspose.barcode, batch-processing
+// Tags: planet, barcode, generation, csv, png, aspose.barcode, encode-types, image-output
using System;
using System.IO;
@@ -10,69 +10,52 @@
using Aspose.BarCode.Generation;
///
-/// Example program that generates Planet barcodes from a CSV list of numeric values and saves each as a PNG file.
+/// Example program that reads numeric values from a CSV string,
+/// generates a Planet barcode for each value, and saves the barcodes as PNG files.
///
class Program
{
///
- /// Entry point of the application. Reads values from a CSV file, validates them, and creates corresponding barcode images.
+ /// Entry point of the application. Performs the barcode generation workflow.
///
static void Main()
{
- // Path to the input CSV file containing comma‑separated numeric values.
- string csvPath = "values.csv";
+ // Sample CSV data containing numeric values
+ string csvData = "12345,67890,112233,445566,778899";
- // If the CSV file does not exist, create a small sample file with example values.
- if (!File.Exists(csvPath))
- {
- string sampleData = "123456,789012,345678,901234,567890";
- File.WriteAllText(csvPath, sampleData);
- }
-
- // Directory where generated PNG barcode images will be stored.
- string outputDir = "Barcodes";
- if (!Directory.Exists(outputDir))
- {
- Directory.CreateDirectory(outputDir);
- }
+ // Split the CSV string into individual values, ignoring empty entries
+ string[] values = csvData.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- // Read the entire CSV content and split it into individual values.
- string csvContent = File.ReadAllText(csvPath);
- string[] values = csvContent.Split(new[] { ',', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
+ // Prepare the output directory for the generated barcode images
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "PlanetBarcodes");
+ Directory.CreateDirectory(outputDir);
- // Process each numeric value from the CSV.
+ // Iterate over each numeric value and generate a corresponding Planet barcode
foreach (string rawValue in values)
{
+ // Trim whitespace and skip empty entries
string value = rawValue.Trim();
+ if (string.IsNullOrEmpty(value))
+ continue;
- // Validate that the value consists only of digits; skip if invalid.
- foreach (char c in value)
- {
- if (!char.IsDigit(c))
- {
- Console.WriteLine($"Skipping invalid value: {value}");
- goto ContinueLoop;
- }
- }
-
- // Build the output file name, e.g., "Planet_123456.png".
- string outputPath = Path.Combine(outputDir, $"Planet_{value}.png");
+ // Construct a safe file name for the barcode image
+ string fileName = $"planet_{value}.png";
+ string filePath = Path.Combine(outputDir, fileName);
- // Generate a Planet barcode for the validated value and save it as PNG.
- using (var generator = new BarcodeGenerator(EncodeTypes.Planet, value))
+ // Create and configure the barcode generator for Planet symbology
+ using (var generator = new BarcodeGenerator(EncodeTypes.Planet))
{
- // Optional: set a white background and black bars (default colors are fine).
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ generator.CodeText = value; // Set the data to encode
- // Save the barcode image in PNG format.
- generator.Save(outputPath, BarCodeImageFormat.Png);
+ // Save the generated barcode as a PNG image
+ generator.Save(filePath, BarCodeImageFormat.Png);
}
- ContinueLoop:
- continue;
+ // Inform the user about the generated file
+ Console.WriteLine($"Generated Planet barcode for value {value} -> {filePath}");
}
+ // Indicate that the batch process has finished
Console.WriteLine("Barcode generation completed.");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-batch-of-postal-barcodes-using-parallel-processing-and-ensure-thread-safe-handling-of-generator-instances.cs b/postal-barcode-types/generate-batch-of-postal-barcodes-using-parallel-processing-and-ensure-thread-safe-handling-of-generator-instances.cs
index 7104f4b..96da5bc 100644
--- a/postal-barcode-types/generate-batch-of-postal-barcodes-using-parallel-processing-and-ensure-thread-safe-handling-of-generator-instances.cs
+++ b/postal-barcode-types/generate-batch-of-postal-barcodes-using-parallel-processing-and-ensure-thread-safe-handling-of-generator-instances.cs
@@ -1,92 +1,86 @@
-// Title: Generate postal barcodes in parallel
-// Description: Demonstrates creating a batch of postal barcodes using Aspose.BarCode with parallel processing, ensuring each thread uses its own generator instance.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on postal symbologies such as Postnet, Planet, AustraliaPost, SingaporePost, and USPS Intelligent Mail. It showcases the use of BarcodeGenerator, EncodeTypes, and related parameter settings to produce PNG images. Developers often need thread‑safe barcode creation for high‑throughput scenarios, and this sample illustrates best practices for parallel execution.
+// Title: Parallel Generation of Australia Post Barcodes
+// Description: Demonstrates generating a batch of Australia Post (FCC 59) barcodes in parallel, saving each as a PNG file.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to use BarcodeGenerator with EncodeTypes.AustraliaPost, configure encoding tables, and employ parallel processing for high‑throughput scenarios. Developers creating bulk postal barcode images for mailing applications can reference this pattern for thread‑safe generator usage and file naming.
// Prompt: Generate a batch of postal barcodes using parallel processing and ensure thread‑safe handling of generator instances.
-// Tags: postal, barcode, parallel, thread-safe, generation, png, aspose.barcode, encode-types
+// Tags: australia post,postal barcode,generation,parallel processing,thread safety,aspose.barcode,encode types,png output
using System;
using System.IO;
using System.Collections.Generic;
+using System.Linq;
using System.Threading.Tasks;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Example program that generates a batch of postal barcodes in parallel,
-/// demonstrating thread‑safe usage of instances.
+/// Example program that creates a set of Australia Post barcodes using parallel processing.
///
class Program
{
///
- /// Entry point of the application. Prepares barcode data, creates an output folder,
- /// and processes the batch concurrently, saving each barcode as a PNG file.
+ /// Entry point of the application. Generates barcode images and writes status messages to the console.
///
static void Main()
{
- // Define a small collection of postal barcode specifications.
- var barcodeData = new List<(string Symbology, string CodeText)>
- {
- ("Postnet", "12345"),
- ("Planet", "12345678"),
- ("AustraliaPost", "5912345678ABCde"),
- ("SingaporePost", "1234567890"),
- ("USPSIntelligentMail", "12345678901234567890")
- };
-
- // Determine the output directory and ensure it exists.
+ // Define the output folder for generated barcode images.
string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
if (!Directory.Exists(outputFolder))
{
Directory.CreateDirectory(outputFolder);
}
- // Process each barcode definition in parallel.
- // Each iteration creates its own BarcodeGenerator instance, which is thread‑safe.
- Parallel.For(0, barcodeData.Count, i =>
- {
- var (symbologyName, codeText) = barcodeData[i];
+ // Prepare a small batch of Australia Post barcode texts (FCC 59 allows up to 5 CTable chars).
+ List codeTexts = GenerateAustraliaPostCodeTexts();
- // Resolve the EncodeTypes enum value by name using reflection.
- var field = typeof(EncodeTypes).GetField(symbologyName);
- if (field == null)
- {
- Console.WriteLine($"Unknown symbology: {symbologyName}");
- return;
- }
+ // Pair each code text with its index to create unique file names.
+ var indexedCodes = codeTexts
+ .Select((code, idx) => new { Code = code, Index = idx })
+ .ToList();
- // Cast the reflected value to BaseEncodeType.
- BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null);
+ // Generate barcodes in parallel; each iteration creates its own BarcodeGenerator instance for thread safety.
+ Parallel.ForEach(indexedCodes, item =>
+ {
+ // Build the full file path for the current barcode image.
+ string filePath = Path.Combine(outputFolder, $"barcode_{item.Index + 1}.png");
- // Create a generator for the current barcode.
- using (var generator = new BarcodeGenerator(encodeType, codeText))
+ // Use a using block to ensure the generator is disposed after saving.
+ using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, item.Code))
{
- // Configure basic visual appearance.
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- generator.Parameters.Barcode.XDimension.Point = 2f; // module size
- generator.Parameters.Barcode.Padding.Left.Point = 5f;
- generator.Parameters.Barcode.Padding.Top.Point = 5f;
- generator.Parameters.Barcode.Padding.Right.Point = 5f;
- generator.Parameters.Barcode.Padding.Bottom.Point = 5f;
-
- // Example of a symbology‑specific setting: AustraliaPost encoding table.
- if (encodeType == EncodeTypes.AustraliaPost)
- {
- generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable;
- }
+ // Set the encoding table to CTable for customer information interpretation.
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
- // Build a unique file name for the output image.
- string fileName = $"{symbologyName}_{i + 1}.png";
- string filePath = Path.Combine(outputFolder, fileName);
-
- // Save the generated barcode as a PNG file.
- generator.Save(filePath);
- Console.WriteLine($"Saved {filePath}");
+ // Save the generated barcode directly as a PNG file.
+ generator.Save(filePath, BarCodeImageFormat.Png);
}
+
+ // Output progress information to the console.
+ Console.WriteLine($"Generated barcode {item.Index + 1}: {item.Code}");
});
- // Indicate that the batch processing has finished.
- Console.WriteLine("Barcode batch generation completed.");
+ // Indicate that all barcode generation tasks have completed.
+ Console.WriteLine("Barcode generation completed.");
+ }
+
+ ///
+ /// Generates a few valid Australia Post code texts using FCC 59 format.
+ ///
+ /// List of barcode text strings.
+ private static List GenerateAustraliaPostCodeTexts()
+ {
+ var list = new List();
+ // Base FCC (59) and DPID (8 digits) components.
+ string fcc = "59";
+ for (int i = 0; i < 5; i++)
+ {
+ // Create an 8‑digit DPID value.
+ string dpid = i.ToString("D8");
+
+ // Append up to 5 CTable characters (e.g., "ABCD").
+ string customerInfo = "ABCD".Substring(0, i % 5);
+ string codeText = fcc + dpid + customerInfo;
+ list.Add(codeText);
+ }
+ return list;
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-batch-of-postnet-barcodes-from-database-table-column-and-save-images-to-specified-folder.cs b/postal-barcode-types/generate-batch-of-postnet-barcodes-from-database-table-column-and-save-images-to-specified-folder.cs
index 64b6e00..421d916 100644
--- a/postal-barcode-types/generate-batch-of-postnet-barcodes-from-database-table-column-and-save-images-to-specified-folder.cs
+++ b/postal-barcode-types/generate-batch-of-postnet-barcodes-from-database-table-column-and-save-images-to-specified-folder.cs
@@ -1,95 +1,87 @@
-// Title: Generate Postnet barcodes from database values and save as PNG images
-// Description: Demonstrates how to create Postnet barcodes for ZIP codes retrieved from a data source and store each barcode as an image file.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator with EncodeTypes.Postnet. It shows typical steps such as preparing output folders, validating numeric input, and saving images, which developers often need when integrating postal barcode creation into batch processing or reporting workflows.
+// Title: Generate Postnet barcodes batch from a data source
+// Description: Demonstrates how to create multiple Postnet barcode images using Aspose.BarCode and save them to a folder. The example simulates reading zip codes from a database.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on batch processing of barcodes. It showcases the BarcodeGenerator class with EncodeTypes.Postnet, file output handling, and typical customization points. Developers looking for ways to automate barcode creation from data collections will find this pattern useful.
// Prompt: Generate a batch of Postnet barcodes from a database table column and save images to a specified folder.
-// Tags: postnet, barcode, generation, image, aspose.barcode
+// Tags: postnet, barcode, batch generation, image output, aspose.barcode, c#, png
using System;
using System.Collections.Generic;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
-///
-/// Demonstrates batch generation of Postnet barcodes from a collection of ZIP codes
-/// and saves each barcode as a PNG image in a dedicated output folder.
-///
-class Program
+namespace PostnetBatchGenerator
{
///
- /// Main entry point. Retrieves ZIP codes, validates them, generates Postnet barcodes,
- /// and writes the resulting images to disk.
+ /// Provides an entry point that generates a set of Postnet barcodes from a list of codes
+ /// (simulating a database column) and saves each barcode as a PNG file.
///
- static void Main()
+ class Program
{
- // Define the folder where barcode images will be stored.
- string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "PostnetBarcodes");
- if (!Directory.Exists(outputFolder))
+ ///
+ /// Main method that orchestrates folder creation, data preparation, barcode generation,
+ /// and file saving for a batch of Postnet barcodes.
+ ///
+ static void Main()
{
- // Create the folder if it does not already exist.
- Directory.CreateDirectory(outputFolder);
- }
+ // Determine the output folder path relative to the current working directory.
+ string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(outputFolder))
+ {
+ // Create the folder if it does not already exist.
+ Directory.CreateDirectory(outputFolder);
+ }
- // ------------------------------------------------------------
- // Simulated data retrieval from a database table column.
- // Replace this block with actual DB access code, e.g., using
- // System.Data.SqlClient to read the column values.
- // ------------------------------------------------------------
- // Example real implementation (commented out because the
- // required database provider may not be available in the runner):
- // List values = new List();
- // using (var connection = new SqlConnection(connectionString))
- // {
- // connection.Open();
- // using (var command = new SqlCommand("SELECT ZipCode FROM Addresses", connection))
- // using (var reader = command.ExecuteReader())
- // {
- // while (reader.Read())
- // {
- // values.Add(reader.GetString(0));
- // }
- // }
- // }
- List values = new List { "12345", "67890", "24680", "13579", "11223" };
+ // -----------------------------------------------------------------
+ // In a real scenario, replace the following block with code that
+ // reads the desired column from a database table (e.g., using
+ // ADO.NET, Dapper, Entity Framework, etc.).
+ // Example (pseudo‑code):
+ // using (var connection = new SqlConnection(connectionString))
+ // {
+ // connection.Open();
+ // var command = new SqlCommand("SELECT ZipCode FROM Addresses", connection);
+ // using (var reader = command.ExecuteReader())
+ // {
+ // while (reader.Read())
+ // postnetCodes.Add(reader.GetString(0));
+ // }
+ // }
+ // -----------------------------------------------------------------
- // Iterate over each ZIP code and generate a barcode if the code is valid.
- foreach (string code in values)
- {
- // Postnet requires a numeric ZIP code of 5 or 9 digits.
- if (string.IsNullOrWhiteSpace(code) || (code.Length != 5 && code.Length != 9) || !IsAllDigits(code))
+ // Sample data to simulate database column values.
+ List postnetCodes = new List
{
- Console.WriteLine($"Skipping invalid Postnet code: {code}");
- continue;
- }
+ "12345",
+ "67890",
+ "123456789",
+ "00123",
+ "98765"
+ };
- // Create a barcode generator for the Postnet symbology.
- using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, code))
+ // Iterate over each code and generate a corresponding Postnet barcode image.
+ foreach (string code in postnetCodes)
{
- // Optional: adjust short bar height for postal barcodes.
- // generator.Parameters.Postal.ShortBarHeight.Point = 2f;
+ // Initialize the barcode generator for the Postnet symbology with the current code.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, code))
+ {
+ // Optional: customize barcode appearance here, e.g.:
+ // generator.Parameters.Barcode.XDimension.Point = 2f;
+ // generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+
+ // Build the full file path using the code as the file name.
+ string filePath = Path.Combine(outputFolder, $"{code}.png");
- // Build the full file path for the output image.
- string filePath = Path.Combine(outputFolder, $"{code}.png");
+ // Save the generated barcode image as a PNG file.
+ generator.Save(filePath);
- // Save the generated barcode as a PNG file.
- generator.Save(filePath);
- Console.WriteLine($"Saved Postnet barcode for {code} to {filePath}");
+ // Inform the user about the generated file.
+ Console.WriteLine($"Generated Postnet barcode for '{code}' at '{filePath}'.");
+ }
}
- }
- }
- ///
- /// Determines whether the supplied string consists solely of digit characters.
- ///
- /// The string to evaluate.
- /// True if all characters are digits; otherwise, false.
- static bool IsAllDigits(string s)
- {
- foreach (char c in s)
- {
- if (!char.IsDigit(c))
- return false;
+ Console.WriteLine("Barcode batch generation completed.");
}
- return true;
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-batch-of-swiss-post-parcel-additional-service-code-barcodes-and-produce-csv-index-linking-identifiers.cs b/postal-barcode-types/generate-batch-of-swiss-post-parcel-additional-service-code-barcodes-and-produce-csv-index-linking-identifiers.cs
index a2dbbe5..f964375 100644
--- a/postal-barcode-types/generate-batch-of-swiss-post-parcel-additional-service-code-barcodes-and-produce-csv-index-linking-identifiers.cs
+++ b/postal-barcode-types/generate-batch-of-swiss-post-parcel-additional-service-code-barcodes-and-produce-csv-index-linking-identifiers.cs
@@ -1,65 +1,75 @@
-// Title: Generate Swiss Post Parcel Additional Service Code Barcodes with CSV Index
-// Description: Creates PNG barcodes for Swiss Post Parcel additional service codes and writes a CSV file mapping each code to its image file.
-// Category-Description: This example demonstrates how to use Aspose.BarCode to generate Swiss Post Parcel additional service code barcodes, save them as images, and build an index CSV. It covers the BarcodeGenerator class, EncodeTypes.SwissPostParcel, and file I/O for batch processing—common tasks for developers automating barcode creation for shipping and logistics.
+// Title: Generate Swiss Post Parcel Barcodes and CSV Index
+// Description: Creates a set of Swiss Post Parcel additional service code barcodes, saves them as PNG files, and builds a CSV file that maps each identifier to its image file.
+// Category-Description: This example demonstrates the Aspose.BarCode generation API for Swiss Post Parcel barcodes. It shows how to configure a BarcodeGenerator, set barcode parameters such as X‑dimension, and export images. Typical use cases include batch creation of parcel service codes and maintaining an index for downstream processing. Developers working with barcode generation, bulk image output, and CSV reporting will find this pattern useful.
// Prompt: Generate a batch of Swiss Post Parcel additional service code barcodes and produce a CSV index linking identifiers.
-// Tags: barcode, swisspost, parcel, additional service code, csv, batch generation, aspose.barcode, image output
+// Tags: barcode, swisspostparcel, generation, png, csv, aspose.barcode, encode types
using System;
using System.IO;
+using System.Collections.Generic;
using Aspose.BarCode.Generation;
///
-/// Demonstrates batch generation of Swiss Post Parcel additional service code barcodes
-/// and creation of a CSV index linking each identifier to its image file.
+/// Demonstrates batch generation of Swiss Post Parcel barcodes and creation of a CSV index file.
///
class Program
{
///
- /// Entry point of the example. Generates barcode images and writes an index CSV.
+ /// Entry point of the example. Generates barcode images and writes a CSV index.
///
static void Main()
{
- // Define the output directory for barcode images
- string outputDir = "Barcodes";
- Directory.CreateDirectory(outputDir); // Ensure the directory exists
+ // Determine output directory for barcode images
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(outputDir))
+ {
+ // Create the directory if it does not exist
+ Directory.CreateDirectory(outputDir);
+ }
- // Define the path for the CSV index file
+ // Define the CSV index file path within the output directory
string csvPath = Path.Combine(outputDir, "index.csv");
- // Sample additional service codes for Swiss Post Parcel
- string[] serviceCodes = new string[]
- {
- "1234567890",
- "0987654321",
- "1122334455",
- "5566778899",
- "0001112223"
- };
+ // Prepare CSV content: header line followed by data rows
+ List csvLines = new List();
+ csvLines.Add("Identifier,FileName");
- // Create the CSV file and write the header row
- using (StreamWriter writer = new StreamWriter(csvPath))
+ // Generate a small batch of barcodes (5 samples)
+ for (int i = 1; i <= 5; i++)
{
- writer.WriteLine("Identifier,FileName");
+ // Build a unique identifier for each barcode
+ string identifier = $"ID{i:D3}";
+ string fileName = $"{identifier}.png";
+ string filePath = Path.Combine(outputDir, fileName);
+ string codeText = identifier; // Use the identifier as the barcode's codetext
- // Iterate over each service code to generate a barcode
- for (int i = 0; i < serviceCodes.Length; i++)
+ // Create and configure the barcode generator for Swiss Post Parcel symbology
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, codeText))
{
- string code = serviceCodes[i];
- string fileName = $"SwissPost_{i + 1}.png";
- string filePath = Path.Combine(outputDir, fileName);
+ // Set module (X) size to 2 points
+ generator.Parameters.Barcode.XDimension.Point = 2f;
- // Generate the barcode image using Aspose.BarCode
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, code))
- {
- generator.Save(filePath); // Save the barcode as a PNG file
- }
+ // Disable exception throwing for incorrect codetext (optional)
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false;
+
+ // Save the generated barcode image as PNG
+ generator.Save(filePath);
+ }
- // Record the mapping of identifier to file name in the CSV
- writer.WriteLine($"{code},{fileName}");
+ // Record the identifier and corresponding file name in the CSV data
+ csvLines.Add($"{identifier},{fileName}");
+ Console.WriteLine($"Generated barcode for {identifier} -> {fileName}");
+ }
+
+ // Write all CSV lines to the index file
+ using (StreamWriter writer = new StreamWriter(csvPath, false))
+ {
+ foreach (string line in csvLines)
+ {
+ writer.WriteLine(line);
}
}
- // Inform the user where the output files are located
- Console.WriteLine($"Barcodes generated and CSV index created at: {csvPath}");
+ Console.WriteLine($"CSV index created at: {csvPath}");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-batch-of-swiss-post-parcel-domestic-barcodes-and-create-single-multi-page-pdf-containing-all.cs b/postal-barcode-types/generate-batch-of-swiss-post-parcel-domestic-barcodes-and-create-single-multi-page-pdf-containing-all.cs
index f3cbcf1..638d4a9 100644
--- a/postal-barcode-types/generate-batch-of-swiss-post-parcel-domestic-barcodes-and-create-single-multi-page-pdf-containing-all.cs
+++ b/postal-barcode-types/generate-batch-of-swiss-post-parcel-domestic-barcodes-and-create-single-multi-page-pdf-containing-all.cs
@@ -1,91 +1,99 @@
-// Title: Generate Swiss Post Parcel barcodes and compile into multi‑page PDF
-// Description: This example creates several Swiss Post Parcel domestic barcodes and assembles them into a single PDF document, one barcode per page.
-// Category-Description: Demonstrates batch barcode generation using Aspose.BarCode and PDF composition with Aspose.Pdf. It showcases the BarcodeGenerator class for SwissPostParcel symbology, configuring colors, rendering to PNG, and embedding images into a multi‑page PDF via Aspose.Pdf Document. Useful for developers needing to produce printable barcode sheets or shipping labels in bulk.
+// Title: Generate Swiss Post Parcel Barcodes and Combine into Multi‑Page PDF
+// Description: Demonstrates how to generate Swiss Post Parcel domestic barcodes using Aspose.BarCode and embed them into a multi‑page PDF with Aspose.Pdf.
+// Category-Description: This example belongs to the barcode generation and PDF composition category of Aspose.BarCode. It showcases the use of BarcodeGenerator (EncodeTypes.SwissPostParcel), BarCodeImageFormat, and Aspose.Pdf Document and Image classes to create barcode images and place them on separate PDF pages. Typical use cases include batch printing of shipping labels, parcel tracking documents, and bulk barcode reports where developers need to programmatically generate multiple barcodes and consolidate them into a single PDF file.
// Prompt: Generate a batch of Swiss Post Parcel domestic barcodes and create a single multi‑page PDF containing all.
-// Tags: swisspostparcel, barcode, pdf, batch, generation, aspose.barcode, aspose.pdf
+// Tags: swisspostparcel, barcode, pdf, aspose.barcode, aspose.pdf, generation, image
using System;
-using System.Collections.Generic;
using System.IO;
+using System.Collections.Generic;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Pdf;
///
-/// Generates a batch of Swiss Post Parcel domestic barcodes and compiles them into a multi‑page PDF.
+/// Demonstrates generating Swiss Post Parcel domestic barcodes and assembling them into a multi‑page PDF.
///
class Program
{
///
- /// Entry point. Creates barcode images, adds each to a PDF page, and saves the document.
+ /// Entry point that triggers PDF generation with barcode images.
///
static void Main()
{
- // Path for the resulting PDF file
- string outputPdfPath = "SwissPostParcelBarcodes.pdf";
+ // Generate a PDF with a batch of Swiss Post Parcel domestic barcodes.
+ GenerateSwissPostParcelPdf();
+ }
- // Sample Swiss Post Parcel domestic barcode texts (limited to 4 for evaluation mode)
+ static void GenerateSwissPostParcelPdf()
+ {
+ // Sample code texts for Swiss Post Parcel domestic barcodes.
+ // In a real scenario these would be valid parcel identifiers.
var codeTexts = new List
{
- "123456789012", // Sample domestic parcel
- "234567890123",
- "345678901234",
- "456789012345"
+ "1234567890",
+ "9876543210",
+ "1122334455",
+ "5566778899"
};
- // Keep barcode image streams alive until the PDF is saved
+ // Limit to 4 items as required for Aspose.Pdf evaluation mode.
+ int maxCount = Math.Min(codeTexts.Count, 4);
+
+ // Prepare a list to hold the memory streams until the PDF is saved.
var barcodeStreams = new List();
- // Create a new PDF document
+ // Create a new PDF document.
using (var pdfDoc = new Document())
{
- // Generate a barcode for each code text and add it to a new PDF page
- foreach (var text in codeTexts)
+ for (int i = 0; i < maxCount; i++)
{
- // Generate barcode image into a memory stream
- using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, text))
+ string codeText = codeTexts[i];
+
+ // Create a barcode generator for Swiss Post Parcel.
+ using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, codeText))
{
- // Optional: set colors (fully qualified to avoid ambiguity)
+ // Optional: set barcode colors if desired.
generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+ // Save the barcode image to a memory stream in PNG format.
var ms = new MemoryStream();
- // Save barcode as PNG into the stream
generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0;
+ ms.Position = 0; // Reset stream position for reading.
- // Keep the stream for later disposal
+ // Keep the stream for later disposal.
barcodeStreams.Add(ms);
- // Add a new page to the PDF
+ // Add a new page to the PDF.
var page = pdfDoc.Pages.Add();
- // Create an image object that uses the barcode stream
- var pdfImage = new Image
+ // Create an Aspose.Pdf.Image from the barcode stream.
+ var pdfImage = new Aspose.Pdf.Image
{
ImageStream = ms,
- // Adjust size as needed
- FixWidth = 200,
- FixHeight = 100,
- HorizontalAlignment = HorizontalAlignment.Center,
- VerticalAlignment = VerticalAlignment.Center
+ // Adjust size as needed.
+ FixWidth = 200.0,
+ FixHeight = 200.0,
+ HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center,
+ Margin = new Aspose.Pdf.MarginInfo { Top = 20 }
};
- // Add the image to the page
+ // Add the image to the page.
page.Paragraphs.Add(pdfImage);
}
}
- // Save the multi‑page PDF
- pdfDoc.Save(outputPdfPath);
+ // Save the multi‑page PDF to disk.
+ string outputPath = "SwissPostParcelBarcodes.pdf";
+ pdfDoc.Save(outputPath);
+ Console.WriteLine($"PDF saved to {Path.GetFullPath(outputPath)}");
}
- // Dispose all barcode streams after the PDF has been saved
+ // Dispose all barcode streams.
foreach (var stream in barcodeStreams)
{
stream.Dispose();
}
-
- Console.WriteLine($"PDF with Swiss Post Parcel barcodes created: {outputPdfPath}");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-batch-of-swiss-post-parcel-international-barcodes-and-combine-them-into-single-tiff-image.cs b/postal-barcode-types/generate-batch-of-swiss-post-parcel-international-barcodes-and-combine-them-into-single-tiff-image.cs
index f988de4..ef10da0 100644
--- a/postal-barcode-types/generate-batch-of-swiss-post-parcel-international-barcodes-and-combine-them-into-single-tiff-image.cs
+++ b/postal-barcode-types/generate-batch-of-swiss-post-parcel-international-barcodes-and-combine-them-into-single-tiff-image.cs
@@ -1,27 +1,28 @@
-// Title: Generate Swiss Post Parcel International Barcodes and Combine into TIFF
-// Description: Creates multiple Swiss Post Parcel International barcodes and merges them into a single multi-page TIFF image.
-// Category-Description: This example belongs to the Aspose.BarCode generation and image manipulation category. It demonstrates how to use BarcodeGenerator (EncodeTypes.SwissPostParcel) to produce barcodes, adjust rendering parameters, and then combine the resulting Bitmap objects using Aspose.Drawing.Graphics. Typical use cases include batch processing of shipping labels, creating composite documents, and exporting barcode collections to common image formats such as TIFF.
+// Title: Generate Swiss Post Parcel barcodes and combine into a TIFF
+// Description: Demonstrates creating multiple Swiss Post Parcel international barcodes and merging them into a single TIFF image for batch processing.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator with EncodeTypes.SwissPostParcel, manipulate bitmap images, and produce multi-page TIFF output. Developers working with postal barcode standards often need to generate batches of barcodes and combine them for printing or archival; this snippet illustrates the typical workflow using Aspose.BarCode and Aspose.Drawing APIs.
// Prompt: Generate a batch of Swiss Post Parcel international barcodes and combine them into a single TIFF image.
-// Tags: swisspostparcel, barcode, generation, tiff, image, combine, aspose.barcode, aspose.drawing
+// Tags: swisspostparcel, barcode generation, tiff, aspose.barcode, aspose.drawing, batch processing
using System;
using System.Collections.Generic;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Demonstrates batch generation of Swiss Post Parcel International barcodes and combines them into a single TIFF image.
+/// Demonstrates generating a batch of Swiss Post Parcel barcodes and combining them into a single TIFF image.
///
class Program
{
///
- /// Entry point of the example. Generates barcodes, merges them vertically, and saves the result as a TIFF file.
+ /// Entry point. Generates barcodes for sample texts and saves the combined TIFF.
///
static void Main()
{
- // Sample Swiss Post Parcel International code texts (replace with real data as needed)
+ // Sample Swiss Post Parcel international code texts
var codeTexts = new List
{
"12345678901234567890",
@@ -31,62 +32,72 @@ static void Main()
"99988877766655544433"
};
- // Store generated barcode images
- var barcodes = new List();
+ // Path for the combined TIFF image
+ string outputPath = "SwissPostParcelBatch.tiff";
- // Generate each barcode
+ // Generate the combined TIFF from the list of barcode texts
+ GenerateCombinedTiff(codeTexts, outputPath);
+
+ // Inform the user where the file was saved
+ Console.WriteLine($"Combined TIFF saved to: {Path.GetFullPath(outputPath)}");
+ }
+
+ ///
+ /// Generates individual barcode images from the provided texts and merges them vertically into a single TIFF file.
+ ///
+ /// Collection of barcode data strings.
+ /// File path for the resulting TIFF image.
+ static void GenerateCombinedTiff(List codeTexts, string outputFile)
+ {
+ if (codeTexts == null || codeTexts.Count == 0)
+ throw new ArgumentException("codeTexts collection must contain at least one element.");
+
+ // Store generated barcode bitmaps
+ var barcodeImages = new List();
+
+ // Generate each barcode image
foreach (var text in codeTexts)
{
using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, text))
{
- // Optional: set module size for better visibility
+ // Optional: adjust module size if needed
generator.Parameters.Barcode.XDimension.Point = 2f;
- // Use interpolation mode to let the generator size the image automatically
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
-
- // Generate the image and add it to the collection
- var bmp = generator.GenerateBarCodeImage();
- barcodes.Add(bmp);
+ // Generate the bitmap for the current barcode
+ Bitmap bmp = generator.GenerateBarCodeImage();
+ barcodeImages.Add(bmp);
}
}
- // Determine combined image dimensions (max width and total height)
+ // Determine final image dimensions (stack vertically)
int maxWidth = 0;
int totalHeight = 0;
- foreach (var bmp in barcodes)
+ foreach (var img in barcodeImages)
{
- if (bmp.Width > maxWidth) maxWidth = bmp.Width;
- totalHeight += bmp.Height;
+ if (img.Width > maxWidth) maxWidth = img.Width;
+ totalHeight += img.Height;
}
- // Create a new bitmap to hold all barcodes vertically
- using (var combined = new Bitmap(maxWidth, totalHeight))
+ // Create the final bitmap that will hold all barcodes
+ using (var finalBitmap = new Bitmap(maxWidth, totalHeight))
{
- using (var graphics = Graphics.FromImage(combined))
+ using (var graphics = Graphics.FromImage(finalBitmap))
{
// Fill background with white
- graphics.Clear(Aspose.Drawing.Color.White);
-
- // Draw each barcode image one below the other
+ graphics.Clear(Color.White);
int offsetY = 0;
- foreach (var bmp in barcodes)
+
+ // Draw each barcode image onto the final bitmap
+ foreach (var img in barcodeImages)
{
- graphics.DrawImage(bmp, 0, offsetY, bmp.Width, bmp.Height);
- offsetY += bmp.Height;
+ graphics.DrawImage(img, 0, offsetY, img.Width, img.Height);
+ offsetY += img.Height;
+ img.Dispose(); // Dispose individual barcode bitmap after drawing
}
}
- // Save the combined image as a TIFF file
- combined.Save("SwissPostParcelBatch.tiff", ImageFormat.Tiff);
+ // Save the combined image as a TIFF file (single-page in this case)
+ finalBitmap.Save(outputFile, ImageFormat.Tiff);
}
-
- // Dispose individual barcode bitmaps
- foreach (var bmp in barcodes)
- {
- bmp.Dispose();
- }
-
- Console.WriteLine("Batch TIFF image created: SwissPostParcelBatch.tiff");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-dutch-kix-2-state-postal-barcode-with-numeric-input-validation-and-automatic-checksum.cs b/postal-barcode-types/generate-dutch-kix-2-state-postal-barcode-with-numeric-input-validation-and-automatic-checksum.cs
index 5b3062d..5bb2520 100644
--- a/postal-barcode-types/generate-dutch-kix-2-state-postal-barcode-with-numeric-input-validation-and-automatic-checksum.cs
+++ b/postal-barcode-types/generate-dutch-kix-2-state-postal-barcode-with-numeric-input-validation-and-automatic-checksum.cs
@@ -1,64 +1,71 @@
-// Title: Generate Dutch KIX 2‑state postal barcode with checksum
-// Description: Demonstrates creating a Dutch KIX barcode from numeric input, validating the data, and automatically adding the required checksum.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator with EncodeTypes.DutchKIX. It shows typical steps such as input validation, enabling checksum, setting colors, and saving the image. Developers working on postal barcode solutions often need these patterns for creating compliant KIX barcodes.
+// Title: Generate Dutch KIX 2‑state Postal Barcode with Validation and Checksum
+// Description: Demonstrates creating a Dutch KIX (2‑state postal) barcode from numeric input, validating the data and enabling automatic checksum calculation.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to select a specific symbology (EncodeTypes.DutchKIX), configure checksum options, and output the result as an image file. Developers working with postal barcodes often need to validate numeric data, enable checksum generation, and produce printable graphics; this snippet shows the typical API usage for those scenarios.
// Prompt: Generate a Dutch KIX 2‑state postal barcode with numeric input validation and automatic checksum.
-// Tags: dutch kix, barcode generation, checksum, png, aspnet, aspose.barcode
+// Tags: barcode, generation, dutch kix, checksum, validation, image, aspose.barcode
using System;
using System.IO;
+using System.Linq;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
///
-/// Demonstrates generating a Dutch KIX 2‑state postal barcode with numeric validation and automatic checksum.
+/// Demonstrates generating a Dutch KIX 2‑state postal barcode with input validation and automatic checksum.
///
class Program
{
///
- /// Entry point. Generates the barcode and saves it as a PNG file.
+ /// Entry point. Generates the barcode and writes status messages to the console.
///
static void Main()
{
- // Sample numeric input for Dutch KIX barcode.
- // In a real scenario this could come from arguments or another source.
+ // Sample numeric data for Dutch KIX barcode
string input = "1234567890123";
+ string outputPath = "dutchkix.png";
- // Validate that the input consists only of digits and is not empty.
- if (string.IsNullOrEmpty(input) || !IsAllDigits(input))
+ try
{
- throw new ArgumentException("Input must be a non‑empty numeric string.");
+ // Generate the barcode and save it to the specified file
+ GenerateDutchKix(input, outputPath);
+ Console.WriteLine($"Dutch KIX barcode saved to '{outputPath}'.");
}
-
- // Determine the output file path in the current working directory.
- string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "kix.png");
-
- // Create the barcode generator for the Dutch KIX symbology with the validated input.
- using (var generator = new BarcodeGenerator(EncodeTypes.DutchKIX, input))
+ catch (Exception ex)
{
- // Enable automatic checksum generation required by the KIX specification.
- generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes;
-
- // Optional visual settings: black bars on a white background.
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
-
- // Save the generated barcode image as a PNG file.
- generator.Save(outputPath, BarCodeImageFormat.Png);
+ // Output any errors that occur during generation
+ Console.WriteLine($"Error: {ex.Message}");
}
-
- // Inform the user where the barcode image has been saved.
- Console.WriteLine($"Dutch KIX barcode saved to: {outputPath}");
}
- // Helper method to verify that a string contains only digit characters.
- static bool IsAllDigits(string s)
+ ///
+ /// Generates a Dutch KIX barcode from numeric data, validates the input, enables checksum, and saves the image.
+ ///
+ /// The numeric string to encode.
+ /// The full path where the barcode image will be saved.
+ static void GenerateDutchKix(string numericData, string filePath)
{
- foreach (char c in s)
+ // Validate input: must be non‑empty and contain only digits
+ if (string.IsNullOrEmpty(numericData))
+ throw new ArgumentException("Input cannot be null or empty.", nameof(numericData));
+
+ if (!numericData.All(char.IsDigit))
+ throw new ArgumentException("Input must contain only numeric characters.", nameof(numericData));
+
+ // Ensure the output directory exists
+ string directory = Path.GetDirectoryName(filePath);
+ if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
+ Directory.CreateDirectory(directory);
+
+ // Create the barcode generator for Dutch KIX (2‑state postal) symbology
+ using (var generator = new BarcodeGenerator(EncodeTypes.DutchKIX, numericData))
{
- if (!char.IsDigit(c))
- return false;
+ // Enable automatic checksum generation
+ generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes;
+ // Optionally display the checksum in the human‑readable text
+ generator.Parameters.Barcode.ChecksumAlwaysShow = true;
+
+ // Save the barcode image (format inferred from file extension)
+ generator.Save(filePath);
}
- return true;
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-dutch-kix-barcodes-using-json-array-of-identifiers-and-export-each-as-bmp-images.cs b/postal-barcode-types/generate-dutch-kix-barcodes-using-json-array-of-identifiers-and-export-each-as-bmp-images.cs
index b5d5d9e..cb12a92 100644
--- a/postal-barcode-types/generate-dutch-kix-barcodes-using-json-array-of-identifiers-and-export-each-as-bmp-images.cs
+++ b/postal-barcode-types/generate-dutch-kix-barcodes-using-json-array-of-identifiers-and-export-each-as-bmp-images.cs
@@ -1,8 +1,8 @@
-// Title: Generate Dutch KIX Barcodes from JSON and Export as BMP
-// Description: This example reads a JSON array of 8‑digit identifiers, creates Dutch KIX barcodes for each, and saves them as BMP images.
-// Category-Description: Demonstrates Aspose.BarCode barcode generation using the BarcodeGenerator class with EncodeTypes.DutchKIX. Typical use cases include batch creation of KIX barcodes for inventory or logistics, reading identifiers from JSON, configuring barcode parameters, and exporting to bitmap files. Developers often need to validate input, manage output folders, and handle serialization when automating barcode production.
+// Title: Generate Dutch KIX barcodes from JSON identifiers and save as BMP files
+// Description: Demonstrates how to parse a JSON array of identifiers, create Dutch KIX barcodes using Aspose.BarCode, and export each barcode as a BMP image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator with EncodeTypes.DutchKIX. It shows typical steps such as parsing input data, configuring the generator, and saving images in a specific format—common tasks for developers needing to produce bulk barcode images for inventory, shipping, or labeling systems.
// Prompt: Generate Dutch KIX barcodes using a JSON array of identifiers and export each as BMP images.
-// Tags: dutch kix, barcode generation, bmp, aspose.barcode, json, csharp
+// Tags: dutch kix, barcode generation, json parsing, bmp output, aspose.barcode, csharp
using System;
using System.IO;
@@ -11,74 +11,73 @@
using Aspose.BarCode.Generation;
///
-/// Reads a JSON file containing an array of identifiers, generates Dutch KIX barcodes,
-/// and saves each barcode as a BMP image in the output folder.
+/// Provides functionality to generate Dutch KIX barcodes from a JSON array and save them as BMP images.
///
class Program
{
///
- /// Entry point of the example. Handles JSON loading, identifier validation,
- /// barcode generation, and image export.
+ /// Entry point of the application. Generates barcodes based on a sample JSON array and writes them to the output folder.
///
- static void Main()
+ /// Command‑line arguments (not used in this example).
+ static void Main(string[] args)
{
- // Path to the JSON file that holds the identifier array.
- const string jsonFile = "identifiers.json";
+ // Sample JSON array of identifiers; replace with args or file input as needed.
+ string json = "[\"123456789012\", \"987654321098\", \"555555555555\"]";
+ string outputFolder = "Barcodes";
- // Load JSON content; fall back to a hard‑coded sample if the file is missing.
- string jsonContent;
- if (File.Exists(jsonFile))
- {
- jsonContent = File.ReadAllText(jsonFile);
- }
- else
- {
- // Sample identifiers for Dutch KIX (numeric, exactly 8 characters).
- jsonContent = "[\"12345678\", \"87654321\", \"11223344\"]";
- }
-
- // Deserialize the JSON array into a string[].
- string[] identifiers;
try
{
- identifiers = JsonSerializer.Deserialize(jsonContent);
- if (identifiers == null || identifiers.Length == 0)
- throw new ArgumentException("No identifiers found in JSON.");
+ // Generate the barcodes and save them to the specified folder.
+ GenerateDutchKixBarcodes(json, outputFolder);
+ Console.WriteLine("Barcode generation completed.");
}
catch (Exception ex)
{
- Console.WriteLine($"Failed to parse identifiers: {ex.Message}");
- return;
+ // Output any errors that occur during processing.
+ Console.WriteLine($"Error: {ex.Message}");
}
+ }
+
+ ///
+ /// Parses a JSON array of identifier strings, creates a Dutch KIX barcode for each, and saves the result as a BMP file.
+ ///
+ /// A JSON-formatted array containing barcode identifiers.
+ /// The directory where BMP images will be written.
+ static void GenerateDutchKixBarcodes(string jsonArray, string outputDirectory)
+ {
+ if (string.IsNullOrWhiteSpace(jsonArray))
+ throw new ArgumentException("JSON array is null or empty.");
- // Ensure the output directory exists (creates it if necessary).
- const string outputDir = "output";
- Directory.CreateDirectory(outputDir);
+ // Ensure the output directory exists.
+ Directory.CreateDirectory(outputDirectory);
- // Iterate over each identifier, validate it, generate a barcode, and save as BMP.
- foreach (string id in identifiers)
+ // Parse the JSON array of strings.
+ using (JsonDocument doc = JsonDocument.Parse(jsonArray))
{
- // Validate identifier: must be numeric and exactly 8 characters for KIX.
- if (string.IsNullOrWhiteSpace(id) || id.Length != 8 || !long.TryParse(id, out _))
+ if (doc.RootElement.ValueKind != JsonValueKind.Array)
+ throw new ArgumentException("Provided JSON is not an array.");
+
+ // Iterate over each element in the JSON array.
+ foreach (JsonElement element in doc.RootElement.EnumerateArray())
{
- Console.WriteLine($"Skipping invalid identifier: '{id}'");
- continue;
- }
+ // Skip entries that are not strings.
+ if (element.ValueKind != JsonValueKind.String)
+ continue;
- // Build the full path for the output BMP file.
- string outputPath = Path.Combine(outputDir, $"{id}.bmp");
+ string identifier = element.GetString();
+ if (string.IsNullOrWhiteSpace(identifier))
+ continue;
- // Create and configure the barcode generator for Dutch KIX.
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.DutchKIX, id))
- {
- // Optional: set X dimension (size of the smallest bar) to 2 points.
- generator.Parameters.Barcode.XDimension.Point = 2f;
+ // Build the full file path for the BMP image.
+ string filePath = Path.Combine(outputDirectory, $"{identifier}.bmp");
- // Save the generated barcode image as BMP.
- generator.Save(outputPath, BarCodeImageFormat.Bmp);
+ // Create and save the Dutch KIX barcode.
+ using (var generator = new BarcodeGenerator(EncodeTypes.DutchKIX, identifier))
+ {
+ // Save directly as BMP using the appropriate format enum.
+ generator.Save(filePath, BarCodeImageFormat.Bmp);
+ }
}
-
- Console.WriteLine($"Generated barcode for '{id}' -> {outputPath}");
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-mailmark-4-state-postal-barcode-with-reed-solomon-correction-and-custom-xdimension-of-05-mm.cs b/postal-barcode-types/generate-mailmark-4-state-postal-barcode-with-reed-solomon-correction-and-custom-xdimension-of-05-mm.cs
index fcbf9e2..ddd6bd5 100644
--- a/postal-barcode-types/generate-mailmark-4-state-postal-barcode-with-reed-solomon-correction-and-custom-xdimension-of-05-mm.cs
+++ b/postal-barcode-types/generate-mailmark-4-state-postal-barcode-with-reed-solomon-correction-and-custom-xdimension-of-05-mm.cs
@@ -1,8 +1,8 @@
-// Title: Generate Mailmark 4‑state barcode with Reed‑Solomon correction and custom XDimension
-// Description: Demonstrates creating a Mailmark 4‑state postal barcode using Reed‑Solomon error correction and setting a custom module size of 0.5 mm.
-// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator together with MailmarkCodetext to produce postal barcodes. Typical use cases include printing Mailmark barcodes for mail sorting and tracking, where developers need to configure format, version, and error‑correction settings.
+// Title: Generate Mailmark 4‑State Barcode with Reed‑Solomon Correction and Custom XDimension
+// Description: Demonstrates how to create a Mailmark 4‑state postal barcode, apply Reed‑Solomon error correction, and set a custom XDimension of 0.5 mm before saving it as a PNG image.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex postal symbologies. It showcases the use of MailmarkCodetext to build the codetext, ComplexBarcodeGenerator to render the barcode, and BarCodeImageFormat for output. Developers working with postal automation, mail sorting, or custom barcode dimensions will find these APIs essential for creating compliant Mailmark barcodes.
// Prompt: Generate a Mailmark 4‑state postal barcode with Reed‑Solomon correction and custom XDimension of 0.5 mm.
-// Tags: mailmark, barcode generation, png, complexbarcode, aspose.barcode
+// Tags: mailmark,4-state,barcode,generation,aspose.barcode,complexbarcode,reed-solomon,xdimension,png
using System;
using Aspose.BarCode;
@@ -11,7 +11,7 @@
///
/// Example program that creates a Mailmark 4‑state barcode with Reed‑Solomon correction
-/// and saves it as a PNG image.
+/// and a custom XDimension, then saves it as a PNG file.
///
class Program
{
@@ -21,27 +21,30 @@ class Program
///
static void Main()
{
- // Prepare Mailmark 4‑state codetext with required fields
+ // Initialize Mailmark codetext for a 4‑state barcode
var mailmark = new MailmarkCodetext
{
- Format = 4, // 4‑state format
- VersionID = 1, // version identifier
- Class = "0", // service class
- SupplychainID = 384224, // supply chain identifier
- ItemID = 16563762, // item identifier
- DestinationPostCodePlusDPS = "EF61AH8T " // valid postcode + DPS (trailing space)
+ Format = 4, // Specify 4‑state format
+ VersionID = 1, // Set version identifier
+ Class = "0", // Set class value
+ SupplychainID = 384224, // Set supply chain identifier
+ ItemID = 16563762, // Set item identifier
+ // DestinationPostCodePlusDPS requires a trailing space
+ DestinationPostCodePlusDPS = "EF61AH8T "
};
- // Generate the barcode using ComplexBarcodeGenerator
+ // Create a ComplexBarcodeGenerator using the prepared codetext
using (var generator = new ComplexBarcodeGenerator(mailmark))
{
- // Set module (X‑dimension) size to 0.5 mm
+ // Apply custom XDimension of 0.5 mm (affects barcode module size)
generator.Parameters.Barcode.XDimension.Millimeters = 0.5f;
- // Save the barcode image as PNG
- generator.Save("mailmark.png");
- }
+ // Define output file path and save the barcode as a PNG image
+ string outputPath = "mailmark.png";
+ generator.Save(outputPath, BarCodeImageFormat.Png);
- Console.WriteLine("Mailmark barcode generated: mailmark.png");
+ // Inform the user where the file was saved
+ Console.WriteLine($"Mailmark barcode saved to {outputPath}");
+ }
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-mailmark-barcode-with-default-settings-and-embed-image-into-pdf-document.cs b/postal-barcode-types/generate-mailmark-barcode-with-default-settings-and-embed-image-into-pdf-document.cs
index 61a8920..4f345ae 100644
--- a/postal-barcode-types/generate-mailmark-barcode-with-default-settings-and-embed-image-into-pdf-document.cs
+++ b/postal-barcode-types/generate-mailmark-barcode-with-default-settings-and-embed-image-into-pdf-document.cs
@@ -1,66 +1,71 @@
// Title: Generate Mailmark barcode and embed in PDF
-// Description: Demonstrates creating a Mailmark barcode with default settings and inserting it into a PDF document.
-// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, showcasing the use of ComplexBarcodeGenerator and MailmarkCodetext to produce Mailmark symbology. Typical use cases include embedding postal barcodes into documents such as PDFs for mailing automation. Developers often need to generate barcode images and combine them with other file formats using Aspose.Pdf.
+// Description: Demonstrates creating a Mailmark barcode with default settings using Aspose.BarCode, converting it to PNG, and embedding the image into a PDF document with Aspose.Pdf.
+// Category-Description: This example belongs to the Aspose.BarCode generation and Aspose.Pdf integration category. It shows how to use ComplexBarcodeGenerator with MailmarkCodetext to produce a barcode image, then use Aspose.Pdf Document to place the image into a PDF. Typical use cases include generating postal Mailmark barcodes for shipping labels and embedding them directly into PDF invoices or documents. Developers often need to combine barcode generation with PDF creation, using classes such as ComplexBarcodeGenerator, MailmarkCodetext, Document, Page, and Image.
// Prompt: Generate a Mailmark barcode with default settings and embed the image into a PDF document.
-// Tags: mailmark, barcode, pdf, aspose.barcode, aspose.pdf, complexbarcodegenerator, image-embedding
+// Tags: mailmark, barcode, generation, pdf, aspose.barcode, aspose.pdf, image, embedding
using System;
using System.IO;
-using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.ComplexBarcode;
using Aspose.Pdf;
+using Aspose.Pdf.Text;
///
-/// Example program that creates a Mailmark barcode and embeds it into a PDF file.
+/// Demonstrates generating a Mailmark barcode and embedding it into a PDF file.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a Mailmark barcode image and saves it inside a PDF document.
+ /// Entry point. Creates a Mailmark barcode, saves it as PNG in memory, and inserts it into a PDF.
///
static void Main()
{
- // Initialize MailmarkCodetext with required default values.
+ // Initialize Mailmark codetext with required default values
var mailmark = new MailmarkCodetext
{
- Format = 4, // 4‑state format
- VersionID = 1, // version
- Class = "0", // class (null/test)
- SupplychainID = 384224, // supply chain identifier
- ItemID = 16563762, // item identifier
- DestinationPostCodePlusDPS = "EF61AH8T " // known valid postcode+DP
+ // Mailmark 4‑state format
+ Format = 4,
+ VersionID = 1,
+ Class = "0",
+ SupplychainID = 384224,
+ ItemID = 16563762,
+ // Destination post code plus DPS must end with a space
+ DestinationPostCodePlusDPS = "EF61AH8T "
};
- // Generate the Mailmark barcode using ComplexBarcodeGenerator.
+ // Generate the barcode image and store it in a memory stream
using (var generator = new ComplexBarcodeGenerator(mailmark))
{
- // Produce the barcode image (Aspose.Drawing.Bitmap).
- using (var bitmap = generator.GenerateBarCodeImage())
+ using (var ms = new MemoryStream())
{
- // Save the bitmap to a memory stream in PNG format.
- using (var imageStream = new MemoryStream())
- {
- bitmap.Save(imageStream, Aspose.Drawing.Imaging.ImageFormat.Png);
- imageStream.Position = 0; // Reset stream position for reading.
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // Reset stream position for reading
- // Create a new PDF document and add a page.
- var pdfDoc = new Document();
+ // Create a new PDF document and add a page
+ using (var pdfDoc = new Document())
+ {
var page = pdfDoc.Pages.Add();
- // Create an Aspose.Pdf.Image from the barcode stream.
+ // Configure the image object to embed the barcode
var pdfImage = new Aspose.Pdf.Image
{
- ImageStream = imageStream
+ ImageStream = ms,
+ FixWidth = 200.0,
+ FixHeight = 100.0,
+ HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center,
+ Margin = new MarginInfo { Top = 20 }
};
- // Insert the image into the PDF page.
+ // Add the image to the page's paragraph collection
page.Paragraphs.Add(pdfImage);
- // Save the resulting PDF to disk.
- pdfDoc.Save("Mailmark.pdf");
+ // Save the PDF to disk
+ pdfDoc.Save("MailmarkBarcode.pdf");
}
}
}
+
+ Console.WriteLine("Mailmark barcode PDF generated: MailmarkBarcode.pdf");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-mailmark-barcodes-for-set-of-order-numbers-and-convert-each-image-to-base64-string.cs b/postal-barcode-types/generate-mailmark-barcodes-for-set-of-order-numbers-and-convert-each-image-to-base64-string.cs
index 87ce738..b9456a9 100644
--- a/postal-barcode-types/generate-mailmark-barcodes-for-set-of-order-numbers-and-convert-each-image-to-base64-string.cs
+++ b/postal-barcode-types/generate-mailmark-barcodes-for-set-of-order-numbers-and-convert-each-image-to-base64-string.cs
@@ -1,58 +1,69 @@
-// Title: Generate Mailmark barcodes and convert to Base64 strings
-// Description: Demonstrates creating Mailmark barcodes for a list of order numbers and encoding each barcode image as a Base64 string.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as Mailmark. It showcases the use of ComplexBarcodeGenerator, MailmarkCodetext, and image format handling to produce PNG images, a common requirement for embedding barcodes in web services or APIs. Developers often need to generate barcodes programmatically and transmit them as Base64 for JSON payloads or HTML img tags.
+// Title: Generate Mailmark barcodes and encode as Base64
+// Description: Demonstrates creating Mailmark barcodes for a list of order numbers using Aspose.BarCode and converting each PNG image to a Base64 string.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode symbologies such as Mailmark. It shows how to configure MailmarkCodetext, use ComplexBarcodeGenerator to render the barcode, and obtain the image data in memory. Developers working with postal services, logistics, or any system that requires Mailmark encoding can use this pattern to produce barcodes and embed them in web pages, emails, or APIs.
// Prompt: Generate Mailmark barcodes for a set of order numbers and convert each image to a Base64 string.
-// Tags: mailmark, barcode, generation, base64, png, aspnet, aspose.barcode, complexbarcode
+// Tags: mailmark, barcode, generation, base64, png, aspose.barcode, complexbarcode, csharp
using System;
+using System.Collections.Generic;
using System.IO;
-using Aspose.BarCode;
-using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode.Generation;
///
-/// Demonstrates generating Mailmark barcodes for a collection of order numbers
-/// and converting each barcode image to a Base64 string.
+/// Example program that creates Mailmark barcodes for a collection of order numbers
+/// and outputs each barcode image as a Base64‑encoded PNG string.
///
class Program
{
///
- /// Entry point of the example. Iterates through sample order numbers,
- /// creates a Mailmark barcode for each, and writes the Base64 representation to the console.
+ /// Entry point of the application. Generates barcodes, converts them to Base64,
+ /// and writes the results to the console.
///
- static void Main(string[] args)
+ static void Main()
{
- // Sample order numbers – in a real scenario these could come from a database or input source.
- int[] orderNumbers = new int[] { 1001, 1002, 1003, 1004, 1005 };
+ // Define a sample set of order numbers to encode.
+ List orderNumbers = new List { 100001, 100002, 100003, 100004, 100005 };
+
+ // Fixed Mailmark field values required for all barcodes.
+ const int format = 4; // Mailmark 4‑state format
+ const int versionId = 1; // Version identifier
+ const string mailClass = "0"; // Mail class code
+ const int supplyChainId = 384224; // Supply chain identifier
+ const string destinationPostCodePlusDps = "EF61AH8T "; // Destination postcode plus DPS (trailing space required)
- foreach (int order in orderNumbers)
+ // Iterate over each order number and generate its corresponding barcode.
+ foreach (int orderNumber in orderNumbers)
{
- // Prepare Mailmark codetext with required fields.
+ // Build the Mailmark codetext with both fixed and variable values.
var mailmark = new MailmarkCodetext
{
- Format = 4, // 4‑state barcode format.
- VersionID = 1, // Version identifier.
- Class = "0", // Service type / class.
- SupplychainID = 384224, // Example supply‑chain identifier.
- ItemID = order, // Use the order number as the item identifier.
- DestinationPostCodePlusDPS = "EF61AH8T " // Known‑valid postcode‑plus‑DPS.
+ Format = format,
+ VersionID = versionId,
+ Class = mailClass,
+ SupplychainID = supplyChainId,
+ ItemID = orderNumber,
+ DestinationPostCodePlusDPS = destinationPostCodePlusDps
};
- // Generate the Mailmark barcode and obtain its image as a Base64 string.
+ // Variable to hold the Base64 representation of the generated image.
+ string base64;
+
+ // Use ComplexBarcodeGenerator to create the barcode image in memory.
using (var generator = new ComplexBarcodeGenerator(mailmark))
{
using (var ms = new MemoryStream())
{
- // Save the barcode image to the memory stream in PNG format.
+ // Save the barcode as a PNG image into the memory stream.
generator.Save(ms, BarCodeImageFormat.Png);
- // Convert the image bytes to a Base64 string.
- string base64 = Convert.ToBase64String(ms.ToArray());
-
- // Output the result.
- Console.WriteLine($"Order: {order}, Base64: {base64}");
+ // Convert the raw image bytes to a Base64 string.
+ base64 = Convert.ToBase64String(ms.ToArray());
}
}
+
+ // Output the order number together with its Base64‑encoded barcode.
+ Console.WriteLine($"Order {orderNumber}: {base64}");
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-onecode-2-state-postal-barcode-using-8-digit-numeric-string-and-default-settings.cs b/postal-barcode-types/generate-onecode-2-state-postal-barcode-using-8-digit-numeric-string-and-default-settings.cs
index ac94c24..8a9b29a 100644
--- a/postal-barcode-types/generate-onecode-2-state-postal-barcode-using-8-digit-numeric-string-and-default-settings.cs
+++ b/postal-barcode-types/generate-onecode-2-state-postal-barcode-using-8-digit-numeric-string-and-default-settings.cs
@@ -1,53 +1,61 @@
-// Title: Generate OneCode 2‑state postal barcode with 8‑digit numeric string
-// Description: Demonstrates creating a OneCode 2‑state postal barcode using Aspose.BarCode with default settings.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on postal symbologies. It showcases the use of EncodeTypes, BaseEncodeType, and BarcodeGenerator classes to produce OneCode barcodes, a common requirement for mailing applications where developers need to generate compliant postal barcodes quickly.
+// Title: Generate OneCode 2‑state Postal Barcode with Default Settings
+// Description: Demonstrates creating a OneCode 2‑state postal barcode from an 8‑digit numeric string using Aspose.BarCode and saving it as a PNG image.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on postal symbologies. It showcases the use of the BarcodeGenerator class with EncodeTypes.OneCode to produce OneCode barcodes, a common requirement for postal automation. Developers often need to validate input length, ensure numeric data, and save the generated barcode in image formats for integration into mailing systems.
// Prompt: Generate a OneCode 2‑state postal barcode using an 8‑digit numeric string and default settings.
-// Tags: onecode, postal barcode, generation, png, aspose.barcode, csharp
+// Tags: onecode,postal,barcode,generation,aspnet,aspose.barcode,csharp,image
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating a OneCode 2‑state postal barcode using Aspose.BarCode.
+/// Example program that generates a OneCode 2‑state postal barcode and saves it as a PNG file.
///
class Program
{
///
- /// Entry point. Generates the barcode and saves it as a PNG file.
+ /// Entry point of the application. Generates the barcode and writes status messages to the console.
///
static void Main()
{
- // 8‑digit numeric string for the OneCode 2‑state postal barcode
+ // Define a sample 8‑digit numeric string to encode.
string codeText = "12345678";
// OneCode requires the codetext length to be exactly 20, 25, 29, or 31 digits.
- int length = codeText.Length;
- if (length != 20 && length != 25 && length != 29 && length != 31)
+ // Validate the length (and numeric content) before attempting generation.
+ if (!IsValidOneCodeLength(codeText))
{
- Console.WriteLine($"Invalid OneCode codetext length: {length}. Allowed lengths are 20, 25, 29, or 31 digits.");
+ Console.WriteLine("Error: OneCode barcode requires a numeric codetext of length 20, 25, 29, or 31 digits.");
+ Console.WriteLine($"Provided codetext length: {codeText.Length}");
return;
}
- // Resolve the OneCode symbology using reflection (EncodeTypes.OneCode)
- const string symbologyName = "OneCode";
- var field = typeof(EncodeTypes).GetField(symbologyName);
- if (field == null)
+ // Create a BarcodeGenerator with the OneCode symbology and the provided text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.OneCode, codeText))
{
- Console.WriteLine($"Symbology '{symbologyName}' not found in EncodeTypes.");
- return;
+ // Save the generated barcode image as a PNG file.
+ generator.Save("onecode.png");
}
- // Cast the reflected value to BaseEncodeType
- BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null);
+ Console.WriteLine("OneCode barcode generated successfully: onecode.png");
+ }
- // Generate the barcode with default settings
- using (var generator = new BarcodeGenerator(encodeType, codeText))
+ // Helper method to verify that the input text meets OneCode length and numeric requirements.
+ private static bool IsValidOneCodeLength(string text)
+ {
+ if (string.IsNullOrEmpty(text))
+ return false;
+
+ // Ensure every character is a digit.
+ foreach (char c in text)
{
- // Save the barcode image (default format is PNG)
- string outputPath = "onecode.png";
- generator.Save(outputPath);
- Console.WriteLine($"OneCode barcode saved to '{outputPath}'.");
+ if (!char.IsDigit(c))
+ return false;
}
+
+ // Allowed lengths for OneCode barcodes.
+ int length = text.Length;
+ return length == 20 || length == 25 || length == 29 || length == 31;
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-onecode-barcode-with-custom-dpi-of-300-and-save-as-high-resolution-png.cs b/postal-barcode-types/generate-onecode-barcode-with-custom-dpi-of-300-and-save-as-high-resolution-png.cs
index 8bd35d5..0d9ca6f 100644
--- a/postal-barcode-types/generate-onecode-barcode-with-custom-dpi-of-300-and-save-as-high-resolution-png.cs
+++ b/postal-barcode-types/generate-onecode-barcode-with-custom-dpi-of-300-and-save-as-high-resolution-png.cs
@@ -1,41 +1,37 @@
-// Title: Generate OneCode barcode with custom DPI and save as PNG
-// Description: Demonstrates creating a OneCode barcode, setting a 300 DPI resolution, and saving it as a high‑resolution PNG image.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on OneCode symbology. It showcases the use of BarcodeGenerator, EncodeTypes, and resolution settings to produce high‑quality images. Developers often need to generate barcodes for printing or digital display with specific DPI requirements, and this snippet illustrates the typical workflow.
+// Title: Generate OneCode barcode with custom 300 DPI PNG output
+// Description: Demonstrates creating a OneCode barcode, setting a custom resolution of 300 DPI, and saving it as a high‑resolution PNG image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class with EncodeTypes.OneCode. Developers often need to customize barcode resolution for print quality, export to high‑resolution image formats, and integrate barcode creation into automated workflows. Typical use cases include product labeling, inventory tracking, and document automation where high‑resolution output is required.
// Prompt: Generate a OneCode barcode with custom DPI of 300 and save as high‑resolution PNG.
-// Tags: onecode, barcode, generation, dpi, png, aspose.barcode
+// Tags: onecode, barcode, generation, resolution, dpi, png, aspose.barcode, csharp
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-namespace OneCodeExample
+///
+/// Example program that generates a OneCode barcode with a custom DPI and saves it as a PNG file.
+///
+class Program
{
///
- /// Provides an entry point that generates a OneCode barcode,
- /// configures a custom DPI of 300, and saves the result as a PNG file.
+ /// Entry point of the application. Creates the barcode, configures resolution, and writes the image to disk.
///
- class Program
+ static void Main()
{
- ///
- /// Main method that performs the barcode generation and saving process.
- ///
- static void Main()
- {
- // OneCode requires a numeric codetext of length 20, 25, 29, or 31.
- const string codeText = "12345678901234567890";
-
- // Initialize the barcode generator with OneCode symbology and the specified codetext.
- using (var generator = new BarcodeGenerator(EncodeTypes.OneCode, codeText))
- {
- // Set the image resolution to 300 DPI for high‑resolution output.
- generator.Parameters.Resolution = 300f;
+ // Define the numeric text to encode (20 digits, valid length for OneCode)
+ const string codeText = "12345678901234567890";
- // Save the generated barcode as a PNG image file.
- generator.Save("OneCode.png");
- }
+ // Initialize the BarcodeGenerator for OneCode symbology with the specified text
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.OneCode, codeText))
+ {
+ // Set the image resolution to 300 DPI for high‑quality output
+ generator.Parameters.Resolution = 300f;
- // Inform the user that the barcode has been saved.
- Console.WriteLine("OneCode barcode saved to OneCode.png");
+ // Save the generated barcode as a high‑resolution PNG file
+ generator.Save("OneCode.png");
}
+
+ // Inform the user that the barcode has been successfully created
+ Console.WriteLine("OneCode barcode generated and saved as OneCode.png");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-onecode-barcodes-from-collection-of-strings-and-embed-images-into-excel-worksheet.cs b/postal-barcode-types/generate-onecode-barcodes-from-collection-of-strings-and-embed-images-into-excel-worksheet.cs
index f80d59a..c1fad17 100644
--- a/postal-barcode-types/generate-onecode-barcodes-from-collection-of-strings-and-embed-images-into-excel-worksheet.cs
+++ b/postal-barcode-types/generate-onecode-barcodes-from-collection-of-strings-and-embed-images-into-excel-worksheet.cs
@@ -1,79 +1,90 @@
-// Title: Generate OneCode Barcodes and Embed into Excel
-// Description: Demonstrates creating OneCode barcodes from numeric strings and inserting them as images into an Excel worksheet using Aspose.BarCode and Aspose.Cells.
-// Category-Description: This example belongs to the Aspose.BarCode generation and Aspose.Cells integration category. It shows how to use BarcodeGenerator (EncodeTypes.OneCode) to produce PNG images, and how to embed those images into an Excel file via the Workbook and Pictures API. Developers often need to automate barcode creation and reporting in spreadsheets for inventory, tracking, or labeling scenarios.
+// Title: Generate OneCode barcodes and embed into Excel
+// Description: Demonstrates creating OneCode barcodes from numeric strings, converting them to PNG images, and inserting those images into an Excel worksheet using Aspose.BarCode and Aspose.Cells.
+// Category-Description: This example belongs to the Aspose.BarCode for .NET barcode generation category, focusing on image rendering and integration with spreadsheet documents. It showcases the use of BarcodeGenerator, EncodeTypes.OneCode, and Aspose.Cells workbook manipulation to embed barcode images. Developers working on inventory, tracking, or labeling solutions often need to generate barcodes and place them into Excel reports or templates, making this pattern a common requirement.
// Prompt: Generate OneCode barcodes from a collection of strings and embed the images into an Excel worksheet.
-// Tags: onecode, barcode, generation, excel, aspose.barcode, aspose.cells, png
+// Tags: onecode, barcode, generation, excel, aspose.barcode, aspose.cells, png, image embedding
using System;
using System.Collections.Generic;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Cells;
+using Aspose.Drawing;
using Aspose.Drawing.Imaging;
+using Aspose.Cells;
+using Aspose.Cells.Drawing;
///
-/// Program that generates OneCode barcodes from a list of strings and embeds them into an Excel worksheet.
+/// Example program that generates OneCode barcodes from a list of numeric strings
+/// and embeds the resulting PNG images into an Excel worksheet.
///
class Program
{
///
- /// Entry point. Creates barcodes, inserts them into an Excel file, and saves the workbook.
+ /// Entry point of the application.
+ /// Generates barcodes, adds them to a workbook, and saves the file.
///
static void Main()
{
- // Sample OneCode numeric strings (20, 25, 29, 31 digits)
- var oneCodeValues = new List
+ // Define a collection of OneCode numeric strings (20, 25, 29, 31 digits)
+ List codes = new List
{
- "12345678901234567890", // 20 digits
- "1234567890123456789012345", // 25 digits
- "12345678901234567890123456789", // 29 digits
- "1234567890123456789012345678901" // 31 digits
+ "12345678901234567890", // 20 digits
+ "1234567890123456789012345", // 25 digits
+ "12345678901234567890123456789", // 29 digits
+ "1234567890123456789012345678901" // 31 digits
};
- // Create a new Excel workbook
- using (var workbook = new Workbook())
- {
- var worksheet = workbook.Worksheets[0];
- worksheet.Name = "OneCode Barcodes";
+ // Create a new Excel workbook and get the first worksheet
+ Workbook workbook = new Workbook();
+ Worksheet sheet = workbook.Worksheets[0];
- // Header row
- worksheet.Cells[0, 0].PutValue("Code Text");
- worksheet.Cells[0, 1].PutValue("Barcode Image");
+ // Starting cell coordinates for the first barcode image
+ int startRow = 0;
+ int startColumn = 0;
- int rowIndex = 1; // start after header
-
- // Iterate over each code string and generate its barcode
- foreach (var code in oneCodeValues)
+ // Iterate over each code string, generate a barcode image, and embed it
+ foreach (string code in codes)
+ {
+ // Use a memory stream to hold the generated PNG image
+ using (MemoryStream imageStream = new MemoryStream())
{
- // Generate OneCode barcode for the current string
- using (var generator = new BarcodeGenerator(EncodeTypes.OneCode, code))
+ // Initialize the barcode generator for OneCode symbology
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.OneCode))
{
- // Enable automatic sizing using interpolation mode
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ generator.CodeText = code;
- // Save the generated barcode to a memory stream in PNG format
- using (var pngStream = new MemoryStream())
- {
- generator.Save(pngStream, BarCodeImageFormat.Png);
- pngStream.Position = 0; // Reset stream position for reading
-
- // Write the raw code text into the first column
- worksheet.Cells[rowIndex, 0].PutValue(code);
+ // OneCode requires an exact length; suppress exception for demonstration purposes
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false;
- // Insert the barcode image into the second column; the picture is anchored to the cell
- worksheet.Pictures.Add(rowIndex, 1, pngStream);
+ // Generate the barcode as a bitmap
+ using (Bitmap bitmap = generator.GenerateBarCodeImage())
+ {
+ // Save the bitmap to the memory stream in PNG format
+ bitmap.Save(imageStream, ImageFormat.Png);
}
}
- rowIndex++; // Move to the next row for the next barcode
+ // Reset the stream position before reading it back into the worksheet
+ imageStream.Position = 0;
+
+ // Add the PNG image to the worksheet at the specified cell
+ int pictureIndex = sheet.Pictures.Add(startRow, startColumn, imageStream);
+ Picture picture = sheet.Pictures[pictureIndex];
+ picture.Placement = PlacementType.FreeFloating;
+
+ // Add a textual label below the barcode image for reference
+ int labelRow = startRow + 5; // Adjust row offset as needed
+ sheet.Cells[labelRow, startColumn].PutValue(code);
}
- // Save the Excel file containing all barcodes
- workbook.Save("OneCodeBarcodes.xlsx");
+ // Advance the start row to provide spacing between successive barcode images
+ startRow += 15; // Space between images
}
- // Indicate completion
- Console.WriteLine("Excel file with OneCode barcodes has been created.");
+ // Save the populated workbook to an XLSX file
+ string outputPath = "OneCodeBarcodes.xlsx";
+ workbook.Save(outputPath, SaveFormat.Xlsx);
+ Console.WriteLine($"Workbook saved to {Path.GetFullPath(outputPath)}");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-planet-2-state-postal-barcode-image-with-custom-xdimension-and-default-bar-height.cs b/postal-barcode-types/generate-planet-2-state-postal-barcode-image-with-custom-xdimension-and-default-bar-height.cs
index ffb6ee3..0e63033 100644
--- a/postal-barcode-types/generate-planet-2-state-postal-barcode-image-with-custom-xdimension-and-default-bar-height.cs
+++ b/postal-barcode-types/generate-planet-2-state-postal-barcode-image-with-custom-xdimension-and-default-bar-height.cs
@@ -1,47 +1,40 @@
-// Title: Generate Planet 2‑state Postal Barcode with Custom XDimension
-// Description: Creates a Planet 2‑state postal barcode image using Aspose.BarCode, applying a custom XDimension while keeping the default bar height.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, demonstrating how to configure barcode parameters such as XDimension for postal symbologies. It showcases the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes, which developers commonly employ to produce printable barcode images for mailing and logistics applications.
+// Title: Generate Planet 2‑state postal barcode with custom XDimension
+// Description: Creates a Planet (2‑state postal) barcode image using Aspose.BarCode, setting a custom XDimension while keeping the default bar height.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, demonstrating how to configure symbology‑specific parameters such as XDimension for a Planet barcode. It showcases the use of the BarcodeGenerator class together with EncodeTypes to produce PNG output, a common task for developers needing to embed postal barcodes in documents or applications.
// Prompt: Generate a Planet 2‑state postal barcode image with custom XDimension and default bar height.
-// Tags: planet, postal, barcode, generation, png, xdimension
+// Tags: planet, barcode, 2-state, postal, xdimension, png, aspose.barcode, generation
using System;
-using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Demonstrates generation of a Planet 2‑state postal barcode with a custom XDimension.
+/// Demonstrates how to generate a Planet (2‑state postal) barcode image
+/// with a custom XDimension while using the default bar height.
///
class Program
{
///
- /// Entry point of the example. Generates and saves the barcode image.
+ /// Entry point of the example. Generates the barcode and saves it as a PNG file.
///
static void Main()
{
- // Define the output file name
- string outputPath = "planet.png";
+ // Define the data to encode in the Planet barcode.
+ const string codeText = "1234567890";
- // Resolve the full directory path and ensure it exists
- string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath));
- if (!Directory.Exists(outputDir))
+ // Initialize a BarcodeGenerator for the Planet symbology with the provided text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Planet, codeText))
{
- Directory.CreateDirectory(outputDir);
- }
-
- // Initialize the barcode generator for Planet symbology with sample data
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Planet, "1234567890"))
- {
- // Set a custom XDimension (module width) in points; 2 points = 0.028 mm
- generator.Parameters.Barcode.XDimension.Point = 2f;
+ // Set a custom XDimension (module size) of 2 points.
+ generator.Parameters.Barcode.XDimension.Point = 2f; // 2 points
- // No explicit BarHeight is set, so the default height is used
+ // No explicit BarHeight is set; the generator uses the default value.
- // Save the generated barcode as a PNG image
- generator.Save(outputPath, BarCodeImageFormat.Png);
+ // Save the generated barcode image to a PNG file.
+ generator.Save("planet.png");
}
- // Inform the user where the file was saved
- Console.WriteLine($"Planet barcode saved to {outputPath}");
+ // Inform the user that the barcode has been created.
+ Console.WriteLine("Planet barcode generated: planet.png");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-postal-barcode-and-embed-it-as-attachment-in-email-message-using-smtp-client.cs b/postal-barcode-types/generate-postal-barcode-and-embed-it-as-attachment-in-email-message-using-smtp-client.cs
index 2878ae0..a76e61f 100644
--- a/postal-barcode-types/generate-postal-barcode-and-embed-it-as-attachment-in-email-message-using-smtp-client.cs
+++ b/postal-barcode-types/generate-postal-barcode-and-embed-it-as-attachment-in-email-message-using-smtp-client.cs
@@ -1,8 +1,8 @@
-// Title: Generate Postal Barcode and Email as Attachment
-// Description: Demonstrates creating a Postnet barcode image and sending it as an email attachment via SMTP.
-// Category-Description: This example belongs to the Aspose.BarCode generation and email integration category. It shows how to use BarcodeGenerator (EncodeTypes) to create barcode images, save them, and then attach them to a MailMessage using System.Net.Mail. Typical use cases include automating mailing labels, shipping notifications, and integrating barcode generation into notification workflows. Developers often need to generate barcodes and embed them in communications, requiring knowledge of Aspose.BarCode classes and the .NET SMTP client.
+// Title: Generate Australia Post barcode and email as attachment
+// Description: Demonstrates creating an Australia Post (postal) barcode image and sending it via SMTP as an email attachment.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to use BarcodeGenerator with EncodeTypes.AustraliaPost, configure encoding tables, and save the image. It also shows integrating the generated barcode into a System.Net.Mail message for typical scenarios such as automated mailing of shipping labels. Developers often need to generate postal barcodes and embed them in emails for logistics workflows.
// Prompt: Generate a postal barcode and embed it as an attachment in an email message using SMTP client.
-// Tags: postal barcode, postnet, email attachment, smtp, aspose.barcode, generation, png
+// Tags: australia post barcode generation email smtp attachment image png
using System;
using System.IO;
@@ -10,68 +10,87 @@
using System.Net.Mail;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing.Imaging;
///
-/// Example program that generates a Postnet barcode image and sends it as an email attachment using SMTP.
+/// Generates an Australia Post barcode, saves it as a PNG file, and sends it as an email attachment using SMTP.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Creates the barcode, composes the email, sends it, and cleans up temporary files.
///
static void Main()
{
- // Define the file path for the generated barcode image.
- string barcodePath = "postal.png";
+ // Define barcode content and output file name
+ const string barcodeText = "5980123456AB"; // Sample data: FCC=59, DPID=8 digits, 2 CTable chars
+ const string barcodeFile = "postal_barcode.png";
- // Generate a Postal (Postnet) barcode with the data "12345".
- using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, "12345"))
+ // -------------------------------------------------
+ // Generate the Australia Post barcode and save it
+ // -------------------------------------------------
+ using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, barcodeText))
{
- // Save the barcode image as a PNG file.
- generator.Save(barcodePath);
+ // Use CTable encoding for customer information
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
+
+ // Save the barcode directly to a PNG file
+ generator.Save(barcodeFile, BarCodeImageFormat.Png);
}
- // Email configuration – replace placeholder values with real credentials and server details.
- string smtpHost = "smtp.example.com";
- int smtpPort = 587;
- string smtpUser = "user@example.com";
- string smtpPass = "password";
- string fromAddress = "sender@example.com";
- string toAddress = "recipient@example.com";
+ // -------------------------------------------------
+ // Prepare email message with the barcode attached
+ // -------------------------------------------------
+ var fromAddress = new MailAddress("sender@example.com", "Sender");
+ var toAddress = new MailAddress("recipient@example.com", "Recipient");
+ const string subject = "Australia Post Barcode Attachment";
+ const string body = "Please find the generated Australia Post barcode attached.";
- // Create the email message and set its properties.
using (var message = new MailMessage())
{
- message.From = new MailAddress(fromAddress);
+ message.From = fromAddress;
message.To.Add(toAddress);
- message.Subject = "Postal Barcode Attachment";
- message.Body = "Please find the generated postal barcode attached.";
+ message.Subject = subject;
+ message.Body = body;
- // Attach the barcode image if the file exists.
- if (File.Exists(barcodePath))
- {
- message.Attachments.Add(new Attachment(barcodePath));
- }
- else
+ // Attach the generated barcode image
+ using (var attachmentStream = new FileStream(barcodeFile, FileMode.Open, FileAccess.Read))
{
- Console.WriteLine($"Barcode file not found: {barcodePath}");
- }
+ var attachment = new Attachment(attachmentStream, "postal_barcode.png", "image/png");
+ message.Attachments.Add(attachment);
- // Configure the SMTP client and send the email.
- using (var client = new SmtpClient(smtpHost, smtpPort))
- {
- client.EnableSsl = true;
- client.Credentials = new NetworkCredential(smtpUser, smtpPass);
- try
- {
- client.Send(message);
- Console.WriteLine("Email sent successfully.");
- }
- catch (Exception ex)
+ // -------------------------------------------------
+ // Configure and use the SMTP client to send the email
+ // -------------------------------------------------
+ using (var smtp = new SmtpClient("smtp.example.com", 587))
{
- Console.WriteLine($"Failed to send email: {ex.Message}");
+ smtp.EnableSsl = true;
+ smtp.Credentials = new NetworkCredential("username", "password");
+
+ try
+ {
+ smtp.Send(message);
+ Console.WriteLine("Email sent successfully.");
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Failed to send email: {ex.Message}");
+ }
}
}
}
+
+ // -------------------------------------------------
+ // Clean up the temporary barcode file
+ // -------------------------------------------------
+ try
+ {
+ if (File.Exists(barcodeFile))
+ File.Delete(barcodeFile);
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Could not delete temporary file: {ex.Message}");
+ }
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-postal-barcode-and-embed-it-directly-into-existing-pdf-page-at-specified-coordinate.cs b/postal-barcode-types/generate-postal-barcode-and-embed-it-directly-into-existing-pdf-page-at-specified-coordinate.cs
index 3650876..2ae0b26 100644
--- a/postal-barcode-types/generate-postal-barcode-and-embed-it-directly-into-existing-pdf-page-at-specified-coordinate.cs
+++ b/postal-barcode-types/generate-postal-barcode-and-embed-it-directly-into-existing-pdf-page-at-specified-coordinate.cs
@@ -1,8 +1,8 @@
-// Title: Generate and embed a Postnet postal barcode into a PDF
-// Description: Demonstrates creating a Postnet barcode and placing it at a specific location within an existing PDF document.
-// Category-Description: This example belongs to the Aspose.BarCode for .NET PDF manipulation category, showcasing how to generate barcode images using BarcodeGenerator (EncodeTypes.Postnet) and embed them into PDF pages via Aspose.Pdf Document and Page classes. Typical use cases include adding shipping barcodes to invoices or labels directly in PDFs, a common requirement for logistics and e‑commerce applications.
+// Title: Generate and embed a Postnet barcode into a PDF
+// Description: This example creates a Postnet postal barcode and places it onto an existing PDF page at a specific location.
+// Category-Description: Demonstrates how to use Aspose.BarCode to generate barcode images and Aspose.Pdf to insert those images into PDF documents. Typical scenarios include adding shipping or mailing barcodes to invoices, labels, or reports. Developers often need to generate barcodes on‑the‑fly and embed them without creating intermediate files.
// Prompt: Generate a postal barcode and embed it directly into an existing PDF page at a specified coordinate.
-// Tags: postnet, barcode generation, pdf embedding, aspnet, aspose.barcode, aspose.pdf
+// Tags: postnet, barcode generation, pdf embedding, aspose.barcode, aspose.pdf, image insertion, c#
using System;
using System.IO;
@@ -11,64 +11,61 @@
using Aspose.Pdf;
///
-/// Example program that generates a Postnet barcode and embeds it into an existing PDF file.
+/// Demonstrates generating a Postnet barcode and embedding it into a PDF page.
///
class Program
{
///
- /// Entry point of the application. Generates the barcode, inserts it into the PDF, and saves the result.
+ /// Entry point. Generates a barcode, creates a placeholder PDF if needed, and embeds the barcode at defined coordinates.
///
- static void Main()
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
- // Define file paths for the source PDF and the resulting PDF
+ // Input and output PDF file paths
string inputPdfPath = "input.pdf";
string outputPdfPath = "output.pdf";
- // Ensure the source PDF exists before proceeding
+ // Ensure the input PDF exists; create a simple one if it does not.
if (!File.Exists(inputPdfPath))
{
- Console.WriteLine($"Input PDF not found: {inputPdfPath}");
- return;
+ using (var doc = new Document())
+ {
+ doc.Pages.Add(); // add a blank page
+ doc.Save(inputPdfPath);
+ }
}
- // Barcode configuration
- string postalCode = "12345"; // Postnet requires 5, 6 or 9 digits
- float llx = 100f; // Lower‑left X coordinate (points)
- float lly = 200f; // Lower‑left Y coordinate (points)
- float width = 150f; // Desired barcode image width (points)
- float height = 50f; // Desired barcode image height (points)
-
- // Create a BarcodeGenerator for the Postnet symbology
- using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, postalCode))
+ // Generate a postal barcode (Postnet) and embed it into the PDF.
+ // Sample code text "12345678" – adjust as needed.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, "12345678"))
{
- // Set visual appearance of the barcode
+ // Optional: set barcode colors
generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- // Render the barcode to a memory stream in PNG format
+ // Save barcode image to a memory stream in PNG format.
using (var barcodeStream = new MemoryStream())
{
generator.Save(barcodeStream, BarCodeImageFormat.Png);
- barcodeStream.Position = 0; // Reset stream position for reading
+ barcodeStream.Position = 0; // reset for reading
- // Load the existing PDF document
+ // Load the existing PDF and add the barcode image at specified coordinates.
using (var pdfDoc = new Document(inputPdfPath))
{
- // Access the first page (adjust index if a different page is required)
var page = pdfDoc.Pages[1];
- // Define the rectangle where the barcode image will be placed
- var rect = new Aspose.Pdf.Rectangle(llx, lly, llx + width, lly + height);
+ // Define placement rectangle: lower-left (100,500), upper-right (250,650)
+ var rect = new Aspose.Pdf.Rectangle(100, 500, 250, 650);
- // Insert the barcode image into the PDF page at the specified coordinates
+ // Add the image to the page.
page.AddImage(barcodeStream, rect);
- // Save the modified PDF to the output path
+ // Save the modified PDF.
pdfDoc.Save(outputPdfPath);
}
}
}
- Console.WriteLine($"Barcode embedded successfully. Output saved to: {outputPdfPath}");
+ Console.WriteLine($"Barcode embedded successfully. Output saved to '{outputPdfPath}'.");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-postal-barcode-and-store-it-as-blob-in-sql-server-database-table.cs b/postal-barcode-types/generate-postal-barcode-and-store-it-as-blob-in-sql-server-database-table.cs
index 627f05e..9e4c2be 100644
--- a/postal-barcode-types/generate-postal-barcode-and-store-it-as-blob-in-sql-server-database-table.cs
+++ b/postal-barcode-types/generate-postal-barcode-and-store-it-as-blob-in-sql-server-database-table.cs
@@ -1,66 +1,78 @@
-// Title: Generate and store a Postnet barcode as a PNG BLOB
-// Description: Demonstrates creating a Postnet postal barcode, converting it to PNG, and showing how to store it as a BLOB in SQL Server.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator, BarcodeParameters, and image handling classes. Typical use cases include generating postal barcodes for mailing systems and persisting them in databases. Developers often need to create barcode images, convert them to byte arrays, and insert them into SQL Server tables as VARBINARY data.
+// Title: Generate Australia Post Barcode and Save as BLOB
+// Description: Demonstrates how to create an Australia Post barcode using Aspose.BarCode, convert it to a PNG byte array, and store it as a binary BLOB (simulated via a file).
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to configure barcode parameters, render the barcode to an image stream, and obtain raw byte data for storage. Typical use cases include persisting barcodes in databases, transmitting them over networks, or embedding them in documents. Developers often work with BarcodeGenerator, EncodeTypes, and image format classes to produce and handle barcode images programmatically.
// Prompt: Generate a postal barcode and store it as a BLOB in a SQL Server database table.
-// Tags: postnet, postal barcode, barcode generation, image conversion, sql server, blob, aspose.barcode
+// Tags: barcode, australia post, generation, blob, sql server, aspose.barcode, png, memorystream
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Example program that generates a Postnet postal barcode,
-/// converts it to a PNG byte array, and demonstrates how it could be stored
-/// as a BLOB in a SQL Server database.
+/// Example program that generates an Australia Post barcode and saves it as a binary BLOB.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the application. Initiates barcode generation and storage.
///
static void Main()
{
- // Initialize the barcode generator for the Postnet symbology with the data "12345".
- using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, "12345"))
+ // Generate an Australia Post barcode and store it as a BLOB.
+ GenerateAndStoreBarcode();
+ }
+
+ ///
+ /// Creates a barcode, converts it to a PNG byte array, and writes the bytes to a file
+ /// to simulate storing the data in a SQL Server BLOB column.
+ ///
+ static void GenerateAndStoreBarcode()
+ {
+ // Sample valid Australia Post code text (FCC=59, DPID=8 digits, 2 CTable chars)
+ const string codeText = "5980123456AB";
+
+ // Initialize the barcode generator for the Australia Post symbology.
+ using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
{
- // Set a short bar height specific to postal barcodes (5 points).
- generator.Parameters.Barcode.Postal.PostalShortBarHeight.Point = 5f;
+ // Configure the encoding table to use the CTable customer information interpreting type.
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
- // Generate the barcode image as a Bitmap.
- using (Bitmap bitmap = generator.GenerateBarCodeImage())
+ // Render the barcode image into a memory stream in PNG format.
+ using (var memoryStream = new MemoryStream())
{
- // Prepare a memory stream to hold the PNG representation.
- using (var ms = new MemoryStream())
- {
- // Save the bitmap to the memory stream in PNG format.
- bitmap.Save(ms, ImageFormat.Png);
- byte[] imageBytes = ms.ToArray(); // Convert stream to byte array.
+ generator.Save(memoryStream, BarCodeImageFormat.Png);
+ byte[] barcodeBytes = memoryStream.ToArray();
- // -----------------------------------------------------------------
- // Example of inserting the PNG byte array into a SQL Server table:
- // -----------------------------------------------------------------
- // using (var connection = new SqlConnection("your_connection_string"))
- // {
- // connection.Open();
- // using (var command = new SqlCommand(
- // "INSERT INTO Barcodes (Id, Image) VALUES (@Id, @Image)", connection))
- // {
- // command.Parameters.Add("@Id", SqlDbType.Int).Value = 1;
- // command.Parameters.Add("@Image", SqlDbType.VarBinary).Value = imageBytes;
- // command.ExecuteNonQuery();
- // }
- // }
- // -----------------------------------------------------------------
- // Since the execution environment may lack SQL Server libraries,
- // write the PNG file locally for demonstration purposes.
+ // Simulate storing the byte array as a BLOB by writing it to a binary file.
+ const string blobFilePath = "barcode_blob.bin";
+ File.WriteAllBytes(blobFilePath, barcodeBytes);
+ Console.WriteLine($"Barcode BLOB saved to '{blobFilePath}' ({barcodeBytes.Length} bytes).");
- File.WriteAllBytes("postal_barcode.png", imageBytes);
- Console.WriteLine("Postal barcode generated and saved to postal_barcode.png");
- }
+ // Optionally save the PNG image for visual verification.
+ const string imageFilePath = "barcode.png";
+ File.WriteAllBytes(imageFilePath, barcodeBytes);
+ Console.WriteLine($"Barcode image saved to '{imageFilePath}'.");
}
}
+
+ /*
+ // Real SQL Server implementation (requires System.Data.SqlClient package and a reachable DB):
+ // string connectionString = "Data Source=SERVER;Initial Catalog=Database;Integrated Security=True;";
+ // using (var connection = new SqlConnection(connectionString))
+ // {
+ // connection.Open();
+ // string insertSql = "INSERT INTO Barcodes (Id, ImageBlob) VALUES (@Id, @Blob)";
+ // using (var command = new SqlCommand(insertSql, connection))
+ // {
+ // command.Parameters.Add("@Id", SqlDbType.Int).Value = 1;
+ // command.Parameters.Add("@Blob", SqlDbType.VarBinary, -1).Value = barcodeBytes;
+ // command.ExecuteNonQuery();
+ // }
+ // }
+ // Note: The above database code is commented out because the snippet runner does not have
+ // the necessary database libraries or environment to execute it.
+ */
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-postal-barcode-using-custom-color-scheme-defined-in-json-configuration-and-save-as-jpeg.cs b/postal-barcode-types/generate-postal-barcode-using-custom-color-scheme-defined-in-json-configuration-and-save-as-jpeg.cs
index 48cb9d3..eb35c25 100644
--- a/postal-barcode-types/generate-postal-barcode-using-custom-color-scheme-defined-in-json-configuration-and-save-as-jpeg.cs
+++ b/postal-barcode-types/generate-postal-barcode-using-custom-color-scheme-defined-in-json-configuration-and-save-as-jpeg.cs
@@ -1,8 +1,8 @@
-// Title: Generate Postal Barcode with Custom Colors
-// Description: Demonstrates creating a Postnet barcode using colors defined in a JSON file and saving it as a JPEG image.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode appearance via the BarcodeGenerator class, set bar and background colors, and serialize output to common image formats. Developers working with postal symbologies often need to customize visual styles for branding or readability, and this snippet shows the typical workflow using Aspose.BarCode and Aspose.Drawing APIs.
+// Title: Generate Australia Post barcode with custom colors from JSON
+// Description: Demonstrates loading bar and background colors from a JSON file, applying them to an Australia Post barcode, and saving the result as a JPEG image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to customize barcode appearance using the BarcodeGenerator class. It shows typical use cases such as reading configuration files, setting bar and background colors, and exporting to common image formats. Developers working with postal barcodes or needing dynamic visual styling can reference this pattern for quick implementation.
// Prompt: Generate a postal barcode using a custom color scheme defined in a JSON configuration and save as JPEG.
-// Tags: postal barcode, color customization, jpeg output, aspose.barcode, aspose.drawing, json configuration
+// Tags: barcode, australia post, color, json, jpeg, generation, aspose.barcode
using System;
using System.IO;
@@ -12,101 +12,94 @@
using Aspose.Drawing;
///
-/// Example program that generates a Postnet barcode using custom colors defined in a JSON configuration file
-/// and saves the result as a JPEG image.
+/// Demonstrates generating an Australia Post barcode with colors defined in a JSON configuration and saving it as a JPEG image.
///
class Program
{
- ///
- /// Entry point of the application.
- ///
- static void Main()
+ // Represents the JSON configuration for colors.
+ private class ColorConfig
{
- // Path to the JSON configuration file containing color definitions
- const string configPath = "config.json";
-
- // Verify that the configuration file exists before proceeding
- if (!File.Exists(configPath))
- {
- Console.WriteLine($"Configuration file not found: {configPath}");
- return;
- }
-
- // Read the JSON content from the file
- string json = File.ReadAllText(configPath);
+ public string BarColor { get; set; }
+ public string BackColor { get; set; }
+ }
- // Deserialize JSON into a strongly‑typed configuration object
- ColorConfig? config = JsonSerializer.Deserialize(json);
- if (config == null)
- {
- Console.WriteLine("Failed to parse configuration.");
- return;
- }
+ // Parses a hex color string (e.g., "#FF1122") into an Aspose.Drawing.Color.
+ private static Color ParseHexColor(string hex)
+ {
+ if (string.IsNullOrWhiteSpace(hex))
+ throw new ArgumentException("Hex color string is null or empty.");
- // Convert the color strings from the configuration into Aspose.Drawing.Color instances
- Aspose.Drawing.Color barColor = ParseColor(config.BarColor);
- Aspose.Drawing.Color backColor = ParseColor(config.BackColor);
+ // Remove leading '#', if present.
+ hex = hex.TrimStart('#');
- // Create a Postnet barcode generator with sample data ("12345")
- using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, "12345"))
- {
- // Apply the custom bar and background colors to the generator
- generator.Parameters.Barcode.BarColor = barColor;
- generator.Parameters.BackColor = backColor;
+ if (hex.Length != 6 && hex.Length != 8)
+ throw new ArgumentException($"Invalid hex color length: {hex}");
- // Save the generated barcode as a JPEG image file
- generator.Save("postal.jpg");
- }
+ // If only RRGGBB is provided, assume full opacity.
+ if (hex.Length == 6)
+ hex = "FF" + hex; // prepend alpha
- Console.WriteLine("Barcode generated and saved as postal.jpg");
+ // Parse ARGB integer.
+ uint argb = Convert.ToUInt32(hex, 16);
+ byte a = (byte)((argb >> 24) & 0xFF);
+ byte r = (byte)((argb >> 16) & 0xFF);
+ byte g = (byte)((argb >> 8) & 0xFF);
+ byte b = (byte)(argb & 0xFF);
+ return Color.FromArgb(a, r, g, b);
}
///
- /// Parses a color string (hex format like "#RRGGBB" or "#AARRGGBB", or a named color) into an Aspose.Drawing.Color.
- /// Returns Black if the input is null, empty, or whitespace.
+ /// Entry point. Loads color settings, creates the barcode, applies colors, and saves the image.
///
- /// The color string to parse.
- /// An Aspose.Drawing.Color representing the parsed color.
- private static Aspose.Drawing.Color ParseColor(string? value)
+ static void Main()
{
- if (string.IsNullOrWhiteSpace(value))
- return Aspose.Drawing.Color.Black;
+ // Path to the JSON configuration file.
+ const string configPath = "config.json";
- value = value.Trim();
+ // Default colors (black bars on white background).
+ Color barColor = Color.Black;
+ Color backColor = Color.White;
- if (value.StartsWith("#"))
+ // Load colors from JSON if the file exists.
+ if (File.Exists(configPath))
{
- string hex = value.TrimStart('#');
-
- // Support #RRGGBB format (no alpha component)
- if (hex.Length == 6)
+ try
{
- int r = Convert.ToInt32(hex.Substring(0, 2), 16);
- int g = Convert.ToInt32(hex.Substring(2, 2), 16);
- int b = Convert.ToInt32(hex.Substring(4, 2), 16);
- return Aspose.Drawing.Color.FromArgb(r, g, b);
+ string json = File.ReadAllText(configPath);
+ ColorConfig cfg = JsonSerializer.Deserialize(json);
+ if (cfg != null)
+ {
+ if (!string.IsNullOrWhiteSpace(cfg.BarColor))
+ barColor = ParseHexColor(cfg.BarColor);
+ if (!string.IsNullOrWhiteSpace(cfg.BackColor))
+ backColor = ParseHexColor(cfg.BackColor);
+ }
}
- // Support #AARRGGBB format (includes alpha component)
- else if (hex.Length == 8)
+ catch (Exception ex)
{
- int a = Convert.ToInt32(hex.Substring(0, 2), 16);
- int r = Convert.ToInt32(hex.Substring(2, 2), 16);
- int g = Convert.ToInt32(hex.Substring(4, 2), 16);
- int b = Convert.ToInt32(hex.Substring(6, 2), 16);
- return Aspose.Drawing.Color.FromArgb(a, r, g, b);
+ Console.WriteLine($"Failed to read or parse config file: {ex.Message}");
+ Console.WriteLine("Using default colors.");
}
}
+ else
+ {
+ Console.WriteLine("Config file not found. Using default colors.");
+ }
- // Fallback to a named color if the string is not a hex value
- return Aspose.Drawing.Color.FromName(value);
- }
+ // Sample Australia Post barcode text (FCC 59, DPID 12345678, CTable "AB").
+ const string codeText = "5912345678AB";
- ///
- /// Represents the JSON configuration for barcode colors.
- ///
- private class ColorConfig
- {
- public string? BarColor { get; set; }
- public string? BackColor { get; set; }
+ // Generate and save the barcode.
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, codeText))
+ {
+ // Apply custom colors.
+ generator.Parameters.Barcode.BarColor = barColor;
+ generator.Parameters.BackColor = backColor;
+
+ // Save as JPEG.
+ const string outputFile = "postal_barcode.jpg";
+ generator.Save(outputFile, BarCodeImageFormat.Jpeg);
+ Console.WriteLine($"Barcode saved to '{outputFile}'.");
+ }
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-postal-barcode-with-custom-font-for-human-readable-text-and-export-as-png.cs b/postal-barcode-types/generate-postal-barcode-with-custom-font-for-human-readable-text-and-export-as-png.cs
index c4bd799..782a3aa 100644
--- a/postal-barcode-types/generate-postal-barcode-with-custom-font-for-human-readable-text-and-export-as-png.cs
+++ b/postal-barcode-types/generate-postal-barcode-with-custom-font-for-human-readable-text-and-export-as-png.cs
@@ -1,52 +1,47 @@
-// Title: Generate Postal Barcode with Custom Font
-// Description: Demonstrates creating a Postnet barcode with a custom human‑readable font and exporting it as a PNG image.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to configure barcode parameters such as symbology, auto‑size mode, font styling, colors, and image output. It uses the BarcodeGenerator class and related parameter objects, which are commonly employed by developers to produce printable barcodes for mailing, shipping, and inventory applications.
+// Title: Generate Postal Barcode with Custom Font and PNG Output
+// Description: Demonstrates creating a Postnet postal barcode, applying a custom Helvetica font to the human‑readable text, and saving the result as a PNG image.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to configure barcode parameters such as code text location, font, size, and alignment using the BarcodeGenerator and its Parameters properties. Typical use cases include generating postal barcodes for mailing applications where custom styling of the human‑readable text is required. Developers often need to customize font attributes and export the barcode to common image formats like PNG.
// Prompt: Generate a postal barcode with a custom font for the human‑readable text and export as PNG.
-// Tags: postnet, barcode generation, custom font, png, aspose.barcode
+// Tags: postnet, custom-font, png, barcodegenerator, codetextparameters
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Example program that generates a Postnet postal barcode with a custom font for the
-/// human‑readable text and saves it as a PNG file.
+/// Example program that creates a Postnet postal barcode with a custom font for the human‑readable text
+/// and saves it as a PNG image.
///
class Program
{
///
- /// Entry point of the application. Creates the barcode, applies visual customizations,
- /// and writes the resulting image to disk.
+ /// Entry point of the example. Generates the barcode, configures text appearance, and writes the image file.
///
static void Main()
{
- // Define output file name and the sample ZIP+4 code to encode.
+ // Define output file name and the ZIP code to encode.
const string outputPath = "postal.png";
- const string codeText = "12345-6789"; // Example ZIP+4 code
+ const string codeText = "12345"; // ZIP code for Postnet
- // Initialize the barcode generator for the Postnet symbology.
+ // Initialize the barcode generator with Postnet symbology and the specified code text.
using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, codeText))
{
- // Enable auto‑size mode to let the library calculate optimal bar height.
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Position the human‑readable text below the barcode.
+ generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below;
- // Configure the appearance of the human‑readable text.
- generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Arial"; // Custom font name.
- generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 12f; // Font size.
- generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center;
- generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below; // Position text below bars.
+ // Set a custom, cross‑platform font (Helvetica) and size for the text.
+ generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Helvetica";
+ generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 12f;
- // Optional: set barcode and background colors.
- generator.Parameters.Barcode.BarColor = Color.Black;
- generator.Parameters.BackColor = Color.White;
+ // Center‑align the human‑readable text.
+ generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center;
// Save the generated barcode as a PNG image.
generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Inform the user that the file has been created.
- Console.WriteLine($"Postal barcode saved to '{outputPath}'.");
+ // Inform the user where the file was saved.
+ Console.WriteLine($"Barcode saved to {outputPath}");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-postal-barcode-with-custom-margin-settings-and-verify-image-dimensions-match-expectations.cs b/postal-barcode-types/generate-postal-barcode-with-custom-margin-settings-and-verify-image-dimensions-match-expectations.cs
index 17f400b..d10bbbc 100644
--- a/postal-barcode-types/generate-postal-barcode-with-custom-margin-settings-and-verify-image-dimensions-match-expectations.cs
+++ b/postal-barcode-types/generate-postal-barcode-with-custom-margin-settings-and-verify-image-dimensions-match-expectations.cs
@@ -1,8 +1,8 @@
-// Title: Generate Postnet Barcode with Custom Margins and Verify Image Size
-// Description: Creates a Postnet postal barcode, applies custom padding, saves as PNG, and checks that the resulting image dimensions meet the expected minimum based on the margins.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, demonstrating how to configure barcode appearance (padding, X‑dimension) and export to an image file. It uses BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes—common tools for developers who need to produce printable barcodes with precise layout requirements. Ideal for tutorials, reference guides, and search results about barcode image customization.
+// Title: Generate a Postnet postal barcode with custom margins and verify image size
+// Description: Demonstrates how to create a Postnet barcode, apply custom padding, set image dimensions, and confirm the saved PNG matches expected pixel size.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing barcode creation, layout customization, and image export. It uses BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes to configure symbology, margins, and output format—common tasks for developers integrating barcode printing or validation into applications.
// Prompt: Generate a postal barcode with custom margin settings and verify image dimensions match expectations.
-// Tags: postnet, barcode, margin, png, aspose.barcode, image verification
+// Tags: postnet, margin, image, generation, aspose.barcode, aspose.drawing
using System;
using System.IO;
@@ -12,64 +12,61 @@
using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating a Postnet barcode with custom margins,
-/// saving it as a PNG image, and verifying the resulting image dimensions.
+/// Example program that generates a Postnet postal barcode with custom margins,
+/// saves it as a PNG file, and verifies the resulting image dimensions.
///
class Program
{
///
- /// Entry point of the example. Creates the barcode, applies padding,
- /// saves the image, and performs a simple size verification.
+ /// Entry point of the example. Performs barcode generation, saves the image,
+ /// and checks that the image size matches the expected dimensions.
///
static void Main()
{
- // Define the output file path for the generated barcode image.
- string outputPath = "postal.png";
+ // Define the output file path for the generated barcode image
+ string outputPath = "postal_barcode.png";
- // Initialize a BarcodeGenerator for the Postnet symbology with sample data.
- using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, "12345"))
+ // Remove any existing file to ensure a clean run
+ if (File.Exists(outputPath))
{
- // Apply custom padding of 10 points on each side.
+ File.Delete(outputPath);
+ }
+
+ // Create a BarcodeGenerator for the Postnet symbology with sample data
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Postnet, "12345678"))
+ {
+ // Configure custom margins (padding) in points
generator.Parameters.Barcode.Padding.Left.Point = 10f;
- generator.Parameters.Barcode.Padding.Top.Point = 10f;
+ generator.Parameters.Barcode.Padding.Top.Point = 15f;
generator.Parameters.Barcode.Padding.Right.Point = 10f;
- generator.Parameters.Barcode.Padding.Bottom.Point = 10f;
+ generator.Parameters.Barcode.Padding.Bottom.Point = 15f;
- // Optionally adjust the X‑dimension to influence overall barcode size.
- generator.Parameters.Barcode.XDimension.Point = 2f;
+ // Set the desired image size (including margins) in points
+ generator.Parameters.ImageWidth.Point = 300f;
+ generator.Parameters.ImageHeight.Point = 150f;
- // Save the generated barcode as a PNG image.
+ // Save the barcode image to the specified path in PNG format
generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Verify that the image file was successfully created.
- if (!File.Exists(outputPath))
+ // Load the saved image to verify its dimensions
+ using (Bitmap bitmap = new Bitmap(outputPath))
{
- Console.WriteLine($"Error: Barcode image file '{outputPath}' was not created.");
- return;
- }
-
- // Load the saved image to retrieve its width and height in pixels.
- using (Image image = Image.FromFile(outputPath))
- {
- int width = image.Width;
- int height = image.Height;
-
- Console.WriteLine($"Barcode image dimensions: Width = {width} px, Height = {height} px");
+ // Calculate expected pixel dimensions.
+ // Aspose.Drawing uses pixels; points are converted using the default DPI (96).
+ const float dpi = 96f;
+ int expectedWidth = (int)Math.Round(300f * dpi / 72f);
+ int expectedHeight = (int)Math.Round(150f * dpi / 72f);
- // Expected minimum dimensions based on the total padding (10 + 10 points each side).
- const int expectedMinWidth = 20; // left + right padding
- const int expectedMinHeight = 20; // top + bottom padding
+ // Output actual vs. expected dimensions for diagnostic purposes
+ Console.WriteLine($"Actual Width: {bitmap.Width}px, Expected Width: {expectedWidth}px");
+ Console.WriteLine($"Actual Height: {bitmap.Height}px, Expected Height: {expectedHeight}px");
- // Simple verification: ensure the image dimensions are not smaller than the padding.
- if (width < expectedMinWidth || height < expectedMinHeight)
- {
- Console.WriteLine("Verification failed: Image dimensions are smaller than expected based on padding.");
- }
- else
- {
- Console.WriteLine("Verification succeeded: Image dimensions meet the expected minimum size.");
- }
+ // Determine whether the dimensions match the expectations
+ bool sizeMatches = bitmap.Width == expectedWidth && bitmap.Height == expectedHeight;
+ Console.WriteLine(sizeMatches
+ ? "Image dimensions match the expectations."
+ : "Image dimensions do NOT match the expectations.");
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-postal-barcode-with-transparent-background-and-save-as-png-with-alpha-channel.cs b/postal-barcode-types/generate-postal-barcode-with-transparent-background-and-save-as-png-with-alpha-channel.cs
index 5cf0fec..2be2a71 100644
--- a/postal-barcode-types/generate-postal-barcode-with-transparent-background-and-save-as-png-with-alpha-channel.cs
+++ b/postal-barcode-types/generate-postal-barcode-with-transparent-background-and-save-as-png-with-alpha-channel.cs
@@ -1,36 +1,56 @@
// Title: Generate a Postnet barcode with transparent background and save as PNG
-// Description: Demonstrates creating a Postnet postal barcode, applying a transparent background, and exporting it as a PNG image with an alpha channel.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on visual customization and image output. It showcases key API classes such as BarcodeGenerator, EncodeTypes, and the Parameters property to modify colors and save formats. Developers often need to generate barcodes for mailing, customize appearance, and produce images with transparency for web or print integration.
+// Description: This example creates a US Postal Service Postnet barcode, applies a transparent background, and saves the image as a PNG file that retains the alpha channel.
+// Category-Description: Demonstrates Aspose.BarCode generation for postal symbologies. It uses the BarcodeGenerator class with EncodeTypes.Postnet, configures visual parameters such as background and bar colors, and saves the result in a format supporting transparency (PNG). Typical use cases include creating shipping labels, mailing automation, and integrating barcode images into documents where a clear background is required. Developers working with barcode creation, especially for postal services, frequently need to control colors and output formats using the Aspose.BarCode API.
// Prompt: Generate a postal barcode with transparent background and save as PNG with alpha channel.
-// Tags: postnet, barcode generation, png, transparent background, aspose.barcode, aspnet
+// Tags: postnet, postal barcode, transparent background, png, alpha channel, aspose.barcode, barcode generation
using System;
-using Aspose.BarCode;
+using System.IO;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
///
-/// Example program that creates a Postnet barcode with a transparent background
-/// and saves it as a PNG file preserving the alpha channel.
+/// Demonstrates generating a Postnet barcode with a transparent background and saving it as a PNG image.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Generates the barcode and writes a confirmation message.
///
static void Main()
{
- // Initialize a BarcodeGenerator for the Postnet symbology with a sample ZIP code.
- using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, "12345"))
+ // Generate a postal (Postnet) barcode with transparent background and save as PNG.
+ GeneratePostalBarcode("postal.png", "12345");
+
+ // Inform the user that the barcode has been saved.
+ Console.WriteLine("Barcode saved to postal.png");
+ }
+
+ ///
+ /// Creates a Postnet barcode image with a transparent background and saves it as PNG.
+ ///
+ /// Full file path where the PNG image will be saved.
+ /// ZIP code data to encode in the barcode.
+ static void GeneratePostalBarcode(string outputPath, string zipCode)
+ {
+ // Ensure the output directory exists.
+ string directory = Path.GetDirectoryName(outputPath);
+ if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
+ {
+ Directory.CreateDirectory(directory);
+ }
+
+ // Initialize the barcode generator for Postnet symbology with the provided ZIP code.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, zipCode))
{
- // Set the background color to transparent so the PNG will have an alpha channel.
+ // Set the background to transparent so the PNG retains an alpha channel.
generator.Parameters.BackColor = Color.Transparent;
- // Ensure the barcode bars are drawn in black (default, but set explicitly for clarity).
+ // Optionally set the bar (foreground) color; black is the typical choice.
generator.Parameters.Barcode.BarColor = Color.Black;
- // Save the generated barcode as a PNG file; the transparent background is retained.
- generator.Save("postal.png");
+ // Save the generated barcode as a PNG image, which supports transparency.
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-postnet-2-state-postal-barcode-with-overridden-barheight-set-to-30-points.cs b/postal-barcode-types/generate-postnet-2-state-postal-barcode-with-overridden-barheight-set-to-30-points.cs
index ce3b440..5e253ff 100644
--- a/postal-barcode-types/generate-postnet-2-state-postal-barcode-with-overridden-barheight-set-to-30-points.cs
+++ b/postal-barcode-types/generate-postnet-2-state-postal-barcode-with-overridden-barheight-set-to-30-points.cs
@@ -1,33 +1,37 @@
// Title: Generate Postnet 2‑state barcode with custom bar height
-// Description: Demonstrates creating a Postnet 2‑state postal barcode and setting its bar height to 30 points.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on postal symbologies. It showcases the use of BarcodeGenerator, EncodeTypes, and barcode parameter customization (BarHeight). Developers often need to generate printable postal barcodes with specific dimensions for mailing applications.
+// Description: Demonstrates creating a Postnet 2‑state postal barcode and overriding the bar height to 30 points.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use the BarcodeGenerator class with EncodeTypes.Postnet to produce postal barcodes. Typical use cases include printing ZIP codes on mail pieces, customizing barcode dimensions, and exporting to image formats. Developers often need to control size properties such as BarHeight to meet mailing standards.
// Prompt: Generate a Postnet 2‑state postal barcode with overridden BarHeight set to 30 points.
-// Tags: postnet, barcode, generation, barheight, png, aspnet, aspnet.barcode, encodetypes
+// Tags: postnet, barcode, generation, barheight, png, aspose.barcode
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Demonstrates generating a Postnet 2‑state barcode with a custom bar height.
+/// Provides an entry point that creates a Postnet barcode with a custom bar height and saves it as a PNG file.
///
class Program
{
///
- /// Entry point. Creates a Postnet barcode, sets bar height to 30 points, and saves as PNG.
+ /// Generates a Postnet 2‑state barcode for a sample ZIP code, sets the bar height to 30 points, and writes the image to disk.
///
static void Main()
{
- // Initialize a Postnet barcode generator with sample code text
+ // Initialize a BarcodeGenerator for the Postnet symbology with a 5‑digit ZIP code.
using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, "12345"))
{
- // Override the default bar height to 30 points
+ // Disable automatic sizing so the explicit BarHeight value is applied.
+ generator.Parameters.AutoSizeMode = AutoSizeMode.None;
+
+ // Set the bar height to 30 points (1 point = 1/72 inch).
generator.Parameters.Barcode.BarHeight.Point = 30f;
- // Define the output file path and save the barcode as a PNG image
- string outputPath = "postnet.png";
- generator.Save(outputPath);
- Console.WriteLine($"Postnet barcode saved to {outputPath}");
+ // Save the generated barcode as a PNG image file.
+ generator.Save("postnet.png");
+
+ // Inform the user that the file has been created.
+ Console.WriteLine("Postnet barcode saved to postnet.png");
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-rm4scc-2-state-postal-barcode-and-disable-bar-filling-using-filledbars-false.cs b/postal-barcode-types/generate-rm4scc-2-state-postal-barcode-and-disable-bar-filling-using-filledbars-false.cs
index 75c1417..83a8c97 100644
--- a/postal-barcode-types/generate-rm4scc-2-state-postal-barcode-and-disable-bar-filling-using-filledbars-false.cs
+++ b/postal-barcode-types/generate-rm4scc-2-state-postal-barcode-and-disable-bar-filling-using-filledbars-false.cs
@@ -1,31 +1,41 @@
-// Title: Generate RM4SCC 2‑state postal barcode with outlined bars
-// Description: Demonstrates creating an RM4SCC barcode and disabling bar filling so only bar outlines are rendered.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode appearance using the BarcodeGenerator and its Parameters. It shows usage of EncodeTypes, BarcodeGenerator, and BarcodeParameters to produce postal barcodes, a common requirement for mailing applications where visual style customization is needed. Developers often search for examples on disabling filled bars, setting symbology, and exporting to image formats.
+// Title: Generate RM4SCC 2‑State Postal Barcode with Unfilled Bars
+// Description: Demonstrates how to create an RM4SCC postal barcode and disable bar filling so the bars are only outlined.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of EncodeTypes, BarcodeGenerator, and barcode appearance settings. Typical scenarios include generating postal barcodes for mail sorting and customizing visual styles such as unfilled (outline‑only) bars. Developers often need to adjust rendering options to meet printing or design requirements.
// Prompt: Generate an RM4SCC 2‑state postal barcode and disable bar filling using FilledBars false.
-// Tags: rm4scc, barcode, generation, filledbars, png, aspose.barcode
+// Tags: rm4scc, postal, barcode, generation, filledbars, png, aspose.barcode
using System;
-using Aspose.BarCode.Generation;
using Aspose.BarCode;
+using Aspose.BarCode.Generation;
///
-/// Demonstrates generating an RM4SCC 2‑state postal barcode with bar outlines only.
+/// Example program that creates an RM4SCC 2‑state postal barcode with unfilled bars
+/// and saves it as a PNG image.
///
class Program
{
///
- /// Entry point. Creates a BarcodeGenerator, disables bar filling, and saves the image.
+ /// Entry point of the example. Generates the barcode and writes the output file path to the console.
///
static void Main()
{
- // Initialize the generator for RM4SCC symbology with sample text.
- using (var generator = new BarcodeGenerator(EncodeTypes.RM4SCC, "AB12345"))
+ // Define a sample RM4SCC code text (13 characters: 2 letters, 9 digits, 2 letters)
+ string codeText = "AB123456789CD";
+
+ // Initialize the barcode generator for the RM4SCC symbology with the provided code text
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.RM4SCC, codeText))
{
- // Set FilledBars to false so bars are drawn as outlines rather than solid.
+ // Set the FilledBars property to false so bars are drawn as outlines only
generator.Parameters.Barcode.FilledBars = false;
- // Export the barcode to a PNG file.
- generator.Save("rm4scc.png");
+ // Specify the output file name and format (PNG)
+ string outputFile = "rm4scc.png";
+
+ // Render and save the barcode image to the file system
+ generator.Save(outputFile, BarCodeImageFormat.Png);
+
+ // Inform the user where the barcode image has been saved
+ Console.WriteLine($"RM4SCC barcode generated and saved to: {outputFile}");
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-rm4scc-barcodes-for-each-record-in-xml-file-and-write-output-to-multi-page-pdf.cs b/postal-barcode-types/generate-rm4scc-barcodes-for-each-record-in-xml-file-and-write-output-to-multi-page-pdf.cs
index e64af54..9ceff2d 100644
--- a/postal-barcode-types/generate-rm4scc-barcodes-for-each-record-in-xml-file-and-write-output-to-multi-page-pdf.cs
+++ b/postal-barcode-types/generate-rm4scc-barcodes-for-each-record-in-xml-file-and-write-output-to-multi-page-pdf.cs
@@ -1,124 +1,150 @@
-// Title: Generate RM4SCC barcodes from XML and embed into a multi‑page PDF
-// Description: Reads an XML file, extracts values, creates RM4SCC barcode images, and compiles them into a PDF document with one barcode per page.
-// Category-Description: Aspose.BarCode PDF generation examples – demonstrates how to use Aspose.BarCode.Generation.BarcodeGenerator with EncodeTypes.RM4SCC to create barcode images and embed them into an Aspose.Pdf.Document. Typical use cases include batch barcode creation from data sources such as XML, CSV, or databases, and producing printable PDF reports. Developers often need to combine barcode generation with PDF manipulation APIs to automate document workflows.
+// Title: Generate RM4SCC Barcodes from XML and Export to Multi‑Page PDF
+// Description: Demonstrates reading code values from an XML file, creating RM4SCC barcodes for each record, and compiling them into a multi‑page PDF document.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator (EncodeTypes.RM4SCC) together with Aspose.Pdf to produce printable barcode documents. Typical use cases include batch barcode creation for inventory, shipping, or labeling systems where data originates from XML sources. Developers often need to combine barcode rendering with PDF pagination, and this snippet illustrates the common workflow using Aspose.BarCode and Aspose.Pdf APIs.
// Prompt: Generate RM4SCC barcodes for each record in an XML file and write output to a multi‑page PDF.
-// Tags: rm4scc, barcode, xml, pdf, aspose.barcode, aspose.pdf, generation, batch
+// Tags: rm4scc, barcode, generation, pdf, aspose.barcode, aspose.pdf, xml, csharp
using System;
-using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
+using System.Collections.Generic;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Pdf;
-using Aspose.Pdf.Text;
///
-/// Demonstrates generating RM4SCC barcodes from an XML file and writing them to a multi‑page PDF.
+/// Example program that reads record codes from an XML file, generates RM4SCC barcodes,
+/// and writes them to a multi‑page PDF.
///
class Program
{
///
- /// Entry point of the example. Reads input XML, creates barcodes, and saves a PDF.
+ /// Entry point of the application.
///
- static void Main()
+ ///
+ /// Optional command‑line arguments:
+ /// args[0] – path to the input XML file (default: "records.xml").
+ /// args[1] – path to the output PDF file (default: "output.pdf").
+ ///
+ static void Main(string[] args)
{
- // Input and output file paths (fallback to defaults if not provided)
- string inputXmlPath = "input.xml";
- string outputPdfPath = "output.pdf";
+ // Determine input XML file path (first argument or default)
+ string xmlPath = args.Length > 0 ? args[0] : "records.xml";
- // Validate input XML file existence
- if (!File.Exists(inputXmlPath))
- {
- Console.WriteLine($"Input XML file not found: {Path.GetFullPath(inputXmlPath)}");
- return;
- }
+ // Determine output PDF file path (second argument or default)
+ string pdfPath = args.Length > 1 ? args[1] : "output.pdf";
- // Load XML and extract code texts (assumes value structure)
- List codeTexts = new List();
- try
- {
- XDocument doc = XDocument.Load(inputXmlPath);
- foreach (XElement record in doc.Descendants("Record"))
- {
- XElement codeElement = record.Element("Code");
- if (codeElement != null && !string.IsNullOrWhiteSpace(codeElement.Value))
- {
- codeTexts.Add(codeElement.Value.Trim());
- }
- }
- }
- catch (Exception ex)
+ // Ensure a sample XML file exists when none is provided
+ if (!File.Exists(xmlPath))
{
- Console.WriteLine($"Failed to parse XML: {ex.Message}");
- return;
+ CreateSampleXml(xmlPath);
}
- if (codeTexts.Count == 0)
+ // Load barcode text values from the XML file
+ List codeTexts = LoadCodeTexts(xmlPath);
+
+ // Limit the number of records to four as required by the example rule
+ if (codeTexts.Count > 4)
{
- Console.WriteLine("No records with element found in the XML.");
- return;
+ codeTexts = codeTexts.GetRange(0, 4);
}
- // Limit to 4 items for Aspose.Pdf evaluation mode
- int maxItems = Math.Min(codeTexts.Count, 4);
-
- // Prepare PDF document
- Document pdfDoc = new Document();
+ // Create a new PDF document that will hold the barcode pages
+ var pdfDoc = new Document();
- // Keep streams alive until after PDF is saved
- List barcodeStreams = new List();
+ // Keep references to memory streams until the PDF is saved
+ var streams = new List();
- // Generate barcodes and add them to PDF pages
- for (int i = 0; i < maxItems; i++)
+ // Iterate over each code value and generate a corresponding barcode page
+ foreach (string code in codeTexts)
{
- string code = codeTexts[i];
+ // Create a memory stream to hold the barcode image
+ var barcodeStream = new MemoryStream();
- // Generate RM4SCC barcode image into a memory stream
- MemoryStream ms = new MemoryStream();
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.RM4SCC, code))
+ // Generate the RM4SCC barcode and write it as PNG into the stream
+ using (var generator = new BarcodeGenerator(EncodeTypes.RM4SCC, code))
{
- // Optional visual settings
+ // Optional visual customizations
generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- generator.Parameters.Resolution = 300;
+ generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below;
+ generator.Parameters.Barcode.XDimension.Point = 2f;
- // Save as PNG to the stream
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset for reading
+ // Save the barcode image to the memory stream
+ generator.Save(barcodeStream, BarCodeImageFormat.Png);
}
- barcodeStreams.Add(ms);
+ // Reset stream position so it can be read by Aspose.Pdf
+ barcodeStream.Position = 0;
+ streams.Add(barcodeStream);
- // Add a new page and embed the barcode image
- Page page = pdfDoc.Pages.Add();
- Aspose.Pdf.Image pdfImage = new Aspose.Pdf.Image
+ // Add a new page to the PDF and place the barcode image on it
+ var page = pdfDoc.Pages.Add();
+ var pdfImage = new Aspose.Pdf.Image
{
- ImageStream = ms
- // Adjust size as needed; here we let the image keep its original dimensions
- // FixWidth and FixHeight can be set if a specific size is required
+ ImageStream = barcodeStream,
+ FixWidth = 200,
+ FixHeight = 200,
+ HorizontalAlignment = HorizontalAlignment.Center,
+ VerticalAlignment = VerticalAlignment.Center,
+ Margin = new MarginInfo { Top = 20 }
};
page.Paragraphs.Add(pdfImage);
}
- // Save the PDF
- try
- {
- pdfDoc.Save(outputPdfPath);
- Console.WriteLine($"PDF generated successfully: {Path.GetFullPath(outputPdfPath)}");
- }
- catch (Exception ex)
+ // Persist the assembled PDF document to the specified file path
+ pdfDoc.Save(pdfPath);
+
+ // Release all memory streams now that the PDF has been saved
+ foreach (var ms in streams)
{
- Console.WriteLine($"Failed to save PDF: {ex.Message}");
+ ms.Dispose();
}
- finally
+
+ Console.WriteLine($"PDF generated at: {Path.GetFullPath(pdfPath)}");
+ }
+
+ ///
+ /// Loads the values of the <Code> elements from each <Record> node in the XML file.
+ ///
+ /// Path to the XML file containing records.
+ /// List of code strings extracted from the XML.
+ static List LoadCodeTexts(string xmlFile)
+ {
+ var list = new List();
+ try
{
- // Dispose all memory streams
- foreach (var stream in barcodeStreams)
+ XDocument doc = XDocument.Load(xmlFile);
+ foreach (var elem in doc.Descendants("Record"))
{
- stream.Dispose();
+ var codeElem = elem.Element("Code");
+ if (codeElem != null)
+ {
+ list.Add(codeElem.Value.Trim());
+ }
}
}
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Error reading XML: {ex.Message}");
+ }
+ return list;
+ }
+
+ ///
+ /// Creates a simple sample XML file with a few entries for demonstration purposes.
+ ///
+ /// File path where the sample XML will be saved.
+ static void CreateSampleXml(string path)
+ {
+ var doc = new XDocument(
+ new XElement("Records",
+ new XElement("Record", new XElement("Code", "AB12C3")),
+ new XElement("Record", new XElement("Code", "D4E5F6")),
+ new XElement("Record", new XElement("Code", "G7H8I9"))
+ )
+ );
+ doc.Save(path);
+ Console.WriteLine($"Sample XML created at: {Path.GetFullPath(path)}");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcode-and-attach-service-description-as-metadata.cs b/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcode-and-attach-service-description-as-metadata.cs
index c3b5b98..389e34c 100644
--- a/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcode-and-attach-service-description-as-metadata.cs
+++ b/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcode-and-attach-service-description-as-metadata.cs
@@ -1,51 +1,48 @@
-// Title: Generate Swiss Post Parcel barcode with service description metadata
-// Description: Demonstrates creating a Swiss Post Parcel barcode, adding a service description as a caption, and saving it as a PNG image.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class with EncodeTypes.SwissPostParcel. Typical use cases include generating parcel barcodes for logistics, attaching additional service information, and customizing visual appearance. Developers often need to embed metadata such as service descriptions alongside barcodes for printing and scanning workflows.
+// Title: Generate Swiss Post Parcel Additional Service Barcode with Metadata
+// Description: Demonstrates how to create a Swiss Post Parcel barcode, embed an additional service code, and attach a human‑readable description as metadata.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of BarcodeGenerator with EncodeTypes.SwissPostParcel. It illustrates typical tasks such as setting CodeText, adding metadata via CodeTextParameters, and exporting the result to an image format. Developers working with postal barcode standards often need to generate service‑specific barcodes and embed descriptive information for downstream processing.
// Prompt: Generate a Swiss Post Parcel additional service code barcode and attach the service description as metadata.
-// Tags: barcode symbology, generation, png, aspose.barcode, swisspostparcel
+// Tags: swisspostparcel, barcode, generation, png, metadata, aspose.barcode, encode types
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
///
-/// Example program that generates a Swiss Post Parcel barcode,
-/// attaches a service description as a caption, and saves the result as a PNG file.
+/// Demonstrates generating a Swiss Post Parcel barcode with an additional service code and attaching a description as metadata.
///
class Program
{
///
- /// Entry point of the example. Creates and configures a BarcodeGenerator,
- /// adds a caption with the service description, and writes the barcode image to disk.
+ /// Entry point of the example. Creates the barcode and saves it as a PNG file.
///
static void Main()
{
- // Define the service code (10‑digit) and its human‑readable description.
- string serviceCode = "1234567890"; // Example service code
- string serviceDescription = "Express Delivery";
+ // Define the output file path for the generated barcode image
+ string outputPath = "SwissPostParcel.png";
- // Initialize the barcode generator for the Swiss Post Parcel symbology using the service code.
- using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, serviceCode))
+ // Ensure the directory for the output file exists
+ string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath));
+ if (!Directory.Exists(directory))
{
- // Set visual appearance: black bars on a white background.
- generator.Parameters.Barcode.BarColor = Color.Black;
- generator.Parameters.BackColor = Color.White;
+ Directory.CreateDirectory(directory);
+ }
- // Configure the caption that appears above the barcode to show the service description.
- generator.Parameters.CaptionAbove.Visible = true;
- generator.Parameters.CaptionAbove.Text = serviceDescription;
- generator.Parameters.CaptionAbove.Font.FamilyName = "Arial";
- generator.Parameters.CaptionAbove.Font.Size.Point = 10f;
- generator.Parameters.CaptionAbove.Alignment = TextAlignment.Center;
- generator.Parameters.CaptionAbove.TextColor = Color.DarkBlue;
+ // Initialize the barcode generator for the Swiss Post Parcel (additional service) symbology
+ using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel))
+ {
+ // Set the additional service code (replace with actual data as needed)
+ generator.CodeText = "1234567890";
- // Define the output file path and save the barcode as a PNG image.
- string outputPath = "SwissPostParcel.png";
- generator.Save(outputPath);
+ // Attach a human‑readable description as metadata to be displayed with the barcode
+ generator.Parameters.Barcode.CodeTextParameters.TwoDDisplayText = "Additional Service: Express Delivery";
- // Inform the user where the file was saved.
- Console.WriteLine($"Barcode saved to {outputPath}");
+ // Save the generated barcode image in PNG format
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
+
+ // Inform the user where the barcode image has been saved
+ Console.WriteLine($"Swiss Post Parcel barcode saved to: {outputPath}");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcode-in-code-128-format-with-human-readable-description.cs b/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcode-in-code-128-format-with-human-readable-description.cs
index 647453e..8da18ea 100644
--- a/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcode-in-code-128-format-with-human-readable-description.cs
+++ b/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcode-in-code-128-format-with-human-readable-description.cs
@@ -1,50 +1,50 @@
-// Title: Generate Swiss Post Parcel Additional Service Code Barcode (Code 128)
-// Description: Creates a Code 128 barcode for a Swiss Post parcel additional service code and adds a human‑readable caption.
-// Category-Description: This example demonstrates Aspose.BarCode generation of a Code 128 barcode with a caption, a common task when encoding Swiss Post parcel additional service codes. It showcases the BarcodeGenerator class, EncodeTypes enumeration, and caption configuration properties. Developers often need to produce printable barcodes with readable text for logistics and shipping applications.
+// Title: Generate Swiss Post Parcel additional service code barcode (Code 128) with human‑readable text
+// Description: Demonstrates how to create a Swiss Post Parcel additional service code barcode using Aspose.BarCode. The example configures human‑readable text and saves the result as a PNG image.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on specialized symbologies such as Swiss Post Parcel (Code 128). It shows how to set barcode parameters, customize text appearance, and export the image. Developers working with postal services, logistics, or custom barcode requirements can use these patterns to integrate barcode creation into .NET applications.
// Prompt: Generate a Swiss Post Parcel additional service code barcode in Code 128 format with human‑readable description.
-// Tags: barcode, code128, swisspost, additional service, caption, image, aspose.barcode, generation
+// Tags: barcode symbology, generation, png, aspose.barcode, code128, swisspostparcel
using System;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
///
-/// Demonstrates how to generate a Swiss Post parcel additional service code barcode
-/// in Code 128 format with a human‑readable caption using Aspose.BarCode.
+/// Demonstrates generating a Swiss Post Parcel additional service code barcode with human‑readable text.
///
class Program
{
///
- /// Entry point of the example. Generates the barcode image and saves it to disk.
+ /// Entry point that creates the barcode and saves it as a PNG file.
///
static void Main()
{
- // Sample Swiss Post Parcel additional service code (12 digits)
- const string parcelCode = "123456789012";
+ // Sample additional service code for Swiss Post Parcel (replace with real data as needed)
+ const string serviceCode = "1234567890123";
- // Human‑readable description that will appear below the barcode
- const string description = "Additional Service";
+ // Output file path for the generated barcode image
+ const string outputPath = "SwissPostParcel.png";
- // Initialise the barcode generator for Code128 with the parcel code as data
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, parcelCode))
+ // Initialize the barcode generator for Swiss Post Parcel (internally uses Code128 encoding)
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, serviceCode))
{
- // Set the X dimension (module width) to improve visual clarity
- generator.Parameters.Barcode.XDimension.Point = 2f;
-
- // Enable and configure the caption displayed below the barcode
- generator.Parameters.CaptionBelow.Visible = true;
- generator.Parameters.CaptionBelow.Alignment = TextAlignment.Center;
- generator.Parameters.CaptionBelow.Font.FamilyName = "Arial";
- generator.Parameters.CaptionBelow.Font.Size.Point = 10f;
- generator.Parameters.CaptionBelow.TextColor = Color.Black;
- generator.Parameters.CaptionBelow.Text = description;
-
- // Define the output file path and save the generated barcode image
- const string outputPath = "SwissPostParcel.png";
- generator.Save(outputPath);
-
- // Inform the user where the file was saved
- Console.WriteLine($"Barcode saved to {outputPath}");
+ // Position the human‑readable text below the barcode and center it
+ generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below;
+ generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center;
+
+ // Optional styling for the human‑readable text (font family and size)
+ generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Helvetica";
+ generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 12f;
+
+ // General barcode appearance settings
+ generator.Parameters.Barcode.XDimension.Point = 2f; // Module (X) size
+ generator.Parameters.Barcode.FilledBars = false; // Use non‑filled bars
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false;
+
+ // Save the generated barcode image as a PNG file
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
+
+ // Inform the user where the barcode image was saved
+ Console.WriteLine($"Swiss Post Parcel barcode saved to: {outputPath}");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcode-with-embedded-qr-code-for-supplementary-data.cs b/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcode-with-embedded-qr-code-for-supplementary-data.cs
index d70c3fc..9147c2d 100644
--- a/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcode-with-embedded-qr-code-for-supplementary-data.cs
+++ b/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcode-with-embedded-qr-code-for-supplementary-data.cs
@@ -1,67 +1,71 @@
// Title: Generate Swiss Post Parcel barcode with embedded QR code
-// Description: Demonstrates creating a Swiss Post Parcel Additional Service Code barcode and a QR code for supplementary data, then combining them into a single image.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator with EncodeTypes.SwissPostParcel and EncodeTypes.QR. It illustrates typical use cases such as combining multiple symbologies, adjusting dimensions, and saving the result as an image—common tasks for developers integrating postal and QR barcodes.
+// Description: Demonstrates creating a Swiss Post Parcel barcode and a QR code with supplementary data, then combining them into a single image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator with different symbologies (SwissPostParcel and QR) and combine multiple barcode images. Typical use cases include packaging labels that require a primary barcode plus an auxiliary QR code for tracking URLs or additional information. Developers often need to generate, customize, and merge barcode graphics for printing or digital distribution.
// Prompt: Generate a Swiss Post Parcel additional service code barcode with embedded QR code for supplementary data.
// Tags: swisspostparcel, qr, barcode generation, image composition, aspose.barcode, csharp
using System;
-using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating a Swiss Post Parcel Additional Service Code barcode with an embedded QR code and saving the combined image.
+/// Example program that creates a Swiss Post Parcel barcode, generates a QR code with
+/// supplementary tracking data, and merges both images side‑by‑side into a single PNG file.
///
class Program
{
///
- /// Entry point. Creates the Swiss Post barcode, QR code, merges them side‑by‑side, and writes the result to a PNG file.
+ /// Entry point of the example. Generates the barcodes, composes them, and saves the result.
///
static void Main()
{
- // Primary Swiss Post Parcel barcode (Additional Service Code)
- const string swissPostCodeText = "1234567890"; // example code text
- using (var swissGenerator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, swissPostCodeText))
- {
- // Optional: adjust size or colors if needed
- swissGenerator.Parameters.Barcode.XDimension.Point = 2f;
- swissGenerator.Parameters.ImageWidth.Point = 300f;
- swissGenerator.Parameters.ImageHeight.Point = 150f;
+ // Sample parcel identifier (Swiss Post Parcel service code) and supplementary tracking URL
+ string parcelCode = "1234567890123456";
+ string supplementaryData = "https://example.com/track/123456";
- using (var swissImage = swissGenerator.GenerateBarCodeImage())
+ // Create a Swiss Post Parcel barcode generator with the parcel identifier
+ using (var parcelGenerator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, parcelCode))
+ {
+ // Render the Swiss Post Parcel barcode to a bitmap
+ using (Bitmap parcelImage = parcelGenerator.GenerateBarCodeImage())
{
- // QR code for supplementary data
- const string qrSupplementText = "Supplementary Info";
- using (var qrGenerator = new BarcodeGenerator(EncodeTypes.QR, qrSupplementText))
+ // Create a QR code generator containing the supplementary tracking URL
+ using (var qrGenerator = new BarcodeGenerator(EncodeTypes.QR, supplementaryData))
{
- // Set QR error correction level
- qrGenerator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelM;
- qrGenerator.Parameters.ImageWidth.Point = 150f;
- qrGenerator.Parameters.ImageHeight.Point = 150f;
+ // Use high error correction level for better robustness of the QR code
+ qrGenerator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelH;
- using (var qrImage = qrGenerator.GenerateBarCodeImage())
+ // Render the QR code to a bitmap
+ using (Bitmap qrImage = qrGenerator.GenerateBarCodeImage())
{
- // Combine both images side by side
- int combinedWidth = swissImage.Width + qrImage.Width;
- int combinedHeight = Math.Max(swissImage.Height, qrImage.Height);
- using (var combinedBitmap = new Bitmap(combinedWidth, combinedHeight))
+ // Define spacing between the two barcodes
+ int margin = 10;
+
+ // Calculate dimensions for the combined image
+ int combinedWidth = parcelImage.Width + qrImage.Width + margin;
+ int combinedHeight = Math.Max(parcelImage.Height, qrImage.Height);
+
+ // Create a new bitmap to hold the combined image
+ using (Bitmap combined = new Bitmap(combinedWidth, combinedHeight))
{
- using (var graphics = Graphics.FromImage(combinedBitmap))
+ // Draw both barcode images onto the combined bitmap
+ using (Graphics g = Graphics.FromImage(combined))
{
// Fill background with white
- graphics.Clear(Aspose.Drawing.Color.White);
- // Draw Swiss Post barcode on the left
- graphics.DrawImage(swissImage, 0, 0, swissImage.Width, swissImage.Height);
- // Draw QR code on the right
- graphics.DrawImage(qrImage, swissImage.Width, 0, qrImage.Width, qrImage.Height);
+ g.Clear(Color.White);
+
+ // Center the parcel barcode vertically
+ g.DrawImage(parcelImage, 0, (combinedHeight - parcelImage.Height) / 2);
+
+ // Center the QR code vertically, positioned after the parcel barcode plus margin
+ g.DrawImage(qrImage, parcelImage.Width + margin, (combinedHeight - qrImage.Height) / 2);
}
- // Save the final combined barcode image
- const string outputPath = "SwissPostParcel_With_QR.png";
- combinedBitmap.Save(outputPath, ImageFormat.Png);
- Console.WriteLine($"Combined barcode saved to: {outputPath}");
+ // Save the combined image as PNG
+ string outputPath = "SwissPostParcelWithQR.png";
+ combined.Save(outputPath, ImageFormat.Png);
+ Console.WriteLine($"Combined barcode saved to {outputPath}");
}
}
}
diff --git a/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcodes-for-multiple-service-descriptions-and-save-as-svg-files.cs b/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcodes-for-multiple-service-descriptions-and-save-as-svg-files.cs
index c040522..f1e6429 100644
--- a/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcodes-for-multiple-service-descriptions-and-save-as-svg-files.cs
+++ b/postal-barcode-types/generate-swiss-post-parcel-additional-service-code-barcodes-for-multiple-service-descriptions-and-save-as-svg-files.cs
@@ -1,69 +1,69 @@
-// Title: Generate Swiss Post Parcel Service Barcodes as SVG
-// Description: Demonstrates creating Swiss Post Parcel additional service code barcodes for various service descriptions and saving them as SVG files.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use the BarcodeGenerator with EncodeTypes.SwissPostParcel. It covers setting visual parameters, handling output directories, and saving barcodes in vector SVG format—common tasks for developers integrating postal barcode printing into applications.
+// Title: Generate Swiss Post Parcel Service Barcodes and Save as SVG
+// Description: Demonstrates how to create Swiss Post Parcel barcodes for a list of service codes and export each barcode as an SVG file.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of BarcodeGenerator with EncodeTypes.SwissPostParcel. It illustrates typical scenarios such as batch barcode creation for logistics, customizing barcode dimensions, and exporting to vector formats like SVG. Developers working with postal services, shipping labels, or bulk barcode generation will find this pattern useful.
// Prompt: Generate Swiss Post Parcel additional service code barcodes for multiple service descriptions and save as SVG files.
-// Tags: swisspostparcel, barcode, generation, svg, aspose.barcode, encode types
+// Tags: barcode, swisspostparcel, svg, generation, aspose.barcode, encode types
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Generates Swiss Post Parcel additional service code barcodes for multiple service descriptions and saves them as SVG files.
+/// Example program that generates Swiss Post Parcel barcodes for multiple service codes and saves them as SVG files.
///
class Program
{
///
- /// Entry point of the example.
+ /// Entry point that creates barcodes for predefined service codes and writes them to the file system.
///
static void Main()
{
- // Define sample service descriptions and their corresponding Swiss Post Parcel code texts.
- var services = new (string Description, string CodeText)[]
+ // Define a set of sample service descriptions for Swiss Post Parcel additional services
+ string[] services = new[]
{
- ("Standard Delivery", "123456789012"),
- ("Express Delivery", "234567890123"),
- ("Cash on Delivery", "345678901234"),
- ("Registered Mail", "456789012345")
+ "A1", // Example service code
+ "B2", // Another service code
+ "C3D4", // Composite service code
+ "E5F6G7", // Longer service code
+ "H8I9J0K1L2" // Even longer service code
};
- // Ensure the output directory exists.
- string outputDir = "SwissPostParcelBarcodes";
- if (!Directory.Exists(outputDir))
+ // Determine the output folder path and ensure it exists
+ string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "SwissPostBarcodes");
+ if (!Directory.Exists(outputFolder))
{
- Directory.CreateDirectory(outputDir);
+ Directory.CreateDirectory(outputFolder);
}
- // Iterate over each service and generate its barcode.
- foreach (var service in services)
+ // Iterate over each service code and generate a corresponding barcode
+ foreach (string service in services)
{
- // Create a barcode generator for the Swiss Post Parcel symbology.
- using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, service.CodeText))
- {
- // Configure basic visual settings.
- generator.Parameters.Barcode.BarColor = Color.Black; // Barcode bars color
- generator.Parameters.BackColor = Color.White; // Background color
- generator.Parameters.Barcode.XDimension.Point = 2f; // Module size (point size)
+ // Sanitize the file name by removing invalid characters and replacing spaces with underscores
+ string safeFileName = string.Concat(service.Split(Path.GetInvalidFileNameChars()))
+ .Replace(' ', '_');
+ string outputPath = Path.Combine(outputFolder, $"{safeFileName}.svg");
- // Build a safe file name by replacing spaces with underscores.
- string safeDescription = service.Description.Replace(' ', '_');
- string outputPath = Path.Combine(outputDir, $"{safeDescription}.svg");
+ // Initialize the barcode generator for Swiss Post Parcel using the service description as the code text
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, service))
+ {
+ // Optionally adjust the module size (x-dimension) for better visual quality
+ generator.Parameters.Barcode.XDimension.Point = 2f;
- // Attempt to save the barcode as an SVG file.
+ // Attempt to save the barcode as an SVG file; handle potential licensing restrictions
try
{
generator.Save(outputPath, BarCodeImageFormat.Svg);
- Console.WriteLine($"Saved {service.Description} barcode to {outputPath}");
+ Console.WriteLine($"Saved barcode for service '{service}' to '{outputPath}'.");
}
catch (Exception ex)
{
- // Inform the user if the format is not supported (e.g., evaluation license limitation).
- Console.WriteLine($"Failed to save {service.Description} barcode as SVG: {ex.Message}");
+ // Notify the user if SVG export fails (e.g., due to evaluation license limitations)
+ Console.WriteLine($"Failed to save SVG for service '{service}': {ex.Message}");
}
}
}
+
+ Console.WriteLine("Barcode generation completed.");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-swiss-post-parcel-domestic-barcode-using-18-digit-code-starting-with-98-and-output-tiff.cs b/postal-barcode-types/generate-swiss-post-parcel-domestic-barcode-using-18-digit-code-starting-with-98-and-output-tiff.cs
index d6af5bf..f6111ea 100644
--- a/postal-barcode-types/generate-swiss-post-parcel-domestic-barcode-using-18-digit-code-starting-with-98-and-output-tiff.cs
+++ b/postal-barcode-types/generate-swiss-post-parcel-domestic-barcode-using-18-digit-code-starting-with-98-and-output-tiff.cs
@@ -1,31 +1,38 @@
// Title: Generate Swiss Post Parcel Domestic Barcode and Save as TIFF
-// Description: Demonstrates creating an 18‑digit Swiss Post Parcel domestic barcode (starting with 98) and saving it as a TIFF image using Aspose.BarCode.
-// Category-Description: This example belongs to the barcode generation category of Aspose.BarCode, showcasing how to use the BarcodeGenerator class with EncodeTypes.SwissPostParcel. Typical use cases include generating shipping labels for Swiss Post parcels, where an 18‑digit code beginning with "98" is required. Developers often need to create barcodes and export them to various image formats for integration into logistics workflows.
+// Description: Demonstrates how to create a Swiss Post Parcel domestic barcode from an 18‑digit code and save it as a TIFF image using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category. It shows how to use the BarcodeGenerator class with the EncodeTypes.SwissPostParcel symbology to produce printable barcodes. Typical use cases include generating shipping labels for Swiss Post parcels, where an 18‑digit numeric code starting with '98' is required. Developers often need to configure generator parameters, handle validation, and export the barcode to common image formats such as TIFF.
// Prompt: Generate a Swiss Post Parcel domestic barcode using an 18‑digit code starting with 98 and output TIFF.
-// Tags: swisspostparcel, barcode generation, tiff, aspose.barcode, encode types
+// Tags: barcode generation, swiss post parcel, tiff, aspose.barcode, encode types, image export
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Example program that generates a Swiss Post Parcel domestic barcode and saves it as a TIFF file.
+/// Demonstrates generation of a Swiss Post Parcel domestic barcode and saving it as a TIFF file.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point that creates the barcode and writes it to disk.
///
static void Main()
{
- // Define the 18‑digit Swiss Post Parcel domestic code (must start with "98")
- string code = "981234567890123456";
+ // Define an 18‑digit code for Swiss Post Parcel (must start with "98")
+ string codeText = "981234567890123456";
- // Initialize the barcode generator with the Swiss Post Parcel symbology and the provided code
- using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, code))
+ // Initialize the barcode generator with Swiss Post Parcel symbology and the code text
+ using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, codeText))
{
- // Save the generated barcode image in TIFF format to the file system
- generator.Save("SwissPostParcel.tiff");
+ // Allow the generator to proceed even if the code text is slightly off the strict format
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false;
+
+ // Specify the output file path and save the barcode as a TIFF image
+ string outputPath = "SwissPostParcel.tiff";
+ generator.Save(outputPath, BarCodeImageFormat.Tiff);
+
+ // Inform the user where the barcode image was saved
+ Console.WriteLine($"Barcode saved to {outputPath}");
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-swiss-post-parcel-domestic-barcode-using-original-identifier-and-add-custom-margin-around-image.cs b/postal-barcode-types/generate-swiss-post-parcel-domestic-barcode-using-original-identifier-and-add-custom-margin-around-image.cs
index 2309b93..770241c 100644
--- a/postal-barcode-types/generate-swiss-post-parcel-domestic-barcode-using-original-identifier-and-add-custom-margin-around-image.cs
+++ b/postal-barcode-types/generate-swiss-post-parcel-domestic-barcode-using-original-identifier-and-add-custom-margin-around-image.cs
@@ -1,50 +1,55 @@
// Title: Generate Swiss Post Parcel barcode with custom margins
-// Description: Demonstrates creating a Swiss Post Parcel domestic barcode using an original identifier and applying a custom margin around the generated image.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on Swiss Post symbologies. It showcases the use of BarcodeGenerator, EncodeTypes, and image formatting options such as padding and colors. Developers often need to generate postal barcodes for shipping labels and customize appearance for integration into documents or printing workflows.
+// Description: Demonstrates creating a Swiss Post Parcel domestic barcode using Aspose.BarCode, applying a custom margin around the image, and saving it as PNG.
+// Category-Description: This example belongs to the barcode generation category of Aspose.BarCode. It showcases the BarcodeGenerator class with EncodeTypes.SwissPostParcel, configuring barcode parameters such as padding and exception handling. Developers often need to generate postal barcodes for shipping labels and customize image layout, making this pattern useful for creating printable barcode graphics.
// Prompt: Generate a Swiss Post Parcel domestic barcode using original identifier and add a custom margin around the image.
// Tags: swisspostparcel, barcode, generation, padding, png, aspose.barcode
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
///
/// Example program that generates a Swiss Post Parcel barcode,
-/// applies custom margins, and saves the result as a PNG image.
+/// applies custom margins, and saves the result as a PNG file.
///
class Program
{
///
/// Entry point of the application.
- /// Generates the barcode and writes the output file path to the console.
///
static void Main()
{
- // Sample Swiss Post Parcel barcode identifier (original identifier format)
- const string codeText = "123456789012";
+ // Sample identifier for Swiss Post Parcel domestic barcode
+ const string codeText = "1234567890";
- // Output file path for the generated PNG image
- const string outputPath = "SwissPostParcel.png";
+ // Output file path for the generated barcode image
+ string outputPath = "SwissPostParcel.png";
- // Initialize the barcode generator with Swiss Post Parcel symbology and the identifier
+ // Ensure the output directory exists before saving the file
+ string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath));
+ if (!Directory.Exists(outputDir))
+ {
+ Directory.CreateDirectory(outputDir);
+ }
+
+ // Create the barcode generator with Swiss Post Parcel symbology
using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, codeText))
{
- // Configure custom margins (padding) – 10 points on each side
- generator.Parameters.Barcode.Padding.Left.Point = 10f;
- generator.Parameters.Barcode.Padding.Top.Point = 10f;
- generator.Parameters.Barcode.Padding.Right.Point = 10f;
- generator.Parameters.Barcode.Padding.Bottom.Point = 10f;
-
- // Optional: set background to white and bar color to black (default values)
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
-
- // Save the barcode image as a PNG file
- generator.Save(outputPath, BarCodeImageFormat.Png);
+ // Set custom margins (padding) around the barcode image (15 points on each side)
+ generator.Parameters.Barcode.Padding.Left.Point = 15f; // left margin
+ generator.Parameters.Barcode.Padding.Top.Point = 15f; // top margin
+ generator.Parameters.Barcode.Padding.Right.Point = 15f; // right margin
+ generator.Parameters.Barcode.Padding.Bottom.Point = 15f; // bottom margin
+
+ // Optional: prevent exception if the code text is slightly incorrect
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false;
+
+ // Save the barcode image as PNG to the specified path
+ generator.Save(outputPath);
}
// Inform the user where the barcode image has been saved
- Console.WriteLine($"Swiss Post Parcel barcode saved to: {outputPath}");
+ Console.WriteLine($"Swiss Post Parcel barcode saved to: {Path.GetFullPath(outputPath)}");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-swiss-post-parcel-domestic-barcode-using-original-identifier-string-and-save-as-png.cs b/postal-barcode-types/generate-swiss-post-parcel-domestic-barcode-using-original-identifier-string-and-save-as-png.cs
index 6f25d0a..5711bc6 100644
--- a/postal-barcode-types/generate-swiss-post-parcel-domestic-barcode-using-original-identifier-string-and-save-as-png.cs
+++ b/postal-barcode-types/generate-swiss-post-parcel-domestic-barcode-using-original-identifier-string-and-save-as-png.cs
@@ -1,35 +1,44 @@
-// Title: Generate Swiss Post Parcel barcode and save as PNG
-// Description: Demonstrates creating a Swiss Post Parcel domestic barcode from an original identifier string and saving it as a PNG image.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class with EncodeTypes.SwissPostParcel. Typical use cases include generating shipping labels for Swiss Post parcels. Developers often need to create barcodes from raw identifier data and export them to common image formats like PNG.
+// Title: Generate Swiss Post Parcel Barcode and Save as PNG
+// Description: Demonstrates creating a Swiss Post Parcel domestic barcode from an identifier string and saving it as a PNG image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class with EncodeTypes.SwissPostParcel to produce parcel barcodes. Typical use cases include preparing shipping labels for Swiss Post services, where developers need to encode parcel identifiers into machine‑readable barcodes. The snippet shows directory handling, barcode creation, and image export, common tasks for logistics and e‑commerce applications.
// Prompt: Generate a Swiss Post Parcel domestic barcode using original identifier string and save as PNG.
-// Tags: swisspostparcel, barcode generation, png output, aspose.barcode, csharp
+// Tags: barcode, swisspostparcel, generation, png, barcodegenerator, encode-types
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Example program that generates a Swiss Post Parcel barcode from an identifier string
-/// and saves the result as a PNG image file.
+/// Demonstrates generating a Swiss Post Parcel domestic barcode and saving it as a PNG file.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point that creates the barcode using a sample identifier and writes the image to disk.
///
static void Main()
{
- // Define the original identifier string for the Swiss Post Parcel barcode.
- string identifier = "1234567890123456";
+ // Sample identifier for Swiss Post Parcel domestic barcode
+ string identifier = "123456789012";
- // Initialize the barcode generator with the Swiss Post Parcel symbology and the identifier.
- using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, identifier))
+ // Output file path (PNG format)
+ string outputPath = "SwissPostParcel.png";
+
+ // Ensure the output directory exists
+ string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath));
+ if (!Directory.Exists(directory))
+ {
+ Directory.CreateDirectory(directory);
+ }
+
+ // Create a barcode generator for Swiss Post Parcel using the identifier
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, identifier))
{
- // Save the generated barcode image to a PNG file.
- generator.Save("SwissPostParcel.png");
+ // Save the generated barcode as a PNG image
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Inform the user that the barcode has been saved.
- Console.WriteLine("Swiss Post Parcel barcode saved as SwissPostParcel.png");
+ Console.WriteLine($"Swiss Post Parcel barcode saved to: {outputPath}");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-swiss-post-parcel-domestic-barcodes-for-list-of-18-digit-codes-writing-them-to-zip-archive.cs b/postal-barcode-types/generate-swiss-post-parcel-domestic-barcodes-for-list-of-18-digit-codes-writing-them-to-zip-archive.cs
index b8b908e..d5a64b3 100644
--- a/postal-barcode-types/generate-swiss-post-parcel-domestic-barcodes-for-list-of-18-digit-codes-writing-them-to-zip-archive.cs
+++ b/postal-barcode-types/generate-swiss-post-parcel-domestic-barcodes-for-list-of-18-digit-codes-writing-them-to-zip-archive.cs
@@ -1,8 +1,8 @@
-// Title: Generate Swiss Post Parcel domestic barcodes and package them into a ZIP file
-// Description: Demonstrates creating 18‑digit Swiss Post Parcel barcodes, validating input, and saving each barcode as a PNG image inside a ZIP archive.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, showcasing the use of BarcodeGenerator with EncodeTypes.SwissPostParcel, image export via BarCodeImageFormat.Png, and .NET ZipArchive for bundling outputs. Developers often need to batch‑create barcodes for shipping labels and archive them for distribution or storage.
+// Title: Generate Swiss Post Parcel Barcodes and Package into ZIP
+// Description: Demonstrates how to create Swiss Post Parcel domestic barcodes from 18‑digit codes and store the PNG images in a ZIP archive.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, showcasing how to use BarcodeGenerator with EncodeTypes.SwissPostParcel to produce barcode images. Typical use cases include batch creation of shipping labels, parcel tracking codes, and integration with logistics workflows. Developers often need to generate multiple barcodes, choose image formats, and archive results for distribution or storage.
// Prompt: Generate Swiss Post Parcel domestic barcodes for a list of 18‑digit codes, writing them to a ZIP archive.
-// Tags: swisspostparcel, barcode generation, png, zip, aspose.barcode, barcodegenerator, ziparchive
+// Tags: swisspostparcel, barcode-generation, png, zip, aspose.barcode, aspose.drawing
using System;
using System.Collections.Generic;
@@ -10,20 +10,22 @@
using System.IO.Compression;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Program that generates Swiss Post Parcel domestic barcodes from a list of 18‑digit codes
-/// and stores the resulting PNG images in a ZIP archive.
+/// Example program that generates Swiss Post Parcel barcodes for a set of 18‑digit codes
+/// and writes the resulting PNG images into a ZIP archive.
///
-public class Program
+class Program
{
///
- /// Entry point. Generates barcodes, validates codes, and writes them to a ZIP file.
+ /// Entry point of the application. Generates barcodes, packages them into a ZIP file,
+ /// and writes the archive to disk.
///
- public static void Main()
+ static void Main()
{
- // Sample list of 18‑digit Swiss Post Parcel domestic codes
- var codes = new List
+ // Define a sample list of 18‑digit Swiss Post Parcel codes (domestic)
+ List parcelCodes = new List
{
"123456789012345678",
"987654321098765432",
@@ -32,68 +34,48 @@ public static void Main()
"333333333333333333"
};
- // Destination ZIP file path
- string zipPath = "SwissPostParcelBarcodes.zip";
-
- // Remove existing archive if present to avoid conflicts
- if (File.Exists(zipPath))
- {
- File.Delete(zipPath);
- }
-
- // Create a new ZIP archive and add generated barcode images
- using (var zipFile = new FileStream(zipPath, FileMode.CreateNew))
+ // Prepare a memory stream that will hold the ZIP archive in memory
+ using (MemoryStream zipStream = new MemoryStream())
{
- using (var archive = new ZipArchive(zipFile, ZipArchiveMode.Create, leaveOpen: false))
+ // Create the ZIP archive in write mode; leave the stream open after disposing the archive
+ using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
{
- int index = 1;
- foreach (var code in codes)
+ // Iterate over each parcel code and generate a barcode image
+ foreach (string code in parcelCodes)
{
- // Validate that the code consists of exactly 18 digits
- if (code == null || code.Length != 18 || !IsAllDigits(code))
+ // Initialize the barcode generator for Swiss Post Parcel symbology
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, code))
{
- Console.WriteLine($"Skipping invalid code: {code}");
- continue;
- }
-
- // Generate barcode image in memory using Aspose.BarCode
- using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, code))
- {
- using (var imageStream = new MemoryStream())
+ // Save the generated barcode to a memory stream in PNG format
+ using (MemoryStream imageStream = new MemoryStream())
{
- // Save the barcode as PNG to the memory stream
generator.Save(imageStream, BarCodeImageFormat.Png);
- imageStream.Position = 0;
-
- // Define entry name with zero‑padded index
- string entryName = $"Barcode_{index:D3}.png";
+ imageStream.Position = 0; // Reset stream position for reading
- // Create a new entry in the ZIP archive
- var entry = archive.CreateEntry(entryName, CompressionLevel.Optimal);
- using (var entryStream = entry.Open())
+ // Create a new entry in the ZIP archive for this barcode image
+ ZipArchiveEntry entry = zip.CreateEntry($"{code}.png");
+ using (Stream entryStream = entry.Open())
{
- // Copy the PNG data into the ZIP entry
+ // Copy the PNG image data into the ZIP entry
imageStream.CopyTo(entryStream);
}
}
}
-
- index++;
}
}
- }
- Console.WriteLine($"Barcodes have been saved to '{zipPath}'.");
- }
+ // Define the output path for the ZIP archive
+ string zipPath = "SwissPostParcelBarcodes.zip";
- // Helper method to ensure a string contains only digit characters
- private static bool IsAllDigits(string s)
- {
- foreach (char c in s)
- {
- if (c < '0' || c > '9')
- return false;
+ // Write the in‑memory ZIP archive to a file on disk
+ using (FileStream file = new FileStream(zipPath, FileMode.Create, FileAccess.Write))
+ {
+ zipStream.Position = 0; // Ensure we start copying from the beginning
+ zipStream.CopyTo(file);
+ }
+
+ // Inform the user where the ZIP archive was created
+ Console.WriteLine($"ZIP archive created: {Path.GetFullPath(zipPath)}");
}
- return true;
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-swiss-post-parcel-international-barcode-with-automatic-checksum-correction-and-save-as-jpeg.cs b/postal-barcode-types/generate-swiss-post-parcel-international-barcode-with-automatic-checksum-correction-and-save-as-jpeg.cs
index 1ef0536..1a7c434 100644
--- a/postal-barcode-types/generate-swiss-post-parcel-international-barcode-with-automatic-checksum-correction-and-save-as-jpeg.cs
+++ b/postal-barcode-types/generate-swiss-post-parcel-international-barcode-with-automatic-checksum-correction-and-save-as-jpeg.cs
@@ -1,45 +1,55 @@
-// Title: Generate Swiss Post Parcel International barcode with checksum correction
-// Description: Demonstrates creating a Swiss Post Parcel barcode, automatically correcting its checksum, and saving it as a JPEG image.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator with EncodeTypes.SwissPostParcel. It shows how to configure automatic checksum handling and export the result to a JPEG file, a common requirement for integrating barcode images into documents, web pages, or printing workflows.
+// Title: Generate Swiss Post Parcel Barcode and Save as JPEG
+// Description: Demonstrates creating a Swiss Post Parcel international barcode with automatic checksum correction and exporting it to a JPEG image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use the BarcodeGenerator class with EncodeTypes.SwissPostParcel. Typical use cases include creating shipping labels for Swiss Post parcels where the barcode must include a valid checksum. Developers often need to enable checksum generation and handle incorrect code text gracefully, then save the result in common image formats such as JPEG.
// Prompt: Generate a Swiss Post Parcel international barcode with automatic checksum correction and save as JPEG.
-// Tags: swisspostparcel, barcode, generation, jpeg, checksum, aspnet, aspnetcore, aspose.barcode
+// Tags: barcode, swisspostparcel, checksum, jpeg, aspose.barcode, generation
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing.Imaging;
///
-/// Example program that generates a Swiss Post Parcel International barcode,
-/// lets the library automatically correct the checksum, and saves the result as a JPEG image.
+/// Example program that generates a Swiss Post Parcel barcode,
+/// automatically corrects the checksum, and saves the image as JPEG.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the application. Calls the barcode generation routine.
///
static void Main()
{
- // Define the raw code text; the library will adjust the checksum if needed.
- const string codeText = "1234567890123456";
-
- // Specify the output file path for the generated JPEG image.
- const string outputPath = "SwissPostParcel.jpeg";
+ // Generate a Swiss Post Parcel barcode and save it as JPEG.
+ GenerateSwissPostParcelBarcode();
+ }
- // Choose the Swiss Post Parcel symbology for barcode generation.
- BaseEncodeType symbology = EncodeTypes.SwissPostParcel;
+ ///
+ /// Creates a Swiss Post Parcel barcode with checksum enabled,
+ /// suppresses exceptions for incorrect code text, and writes the result to a JPEG file.
+ ///
+ static void GenerateSwissPostParcelBarcode()
+ {
+ // Sample code text; Aspose will correct checksum automatically.
+ const string codeText = "1234567890123";
- // Initialize the barcode generator with the selected symbology and code text.
- using (var generator = new BarcodeGenerator(symbology, codeText))
+ // Initialize the barcode generator for Swiss Post Parcel symbology.
+ using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, codeText))
{
- // Automatic checksum correction is enabled by default.
- // If you need to enforce strict validation, you could set:
- // generator.Parameters.ThrowExceptionWhenCodeTextIncorrect = false;
+ // Enable checksum generation for the barcode.
+ generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes;
- // Save the generated barcode image as a JPEG file.
+ // Allow automatic correction of incorrect code text (no exception thrown).
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false;
+
+ // Define the output file path.
+ const string outputPath = "SwissPostParcel.jpg";
+
+ // Save the generated barcode as a JPEG image.
generator.Save(outputPath, BarCodeImageFormat.Jpeg);
- }
- // Inform the user where the barcode image has been saved.
- Console.WriteLine($"Swiss Post Parcel barcode saved to: {outputPath}");
+ // Inform the user where the file was saved.
+ Console.WriteLine($"Barcode saved to {outputPath}");
+ }
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-swiss-post-parcel-international-barcode-with-checksum-auto-correction-and-store-in-cloud-storage-bucket.cs b/postal-barcode-types/generate-swiss-post-parcel-international-barcode-with-checksum-auto-correction-and-store-in-cloud-storage-bucket.cs
index d895853..1636274 100644
--- a/postal-barcode-types/generate-swiss-post-parcel-international-barcode-with-checksum-auto-correction-and-store-in-cloud-storage-bucket.cs
+++ b/postal-barcode-types/generate-swiss-post-parcel-international-barcode-with-checksum-auto-correction-and-store-in-cloud-storage-bucket.cs
@@ -1,63 +1,63 @@
-// Title: Generate Swiss Post Parcel barcode with auto‑checksum correction and cloud storage upload
-// Description: Demonstrates creating a Swiss Post Parcel international barcode, enabling automatic checksum correction, and saving the image for later upload to a cloud storage bucket.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on symbology‑specific settings and image output. It showcases the use of BarcodeGenerator, EncodeTypes, and image format classes to produce barcodes, a common task for developers integrating barcode creation into applications that require storage in cloud services such as Azure Blob or AWS S3.
+// Title: Generate Swiss Post Parcel Barcode with Auto‑Checksum and Save to Cloud
+// Description: Demonstrates how to create a Swiss Post Parcel (international) barcode, enable automatic checksum correction, and save the image as PNG.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category. It shows how to use the BarcodeGenerator class with EncodeTypes.SwissPostParcel, configure checksum settings, and export the result to an image file. Developers working with postal symbologies often need to generate barcodes that comply with specific standards and then store them in cloud storage for downstream processing.
// Prompt: Generate a Swiss Post Parcel international barcode with checksum auto‑correction and store in a cloud storage bucket.
-// Tags: swisspostparcel, barcode, generation, checksum, auto-correction, png, cloud-storage, aspose.barcode
+// Tags: barcode, swisspostparcel, checksum, image, png, cloud, aspose.barcode, generation
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
/// Example program that generates a Swiss Post Parcel barcode,
-/// enables automatic checksum correction, saves the image locally,
-/// and outlines how to upload it to a cloud storage bucket.
+/// enables automatic checksum correction, saves it as a PNG file,
+/// and provides a placeholder for uploading the file to cloud storage.
///
class Program
{
///
- /// Entry point of the example. Generates the barcode and saves it as a PNG file.
+ /// Entry point of the example. Generates the barcode and writes the image to disk.
///
static void Main()
{
- // Define a sample Swiss Post Parcel code.
- // Replace with a valid code as required by your use case.
- string codeText = "123456789012";
+ // Define the raw data for the Swiss Post Parcel (international) barcode.
+ // In a real scenario, this should follow the Swiss Post specification.
+ string codeText = "1234567890123";
// Initialize the barcode generator for the Swiss Post Parcel symbology.
using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, codeText))
{
- // Allow the generator to auto‑correct the checksum instead of throwing an exception.
+ // Allow the generator to automatically correct the checksum
+ // instead of throwing an exception for incorrect code text.
generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false;
- // Optional visual customizations.
- generator.Parameters.Barcode.BarColor = Color.Black; // Set barcode bars to black.
- generator.Parameters.BackColor = Color.White; // Set background to white.
- generator.Parameters.Barcode.XDimension.Point = 2f; // Define module (X) size.
+ // Enable checksum generation (required for most postal barcodes).
+ generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes;
- // Determine the output file path in the current working directory.
+ // Build the full path for the output PNG file.
string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "SwissPostParcel.png");
- // Save the generated barcode as a PNG image.
+ // Save the generated barcode image to the specified path in PNG format.
generator.Save(outputPath, BarCodeImageFormat.Png);
Console.WriteLine($"Barcode image saved to: {outputPath}");
// -----------------------------------------------------------------
- // Cloud storage upload (e.g., Azure Blob Storage, AWS S3) would be performed here.
- // The required SDKs are not included in this snippet; see documentation for integration.
+ // Cloud storage upload placeholder.
+ // The actual upload would require a cloud SDK (e.g., Google Cloud,
+ // AWS S3, Azure Blob). Since such packages are not available in the
+ // snippet runner, the implementation is shown as a comment.
+ //
+ // Example (Google Cloud Storage):
+ // using Google.Cloud.Storage.V1;
+ // var storage = StorageClient.Create();
+ // string bucketName = "my-bucket";
+ // string objectName = "SwissPostParcel.png";
+ // using var fileStream = File.OpenRead(outputPath);
+ // storage.UploadObject(bucketName, objectName, "image/png", fileStream);
// -----------------------------------------------------------------
- // var connectionString = "";
- // var containerName = "";
- // var blobName = "SwissPostParcel.png";
- // var blobClient = new BlobClient(connectionString, containerName, blobName);
- // using (var fileStream = File.OpenRead(outputPath))
- // {
- // blobClient.Upload(fileStream);
- // }
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/generate-swiss-post-parcel-international-barcodes-from-spreadsheet-and-include-checksum-verification-logs.cs b/postal-barcode-types/generate-swiss-post-parcel-international-barcodes-from-spreadsheet-and-include-checksum-verification-logs.cs
index e274362..ed09c75 100644
--- a/postal-barcode-types/generate-swiss-post-parcel-international-barcodes-from-spreadsheet-and-include-checksum-verification-logs.cs
+++ b/postal-barcode-types/generate-swiss-post-parcel-international-barcodes-from-spreadsheet-and-include-checksum-verification-logs.cs
@@ -1,104 +1,125 @@
-// Title: Swiss Post Parcel Barcode Generation and Checksum Validation
-// Description: Generates Swiss Post Parcel barcodes from sample data and demonstrates checksum validation during recognition.
-// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing how to use EncodeTypes.SwissPostParcel for barcode creation and DecodeType.SwissPostParcel for reading. It highlights typical use cases such as parcel tracking where checksum verification ensures data integrity. Developers often need to generate barcodes, save them as images, and validate them during scanning, making this a common pattern in logistics applications.
+// Title: Generate Swiss Post Parcel Barcodes from Excel and Log Checksums
+// Description: This example reads parcel codes from an Excel spreadsheet, creates Swiss Post Parcel barcodes as PNG images, and logs checksum verification results.
+// Category-Description: Demonstrates Aspose.BarCode barcode generation and recognition combined with Aspose.Cells for spreadsheet handling. Shows how to enable checksum generation, save barcodes, read them back for validation, and log results—common tasks for logistics and shipping software developers.
// Prompt: Generate Swiss Post Parcel international barcodes from a spreadsheet and include checksum verification logs.
-// Tags: barcode symbology, generation, recognition, checksum, png, aspose.barcode, encode types, decode types
+// Tags: swisspostparcel, barcode generation, barcode recognition, checksum, excel, png, aspose.cells, aspose.barcode
using System;
-using System.Collections.Generic;
using System.IO;
+using Aspose.Cells;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.BarCode; // for EncodeTypes
+using Aspose.Drawing;
///
-/// Demonstrates creating Swiss Post Parcel barcodes from a list of parcel codes,
-/// saving them as PNG images, and performing recognition with checksum validation
-/// both enabled and disabled.
+/// Reads parcel identifiers from an Excel file, generates Swiss Post Parcel barcodes,
+/// validates the checksums by re‑reading the images, and writes a verification log.
///
class Program
{
///
- /// Entry point of the example. Generates barcodes, saves them, and logs
- /// recognition results with checksum validation toggled.
+ /// Entry point of the example. Performs file preparation, barcode generation,
+ /// checksum verification, and logging.
///
static void Main()
{
- // Sample data representing rows from a spreadsheet (e.g., parcel IDs)
- var parcelCodes = new List
- {
- "1234567890123",
- "9876543210987",
- "5555555555555",
- "1111111111111",
- "2222222222222"
- };
-
- // Directory to store generated barcode images
+ // Define file and folder paths
+ string excelPath = "ParcelData.xlsx";
string outputDir = "Barcodes";
+ string logPath = "checksum_log.txt";
+
+ // Ensure the output directory exists
if (!Directory.Exists(outputDir))
{
Directory.CreateDirectory(outputDir);
}
- // Generate Swiss Post Parcel barcodes and save them as PNG files
- for (int i = 0; i < parcelCodes.Count; i++)
+ // Create a sample Excel file if it does not already exist
+ if (!File.Exists(excelPath))
{
- string code = parcelCodes[i];
- string filePath = Path.Combine(outputDir, $"SwissPost_{i + 1}.png");
+ CreateSampleExcel(excelPath);
+ }
- using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, code))
- {
- // Set image dimensions (optional)
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 150f;
+ // Load the workbook and get the first worksheet
+ Workbook workbook = new Workbook(excelPath);
+ Worksheet sheet = workbook.Worksheets[0];
+ Cells cells = sheet.Cells;
+
+ // Clear any previous log content
+ File.WriteAllText(logPath, string.Empty);
- // Save the barcode image
- generator.Save(filePath, BarCodeImageFormat.Png);
- Console.WriteLine($"Generated barcode for '{code}' -> {filePath}");
+ // Iterate through data rows (skip the header row)
+ int startRow = 1;
+ int totalRows = cells.MaxDataRow + 1; // inclusive upper bound
+ for (int row = startRow; row < totalRows; row++)
+ {
+ // Column A (index 0) holds the parcel code text
+ string codeText = cells[row, 0]?.StringValue?.Trim();
+ if (string.IsNullOrEmpty(codeText))
+ {
+ continue; // Skip rows without a code
}
- }
- Console.WriteLine();
- Console.WriteLine("=== Barcode Recognition with Checksum Validation (On) ===");
+ // Build the output image path for the current barcode
+ string imagePath = Path.Combine(outputDir, $"barcode_{row}.png");
- // Recognize each barcode with checksum validation enabled
- foreach (var file in Directory.GetFiles(outputDir, "*.png"))
- {
- using (var reader = new BarCodeReader(file, DecodeType.SwissPostParcel))
+ // Generate the barcode image with checksum enabled
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, codeText))
+ {
+ generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes;
+ generator.Parameters.Barcode.ChecksumAlwaysShow = true; // Show checksum in human‑readable text
+ generator.Save(imagePath, BarCodeImageFormat.Png);
+ }
+
+ // Verify the checksum by reading the generated barcode image
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.SwissPostParcel))
{
- // Enable checksum validation
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
+ reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; // Enable checksum validation
- foreach (var result in reader.ReadBarCodes())
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- Console.WriteLine($"File: {Path.GetFileName(file)}");
- Console.WriteLine($" Detected CodeText: {result.CodeText}");
- Console.WriteLine($" Confidence: {result.Confidence}");
- Console.WriteLine($" ReadingQuality: {result.ReadingQuality}");
+ string logEntry = $"Row {row}: CodeText=\"{result.CodeText}\"";
+
+ // Attempt to retrieve the checksum value if the symbology provides it
+ try
+ {
+ string checksum = result.Extended?.OneD?.CheckSum;
+ if (!string.IsNullOrEmpty(checksum))
+ {
+ logEntry += $", CheckSum=\"{checksum}\"";
+ }
+ }
+ catch
+ {
+ // Ignore exceptions when checksum information is unavailable
+ }
+
+ Console.WriteLine(logEntry);
+ File.AppendAllText(logPath, logEntry + Environment.NewLine);
}
}
}
- Console.WriteLine();
- Console.WriteLine("=== Barcode Recognition with Checksum Validation (Off) ===");
+ Console.WriteLine("Barcode generation and checksum verification completed.");
+ }
- // Recognize each barcode with checksum validation disabled
- foreach (var file in Directory.GetFiles(outputDir, "*.png"))
+ // Helper method to create a sample Excel file with dummy parcel data
+ private static void CreateSampleExcel(string path)
+ {
+ using (Workbook wb = new Workbook())
{
- using (var reader = new BarCodeReader(file, DecodeType.SwissPostParcel))
- {
- // Disable checksum validation
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Off;
+ Worksheet ws = wb.Worksheets[0];
+ Cells cells = ws.Cells;
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"File: {Path.GetFileName(file)}");
- Console.WriteLine($" Detected CodeText: {result.CodeText}");
- Console.WriteLine($" Confidence: {result.Confidence}");
- Console.WriteLine($" ReadingQuality: {result.ReadingQuality}");
- }
- }
+ // Header row
+ cells[0, 0].PutValue("SwissPostParcelCode");
+
+ // Sample parcel codes (must be valid for Swiss Post Parcel)
+ cells[1, 0].PutValue("123456789012");
+ cells[2, 0].PutValue("987654321098");
+ cells[3, 0].PutValue("555555555555");
+
+ wb.Save(path);
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/implement-asynchronous-barcode-decoding-for-large-image-collections-using-task-parallel-library.cs b/postal-barcode-types/implement-asynchronous-barcode-decoding-for-large-image-collections-using-task-parallel-library.cs
index 47a6540..0c9cb08 100644
--- a/postal-barcode-types/implement-asynchronous-barcode-decoding-for-large-image-collections-using-task-parallel-library.cs
+++ b/postal-barcode-types/implement-asynchronous-barcode-decoding-for-large-image-collections-using-task-parallel-library.cs
@@ -1,111 +1,115 @@
-// Title: Asynchronous barcode decoding with Task Parallel Library
-// Description: Demonstrates generating sample barcode images and decoding them concurrently using TPL for high‑throughput scenarios.
-// Category-Description: This example belongs to the Aspose.BarCode batch processing category, showcasing how to use BarcodeGenerator for image creation and BarCodeReader for recognition. It illustrates typical use cases such as large‑scale image collections, where developers need efficient, asynchronous decoding using core API classes like BarcodeGenerator, BarCodeReader, and QualitySettings.
+// Title: Asynchronous Barcode Decoding with TPL
+// Description: Demonstrates generating sample barcode images and decoding them asynchronously using the Task Parallel Library to improve throughput for large image collections.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing how to use BarCodeReader, BarcodeGenerator, and related classes for batch processing. Typical use cases include high‑volume scanning, automated inventory, and document processing where many images must be decoded efficiently. Developers often need to configure processor settings and run recognition in parallel to maximize performance.
// Prompt: Implement asynchronous barcode decoding for large image collections using Task Parallel Library.
-// Tags: code128, generation, recognition, png, tpl, aspose.barcode, aspose.drawing, barcode decoding, asynchronous processing
+// Tags: barcode, decoding, asynchronous, task parallel library, aspose.barcode, image processing, batch, recognition
using System;
-using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Sample program that generates a set of barcode images and decodes them asynchronously
-/// using the Task Parallel Library. Demonstrates high‑performance batch processing with
-/// Aspose.BarCode APIs.
+/// Provides methods to generate sample barcode images and decode them asynchronously.
///
class Program
{
- ///
- /// Entry point of the application. Generates sample barcodes, decodes them in parallel,
- /// and cleans up temporary resources.
- ///
- /// Command‑line arguments (not used).
- static async Task Main(string[] args)
+ // Generates a set of sample barcode images in the specified folder.
+ private static void GenerateSampleBarcodes(string folderPath)
{
- // --------------------------------------------------------------------
- // Prepare a temporary folder for sample barcode images
- // --------------------------------------------------------------------
- string tempFolder = Path.Combine(Path.GetTempPath(), "AsposeBarcodeSamples");
- if (!Directory.Exists(tempFolder))
+ // Ensure the output folder exists.
+ Directory.CreateDirectory(folderPath);
+
+ // Sample data: each tuple contains the symbology and the text to encode.
+ var samples = new (BaseEncodeType encodeType, string text)[]
{
- Directory.CreateDirectory(tempFolder);
- }
+ (EncodeTypes.Code128, "Sample123"),
+ (EncodeTypes.QR, "https://example.com"),
+ (EncodeTypes.DataMatrix, "DM12345"),
+ (EncodeTypes.Pdf417, "PDF417 Sample Text"),
+ (EncodeTypes.Aztec, "AztecCode")
+ };
- // --------------------------------------------------------------------
- // Generate a small set of sample barcode images (5 items)
- // --------------------------------------------------------------------
- int sampleCount = 5;
- List imagePaths = new List();
- for (int i = 0; i < sampleCount; i++)
+ int index = 0;
+ foreach (var (encodeType, text) in samples)
{
- string filePath = Path.Combine(tempFolder, $"barcode_{i}.png");
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i}"))
+ string filePath = Path.Combine(folderPath, $"barcode_{index}.png");
+ using (var generator = new BarcodeGenerator(encodeType, text))
{
- // Auto‑size the barcode image for optimal dimensions
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Save as PNG.
generator.Save(filePath, BarCodeImageFormat.Png);
}
- imagePaths.Add(filePath);
+ index++;
}
+ }
- // --------------------------------------------------------------------
- // Asynchronously decode all images using TPL
- // --------------------------------------------------------------------
- List decodeTasks = new List();
- foreach (string path in imagePaths)
- {
- // Queue each decode operation on the thread pool
- decodeTasks.Add(Task.Run(() => DecodeBarcode(path)));
- }
-
- // Wait for all decoding tasks to complete
- await Task.WhenAll(decodeTasks);
-
- // --------------------------------------------------------------------
- // Clean up temporary files (optional)
- // --------------------------------------------------------------------
- foreach (string path in imagePaths)
+ // Asynchronously decodes a single barcode image and returns the first detected code text.
+ private static Task DecodeBarcodeAsync(string imagePath)
+ {
+ return Task.Run(() =>
{
- try { File.Delete(path); } catch { /* ignore cleanup errors */ }
- }
- try { Directory.Delete(tempFolder); } catch { /* ignore cleanup errors */ }
+ using (var reader = new BarCodeReader())
+ {
+ // Use all supported symbologies.
+ reader.BarCodeReadType = DecodeType.AllSupportedTypes;
+ // Assign the image file.
+ reader.SetBarCodeImage(imagePath);
+ // Perform recognition.
+ var results = reader.ReadBarCodes();
+ if (results != null && results.Length > 0 && !string.IsNullOrEmpty(results[0].CodeText))
+ {
+ return results[0].CodeText;
+ }
+ return null;
+ }
+ });
}
///
- /// Decodes a single barcode image and writes the results to the console.
+ /// Entry point of the program. Generates sample barcodes (if needed), then decodes all PNG images in the folder asynchronously.
///
- /// Full path to the barcode image file.
- private static void DecodeBarcode(string imagePath)
+ static async Task Main(string[] args)
{
- if (!File.Exists(imagePath))
+ // Folder to hold sample barcode images.
+ string barcodeFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+
+ // Generate sample images if the folder is empty.
+ if (!Directory.Exists(barcodeFolder) || Directory.GetFiles(barcodeFolder, "*.png").Length == 0)
{
- Console.WriteLine($"File not found: {imagePath}");
+ GenerateSampleBarcodes(barcodeFolder);
+ Console.WriteLine($"Generated sample barcodes in '{barcodeFolder}'.");
+ }
+
+ // Get all PNG files in the folder.
+ string[] imageFiles = Directory.GetFiles(barcodeFolder, "*.png");
+ if (imageFiles.Length == 0)
+ {
+ Console.WriteLine("No barcode images found to decode.");
return;
}
- // Use BarCodeReader to read all supported barcode types
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ // Configure the reader to use all available processor cores.
+ BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Environment.ProcessorCount;
+
+ // Create a decoding task for each image.
+ var decodeTasks = new Task[imageFiles.Length];
+ for (int i = 0; i < imageFiles.Length; i++)
{
- // Apply a high‑performance quality preset for faster processing
- reader.QualitySettings = QualitySettings.HighPerformance;
+ decodeTasks[i] = DecodeBarcodeAsync(imageFiles[i]);
+ }
- BarCodeResult[] results = reader.ReadBarCodes();
- if (results.Length == 0)
- {
- Console.WriteLine($"No barcode detected in {Path.GetFileName(imagePath)}");
- return;
- }
+ // Await all decoding operations.
+ string[] decodedTexts = await Task.WhenAll(decodeTasks);
- // Output each detected barcode's type and text
- foreach (var result in results)
- {
- Console.WriteLine($"File: {Path.GetFileName(imagePath)} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
- }
+ // Output the results.
+ Console.WriteLine("Decoding results:");
+ for (int i = 0; i < imageFiles.Length; i++)
+ {
+ string fileName = Path.GetFileName(imageFiles[i]);
+ string codeText = decodedTexts[i] ?? "(no code detected)";
+ Console.WriteLine($"{fileName}: {codeText}");
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/implement-asynchronous-barcode-generation-for-high-throughput-web-requests-using-async-await-pattern-efficiently.cs b/postal-barcode-types/implement-asynchronous-barcode-generation-for-high-throughput-web-requests-using-async-await-pattern-efficiently.cs
index f55455c..8454c0e 100644
--- a/postal-barcode-types/implement-asynchronous-barcode-generation-for-high-throughput-web-requests-using-async-await-pattern-efficiently.cs
+++ b/postal-barcode-types/implement-asynchronous-barcode-generation-for-high-throughput-web-requests-using-async-await-pattern-efficiently.cs
@@ -1,97 +1,131 @@
-// Title: Asynchronous barcode generation example
-// Description: Demonstrates generating multiple barcodes concurrently using async/await, suitable for high‑throughput web scenarios.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the BarcodeGenerator class with Code128 symbology, image sizing, and styling. Developers often need to create barcodes on demand in web services, batch processes, or APIs, requiring efficient asynchronous I/O and parallel execution. The snippet illustrates typical usage patterns for high‑volume barcode creation.
+// Title: Asynchronous Barcode Generation with Controlled Parallelism
+// Description: Demonstrates generating multiple barcodes concurrently using async/await and a semaphore to limit parallelism, saving each as a PNG file.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class together with EncodeTypes to create various symbologies. Typical use cases include high‑throughput web services that need to produce barcode images on demand. Developers often need to manage resources efficiently, handle unknown symbologies, and control concurrency when processing large batches.
// Prompt: Implement asynchronous barcode generation for high‑throughput web requests using async/await pattern efficiently.
-// Tags: barcode, code128, async, await, generation, png, aspose.barcode, high-throughput
+// Tags: barcode, symbology, async, parallelism, generation, aspose.barcode, png
using System;
using System.Collections.Generic;
using System.IO;
+using System.Reflection;
+using System.Threading;
using System.Threading.Tasks;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates asynchronous generation of Code128 barcodes using Aspose.BarCode.
+/// Provides methods to resolve barcode symbologies, generate barcode images asynchronously,
+/// and process batches of barcode requests with controlled parallelism.
///
class Program
{
///
- /// Entry point that initiates asynchronous barcode generation.
+ /// Resolves a symbology name (e.g., "Code128") to the corresponding using reflection.
+ /// Returns null if the symbology is not found.
///
- /// Command‑line arguments (not used).
- static async Task Main(string[] args)
+ /// The name of the barcode symbology.
+ /// The matching , or null if unknown.
+ private static BaseEncodeType ResolveEncodeType(string symbologyName)
{
- // Generate a small batch of barcodes asynchronously.
- await GenerateBarcodesAsync();
+ // Look up the static field in EncodeTypes that matches the provided name.
+ FieldInfo field = typeof(EncodeTypes).GetField(symbologyName, BindingFlags.Public | BindingFlags.Static);
+ if (field == null)
+ {
+ Console.WriteLine($"Unknown symbology: {symbologyName}. Skipping.");
+ return null;
+ }
+ return (BaseEncodeType)field.GetValue(null);
}
- // Asynchronously generates barcodes for a set of sample texts.
- private static async Task GenerateBarcodesAsync()
+ ///
+ /// Asynchronously generates a single barcode image and saves it to the specified path.
+ ///
+ /// The barcode symbology to use.
+ /// The text or data to encode.
+ /// The full file path where the PNG image will be saved.
+ /// A representing the asynchronous operation.
+ private static Task GenerateBarcodeAsync(BaseEncodeType encodeType, string codeText, string outputPath)
{
- // Sample data – in a real high‑throughput scenario this could come from a request queue.
- var samples = new List
+ return Task.Run(() =>
{
- "ABC123",
- "DEF456",
- "GHI789",
- "JKL012",
- "MNO345"
- };
+ // Ensure the target directory exists before saving.
+ string directory = Path.GetDirectoryName(outputPath);
+ if (!Directory.Exists(directory))
+ {
+ Directory.CreateDirectory(directory);
+ }
- var tasks = new List();
+ // Create and configure the barcode generator.
+ using (var generator = new BarcodeGenerator(encodeType, codeText))
+ {
+ // Example of setting a barcode parameter (optional).
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+
+ // Save the generated barcode as a PNG file.
+ generator.Save(outputPath, BarCodeImageFormat.Png);
+ }
+ });
+ }
- // Create a task for each sample text.
- foreach (var text in samples)
+ ///
+ /// Processes a batch of barcode generation requests concurrently, limiting the number of simultaneous operations.
+ ///
+ ///
+ /// A collection of tuples containing the symbology name, code text, and desired output file name.
+ ///
+ /// Maximum number of concurrent barcode generation tasks.
+ /// A that completes when all requests have been processed.
+ private static async Task ProcessBatchAsync(IEnumerable<(string Symbology, string CodeText, string FileName)> requests, int maxDegreeOfParallelism)
+ {
+ // Semaphore limits the number of parallel tasks.
+ using (var semaphore = new SemaphoreSlim(maxDegreeOfParallelism))
{
- tasks.Add(Task.Run(async () =>
+ var tasks = new List();
+
+ foreach (var request in requests)
{
- // Create and configure the generator for Code128.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, text))
+ // Resolve the symbology to an EncodeType; skip if unknown.
+ BaseEncodeType encodeType = ResolveEncodeType(request.Symbology);
+ if (encodeType == null)
{
- // Use interpolation mode for automatic sizing.
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 150f;
+ continue;
+ }
- // Optional styling: set barcode and background colors.
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.DarkBlue;
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+ // Wait for an available slot before starting a new task.
+ await semaphore.WaitAsync();
- // Generate the bitmap image.
- using (var bitmap = generator.GenerateBarCodeImage())
- {
- var fileName = $"barcode_{text}.png";
- // Save the bitmap asynchronously.
- await SaveBitmapAsync(bitmap, fileName);
- Console.WriteLine($"Saved {fileName}");
- }
- }
- }));
- }
+ // Start the generation task and ensure the semaphore is released afterwards.
+ Task task = GenerateBarcodeAsync(encodeType, request.CodeText, Path.Combine("Barcodes", request.FileName))
+ .ContinueWith(t => semaphore.Release());
+
+ tasks.Add(task);
+ }
- // Await all generation tasks to ensure completion.
- await Task.WhenAll(tasks);
+ // Await completion of all generation tasks.
+ await Task.WhenAll(tasks);
+ }
}
- // Saves a bitmap to a file using asynchronous file I/O.
- private static async Task SaveBitmapAsync(Bitmap bitmap, string path)
+ ///
+ /// Application entry point. Creates sample barcode requests and processes them asynchronously.
+ ///
+ /// Command‑line arguments (not used).
+ /// A representing the asynchronous execution.
+ static async Task Main(string[] args)
{
- // Ensure the target directory exists.
- var directory = Path.GetDirectoryName(path);
- if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
+ // Sample barcode requests (symbology, code text, output file name).
+ var requests = new List<(string Symbology, string CodeText, string FileName)>
{
- Directory.CreateDirectory(directory);
- }
+ ("Code128", "123ABC", "code128_1.png"),
+ ("QR", "https://example.com", "qr_1.png"),
+ ("Code39", "CODE39", "code39_1.png"),
+ ("DataMatrix", "DM12345", "datamatrix_1.png"),
+ ("Aztec", "AztecDemo", "aztec_1.png")
+ };
- // Write the image to a file stream asynchronously.
- using (var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 4096, useAsync: true))
- {
- // Bitmap.Save writes synchronously to the provided stream.
- bitmap.Save(stream, ImageFormat.Png);
- await stream.FlushAsync();
- }
+ // Process the batch with a maximum of 3 concurrent operations.
+ await ProcessBatchAsync(requests, maxDegreeOfParallelism: 3);
+
+ Console.WriteLine("Barcode generation completed.");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/implement-error-handling-for-invalid-xdimension-values-when-creating-postal-barcode.cs b/postal-barcode-types/implement-error-handling-for-invalid-xdimension-values-when-creating-postal-barcode.cs
index 5e1cb69..7779d9d 100644
--- a/postal-barcode-types/implement-error-handling-for-invalid-xdimension-values-when-creating-postal-barcode.cs
+++ b/postal-barcode-types/implement-error-handling-for-invalid-xdimension-values-when-creating-postal-barcode.cs
@@ -1,80 +1,89 @@
-// Title: Postal barcode generation with XDimension validation
-// Description: Demonstrates creating a Postnet barcode while validating the XDimension parameter to ensure it is positive.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on postal symbologies. It showcases the use of BarcodeGenerator, EncodeTypes, and barcode parameter settings such as XDimension, BarColor, and BackColor. Developers often need to generate valid postal barcodes for mailing applications and must validate dimensions to meet specification requirements.
-// Prompt: Implement error handling for invalid XDimension values when creating a postal barcode.
-// Tags: barcode, postal, xdimension, validation, generation, aspose.barcode, png
+// Title: Postal Barcode Generation with XDimension Validation
+// Description: Demonstrates creating a Postnet postal barcode using Aspose.BarCode while validating the XDimension parameter to ensure it is positive.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on postal symbologies such as Postnet. It shows how to configure barcode parameters (e.g., XDimension), handle invalid input, and save the image using BarcodeGenerator and related classes. Developers working with postal barcode creation, parameter validation, and image output can use this pattern as a reference.
+/// Prompt: Implement error handling for invalid XDimension values when creating a postal barcode.
+/// Tags: barcode, postal, postnet, xdimension, validation, aspnet, aspnetcore, aspose.barcode, image, png, error-handling
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
///
-/// Example program that generates Postnet barcodes with validation for the XDimension parameter.
+/// Example program that generates Postnet postal barcodes and demonstrates validation of the XDimension parameter.
///
class Program
{
///
- /// Entry point of the application. Iterates over sample XDimension values,
- /// attempts to generate a barcode for each, and reports success or errors.
+ /// Entry point of the application. Generates a valid barcode and attempts to generate an invalid one to showcase error handling.
///
static void Main()
{
- // Sample XDimension values to demonstrate validation (valid, negative, zero)
- float[] xDimensions = { 2f, -1f, 0f };
-
- foreach (float xDim in xDimensions)
+ // ------------------------------------------------------------
+ // Generate a valid postal barcode
+ // ------------------------------------------------------------
+ try
{
- try
- {
- // Build a unique file name based on the current XDimension value
- string fileName = $"postal_{xDim}.png";
-
- // Attempt to create and save the barcode
- CreatePostalBarcode(xDim, fileName);
+ // Create a barcode with a positive XDimension value
+ CreatePostalBarcode("12345", 2f, "postal_valid.png");
+ Console.WriteLine("Valid barcode generated successfully.");
+ }
+ catch (Exception ex)
+ {
+ // Unexpected errors during valid barcode generation
+ Console.WriteLine($"Error generating valid barcode: {ex.Message}");
+ }
- // Inform the user of successful generation
- Console.WriteLine($"Barcode generated and saved to '{fileName}' with XDimension = {xDim}");
- }
- catch (ArgumentOutOfRangeException ex)
- {
- // Handle validation errors for XDimension
- Console.WriteLine($"Invalid XDimension ({xDim}): {ex.Message}");
- }
- catch (Aspose.BarCode.BarCodeException ex)
- {
- // Handle errors thrown by the Aspose.BarCode library
- Console.WriteLine($"Barcode generation error for XDimension ({xDim}): {ex.Message}");
- }
+ // ------------------------------------------------------------
+ // Attempt to generate a barcode with an invalid XDimension
+ // ------------------------------------------------------------
+ try
+ {
+ // XDimension is negative, which should trigger validation logic
+ CreatePostalBarcode("12345", -1f, "postal_invalid.png");
+ }
+ catch (ArgumentOutOfRangeException ex)
+ {
+ // Expected validation exception for non‑positive XDimension
+ Console.WriteLine($"Caught expected argument error: {ex.Message}");
+ }
+ catch (Exception ex)
+ {
+ // Any other unexpected exceptions
+ Console.WriteLine($"Unexpected error: {ex.Message}");
}
}
///
- /// Creates a Postnet barcode using the specified XDimension and saves it to the given path.
+ /// Creates a Postnet postal barcode with the specified XDimension.
+ /// Throws if is not positive.
///
- /// The XDimension (module width) in points; must be greater than zero.
- /// The file path where the generated barcode image will be saved.
- static void CreatePostalBarcode(float xDimension, string outputPath)
+ /// The postal code to encode.
+ /// Module size in points (must be > 0).
+ /// File path to save the generated barcode image.
+ static void CreatePostalBarcode(string codeText, float xDimension, string outputPath)
{
- // Validate XDimension before applying it to the generator
+ // Validate that the XDimension is a positive value
if (xDimension <= 0f)
{
throw new ArgumentOutOfRangeException(nameof(xDimension), "XDimension must be greater than zero.");
}
- // Initialize the barcode generator for the Postnet symbology with sample data
- using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, "12345678"))
+ // Ensure the output directory exists before saving the image
+ string directory = Path.GetDirectoryName(outputPath);
+ if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
- // Apply the validated XDimension to control module size
- generator.Parameters.Barcode.XDimension.Point = xDimension;
+ Directory.CreateDirectory(directory);
+ }
- // Optional visual settings: black bars on a white background
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+ // Initialize the barcode generator for the Postnet symbology
+ using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, codeText))
+ {
+ // Apply the validated XDimension (module size) to the barcode parameters
+ generator.Parameters.Barcode.XDimension.Point = xDimension;
- // Save the generated barcode image to the specified file
- generator.Save(outputPath);
+ // Save the generated barcode as a PNG image
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/implement-fallback-logic-to-use-automatic-bar-height-when-barheight-property-is-set-to-zero.cs b/postal-barcode-types/implement-fallback-logic-to-use-automatic-bar-height-when-barheight-property-is-set-to-zero.cs
index 0dada88..1dead59 100644
--- a/postal-barcode-types/implement-fallback-logic-to-use-automatic-bar-height-when-barheight-property-is-set-to-zero.cs
+++ b/postal-barcode-types/implement-fallback-logic-to-use-automatic-bar-height-when-barheight-property-is-set-to-zero.cs
@@ -1,54 +1,83 @@
-// Title: Automatic Bar Height Fallback for Barcode Generation
-// Description: Demonstrates how to let Aspose.BarCode automatically determine bar height when BarHeight is set to zero, using AutoSizeMode.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of BarcodeGenerator, EncodeTypes, and AutoSizeMode to create barcodes with dynamic sizing. Developers often need to generate barcodes that fit specific image dimensions without manually calculating bar heights; this pattern provides a reliable fallback to automatic sizing.
+// Title: Barcode generation with fallback automatic bar height
+// Description: Shows how to configure a barcode generator to use a specified bar height or automatically determine it when the height is zero or negative.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, its Parameters, and AutoSizeMode for dynamic sizing. Developers often need to adjust bar height for different output media while ensuring automatic sizing works as a fallback, a common requirement in barcode rendering pipelines.
// Prompt: Implement fallback logic to use automatic bar height when BarHeight property is set to zero.
-// Tags: barcode, autosize, barheight, code128, image, aspose.barcode, generation
+// Tags: barcode, barheight, autosizemode, fallback, generation, png, aspose.barcode, code128
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Generates a Code128 barcode and applies automatic bar height sizing when the desired height is zero.
+/// Demonstrates how to apply fallback logic for bar height when generating barcodes with Aspose.BarCode.
+/// If a positive height is provided, it is used; otherwise the generator switches to automatic sizing.
///
class Program
{
///
- /// Entry point of the example. Creates a barcode image with optional automatic height adjustment.
+ /// Configures the barcode generator's bar height.
+ /// If the supplied height is greater than zero, it is applied.
+ /// Otherwise automatic sizing is enabled by setting AutoSizeMode to Interpolation.
+ ///
+ /// The BarcodeGenerator instance to configure.
+ /// Desired bar height in points; zero or negative triggers automatic sizing.
+ static void ConfigureBarHeight(BarcodeGenerator generator, float barHeight)
+ {
+ if (barHeight > 0f)
+ {
+ // Apply explicit bar height (in points).
+ generator.Parameters.Barcode.BarHeight.Point = barHeight;
+ Console.WriteLine($"BarHeight set to {barHeight} pt.");
+ }
+ else
+ {
+ // Enable automatic sizing; do not set BarHeight (zero would throw).
+ generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ Console.WriteLine("BarHeight is zero or negative; using automatic bar height (AutoSizeMode.Interpolation).");
+ }
+ }
+
+ ///
+ /// Entry point of the example. Generates barcode images using a set of test bar heights,
+ /// demonstrating the fallback to automatic sizing when the height is not positive.
///
static void Main()
{
- // Sample barcode text to encode.
- const string codeText = "123456";
+ // Output file path for the generated PNG barcode.
+ const string outputPath = "barcode.png";
- // Desired bar height (set to 0 to trigger automatic sizing).
- float desiredBarHeight = 0f;
+ // Example bar height values to test the fallback logic.
+ float[] testBarHeights = { 30f, 0f, -5f };
- // Initialize the barcode generator for Code128 symbology.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ foreach (float height in testBarHeights)
{
- // Determine whether to use automatic sizing based on the desired bar height.
- if (desiredBarHeight <= 0f)
- {
- // Enable automatic resizing using interpolation.
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Ensure any previous file is removed before saving a new one.
+ if (File.Exists(outputPath))
+ File.Delete(outputPath);
- // Set target image dimensions (example values).
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 100f;
- }
- else
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
{
- // Apply the explicitly specified bar height.
- generator.Parameters.Barcode.BarHeight.Point = desiredBarHeight;
+ generator.CodeText = "Sample123";
+
+ // Apply the fallback logic for the current test height.
+ ConfigureBarHeight(generator, height);
+
+ // Generate the barcode image.
+ using (Bitmap bitmap = generator.GenerateBarCodeImage())
+ {
+ // Save as PNG using Aspose.Drawing.Imaging.ImageFormat.
+ bitmap.Save(outputPath, ImageFormat.Png);
+ }
}
- // Save the generated barcode image to a file.
- generator.Save("barcode.png");
+ Console.WriteLine($"Barcode saved to '{outputPath}' with BarHeight input {height}.");
+ Console.WriteLine();
}
- // Inform the user that the barcode has been generated.
- Console.WriteLine("Barcode generated: barcode.png");
+ // Indicate completion.
+ Console.WriteLine("All barcode images generated.");
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/implement-function-that-converts-generated-barcode-image-to-base64-string-for-embedding-in-html.cs b/postal-barcode-types/implement-function-that-converts-generated-barcode-image-to-base64-string-for-embedding-in-html.cs
index 4e552a7..1ee6c85 100644
--- a/postal-barcode-types/implement-function-that-converts-generated-barcode-image-to-base64-string-for-embedding-in-html.cs
+++ b/postal-barcode-types/implement-function-that-converts-generated-barcode-image-to-base64-string-for-embedding-in-html.cs
@@ -1,60 +1,51 @@
-// Title: Barcode to Base64 conversion example
-// Description: Demonstrates generating a Code128 barcode image and converting it to a Base64 string for embedding in HTML.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator, set parameters, generate a bitmap, and obtain a Base64-encoded PNG. Developers often need to embed barcodes directly into web pages or emails without saving files, making this pattern common for HTML image sources.
+// Title: Generate a barcode image and convert it to a Base64 string for HTML embedding
+// Description: Demonstrates creating a Code128 barcode with Aspose.BarCode, saving it to a memory stream, and converting the image to a Base64 string that can be embedded directly in an HTML img tag.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class to produce barcode images in various formats. Typical use cases include generating barcodes for web pages, emails, or reports where embedding the image as a Base64 string avoids separate file handling. Developers often need to convert generated images to Base64 for seamless HTML integration, and this snippet shows the standard workflow using MemoryStream and Convert.ToBase64String.
// Prompt: Implement a function that converts a generated barcode image to a Base64 string for embedding in HTML.
-// Tags: barcode symbology, generation, base64, html embedding, aspose.barcode, aspose.drawing
+// Tags: barcode, code128, base64, html, image, aspose.barcode, generation, png
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
namespace BarcodeBase64Example
{
///
- /// Provides an example of generating a barcode and converting it to a Base64 string for HTML embedding.
+ /// Demonstrates barcode generation and conversion to a Base64 string for HTML embedding.
///
class Program
{
///
- /// Entry point of the example. Generates a Code128 barcode and writes its Base64 representation to the console.
+ /// Entry point that creates a Code128 barcode, converts it to Base64, and outputs an HTML img tag.
///
- static void Main()
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
- // Define the text to encode in the barcode.
+ // Define the barcode text and symbology
string codeText = "1234567890";
+ BaseEncodeType encodeType = EncodeTypes.Code128;
- // Initialize a BarcodeGenerator for Code128 symbology with the specified text.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ // Initialize the barcode generator with the chosen type and text
+ using (BarcodeGenerator generator = new BarcodeGenerator(encodeType, codeText))
{
- // Optional: adjust the module (X) dimension to control barcode size.
- generator.Parameters.Barcode.XDimension.Point = 2f;
+ // Prepare a memory stream to hold the generated PNG image
+ using (MemoryStream ms = new MemoryStream())
+ {
+ // Save the barcode image into the memory stream in PNG format
+ generator.Save(ms, BarCodeImageFormat.Png);
- // Convert the generated barcode image to a Base64 string.
- string base64 = ConvertBarcodeToBase64(generator);
+ // Retrieve the raw image bytes from the stream
+ byte[] imageBytes = ms.ToArray();
- // Output the Base64 string prefixed with the data URI scheme for direct HTML embedding.
- Console.WriteLine("data:image/png;base64," + base64);
- }
- }
+ // Convert the image bytes to a Base64-encoded string
+ string base64 = Convert.ToBase64String(imageBytes);
- ///
- /// Generates the barcode image from the provided generator and returns its Base64 representation.
- ///
- /// Configured instance.
- /// Base64-encoded PNG image.
- static string ConvertBarcodeToBase64(BarcodeGenerator generator)
- {
- // Generate the barcode as a bitmap.
- using (Bitmap bitmap = generator.GenerateBarCodeImage())
- {
- // Save the bitmap into a memory stream using PNG format.
- using (var memoryStream = new MemoryStream())
- {
- bitmap.Save(memoryStream, ImageFormat.Png);
- // Convert the stream's byte array to a Base64 string.
- return Convert.ToBase64String(memoryStream.ToArray());
+ // Build an HTML tag that embeds the Base64 string
+ string htmlImg = $"";
+
+ // Output the HTML markup to the console
+ Console.WriteLine(htmlImg);
}
}
}
diff --git a/postal-barcode-types/implement-logging-of-barcode-decoding-attempts-successes-and-failures-with-timestamps-and-source-file-paths.cs b/postal-barcode-types/implement-logging-of-barcode-decoding-attempts-successes-and-failures-with-timestamps-and-source-file-paths.cs
index a263624..3c14eea 100644
--- a/postal-barcode-types/implement-logging-of-barcode-decoding-attempts-successes-and-failures-with-timestamps-and-source-file-paths.cs
+++ b/postal-barcode-types/implement-logging-of-barcode-decoding-attempts-successes-and-failures-with-timestamps-and-source-file-paths.cs
@@ -1,97 +1,136 @@
-// Title: Barcode Generation and Decoding with Logging
-// Description: Generates a Code128 barcode image, then attempts to decode it while logging each attempt, success, and failure with timestamps and file paths.
-// Category-Description: This example belongs to the Aspose.BarCode operations collection that demonstrates barcode generation and recognition. It showcases the use of BarcodeGenerator for creating barcodes and BarCodeReader for decoding them. Typical scenarios include inventory labeling, document processing, and automated scanning systems where developers need to generate barcodes programmatically and verify them by reading image files.
+// Title: Barcode generation, decoding, and logging example
+// Description: Demonstrates creating sample barcodes (Code128, QR, DataMatrix), decoding them, and logging each attempt with timestamps and file paths.
+// Category-Description: This example belongs to the Aspose.BarCode operations category covering barcode generation and recognition. It showcases the use of BarcodeGenerator, BarCodeReader, EncodeTypes, and DecodeType classes to create and read various symbologies, while logging outcomes for audit or debugging purposes. Developers often need such patterns for batch processing, validation, and traceability of barcode workflows.
// Prompt: Implement logging of barcode decoding attempts, successes, and failures with timestamps and source file paths.
-// Tags: barcode, code128, generation, decoding, logging, aspose.barcode, image, console
+// Tags: barcode, generation, recognition, logging, codetype, decode, encode, aspose.barcode, png
using System;
using System.IO;
-using System.Collections.Generic;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
/// Demonstrates barcode generation, decoding, and logging using Aspose.BarCode.
///
class Program
{
+ // Path to the folder that will hold sample barcode images
+ private const string BarcodeFolder = "Barcodes";
+
+ // Path to the log file
+ private const string LogFile = "barcode_log.txt";
+
///
- /// Entry point that creates a sample barcode, attempts decoding on a list of files, and logs outcomes.
+ /// Entry point. Generates sample barcodes, decodes them, and logs results.
///
static void Main()
{
- // --------------------------------------------------------------------
- // Prepare a directory and generate a sample barcode image (Code128)
- // --------------------------------------------------------------------
- string sampleDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
- Directory.CreateDirectory(sampleDir);
- string samplePath = Path.Combine(sampleDir, "sample.png");
-
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ // Ensure a clean log file at the start of each run
+ if (File.Exists(LogFile))
{
- // Save the generated barcode as a PNG file
- generator.Save(samplePath, BarCodeImageFormat.Png);
+ File.Delete(LogFile);
}
- // ---------------------------------------------------------------
- // Define the list of files to decode (includes a non‑existent file)
- // ---------------------------------------------------------------
- var filesToDecode = new List
+ // Create the folder for sample images if it does not exist
+ if (!Directory.Exists(BarcodeFolder))
{
- samplePath,
- Path.Combine(sampleDir, "missing.png")
- };
-
- // ---------------------------------------------------------------
- // Iterate over each file, attempt decoding, and log the result
- // ---------------------------------------------------------------
- foreach (var filePath in filesToDecode)
+ Directory.CreateDirectory(BarcodeFolder);
+ }
+
+ // Generate a few sample barcodes (Code128, QR, DataMatrix)
+ GenerateSampleBarcodes();
+
+ // Process each PNG image in the folder
+ string[] files = Directory.GetFiles(BarcodeFolder, "*.png");
+ foreach (string filePath in files)
{
- Log($"Attempting to decode barcode in file: {filePath}");
+ // Log the start of a decoding attempt
+ LogAttempt(filePath);
- // Verify that the file exists before trying to read it
+ // Verify the file still exists before attempting to read
if (!File.Exists(filePath))
{
- Log("File does not exist. Decoding failed.");
+ LogMessage($"File not found: {filePath}");
continue;
}
- try
+ // Use AllSupportedTypes to detect any barcode present in the image
+ using (BarCodeReader reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
{
- // Initialize the barcode reader for all supported symbologies
- using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
+ try
{
- // Read all barcodes found in the image
- var results = reader.ReadBarCodes();
+ BarCodeResult[] results = reader.ReadBarCodes();
+ // No barcodes detected
if (results.Length == 0)
{
- Log("No barcode detected. Decoding failed.");
+ LogMessage("Result: Failure – No barcode detected.");
}
else
{
- // Log details for each detected barcode
- foreach (var result in results)
+ // Iterate through all detected barcodes
+ foreach (BarCodeResult result in results)
{
- Log($"Success: Type={result.CodeTypeName}, Text={result.CodeText}, Confidence={result.Confidence}, ReadingQuality={result.ReadingQuality}");
+ if (!string.IsNullOrEmpty(result.CodeText))
+ {
+ LogMessage($"Result: Success – Type: {result.CodeTypeName}, Text: {result.CodeText}");
+ }
+ else
+ {
+ LogMessage($"Result: Failure – Detected type {result.CodeTypeName} but no code text.");
+ }
}
}
}
- }
- catch (Exception ex)
- {
- // Log any unexpected exceptions during decoding
- Log($"Exception during decoding: {ex.Message}");
+ catch (Exception ex)
+ {
+ // Log any exception that occurs during decoding
+ LogMessage($"Result: Failure – Exception: {ex.Message}");
+ }
}
}
+
+ // Indicate completion to the user
+ Console.WriteLine("Barcode processing completed. See log file for details.");
}
- ///
- /// Writes a timestamped log message to the console.
- ///
- /// The message to log.
- static void Log(string message)
+ // Generates sample barcode images (Code128, QR, DataMatrix) in the BarcodeFolder
+ private static void GenerateSampleBarcodes()
+ {
+ // Code128 example
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "ABC123"))
+ {
+ string path = Path.Combine(BarcodeFolder, "code128.png");
+ generator.Save(path, BarCodeImageFormat.Png);
+ }
+
+ // QR code example
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"))
+ {
+ string path = Path.Combine(BarcodeFolder, "qr.png");
+ generator.Save(path, BarCodeImageFormat.Png);
+ }
+
+ // DataMatrix example
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "DataMatrix123"))
+ {
+ string path = Path.Combine(BarcodeFolder, "datamatrix.png");
+ generator.Save(path, BarCodeImageFormat.Png);
+ }
+ }
+
+ // Logs the start of a decoding attempt with timestamp and file path
+ private static void LogAttempt(string filePath)
+ {
+ string entry = $"{DateTime.Now:O} | Attempt: {filePath}{Environment.NewLine}";
+ File.AppendAllText(LogFile, entry);
+ }
+
+ // Appends a generic message to the log with timestamp
+ private static void LogMessage(string message)
{
- Console.WriteLine($"{DateTime.Now:O} - {message}");
+ string entry = $"{DateTime.Now:O} | {message}{Environment.NewLine}";
+ File.AppendAllText(LogFile, entry);
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/implement-logging-of-barcode-generation-parameters-and-outcomes-to-structured-json-log-file.cs b/postal-barcode-types/implement-logging-of-barcode-generation-parameters-and-outcomes-to-structured-json-log-file.cs
index 09fd090..b265e93 100644
--- a/postal-barcode-types/implement-logging-of-barcode-generation-parameters-and-outcomes-to-structured-json-log-file.cs
+++ b/postal-barcode-types/implement-logging-of-barcode-generation-parameters-and-outcomes-to-structured-json-log-file.cs
@@ -1,112 +1,111 @@
-// Title: Barcode Generation with JSON Logging Example
-// Description: This example generates several barcodes using Aspose.BarCode and records the generation parameters and outcomes in a structured JSON log file.
-// Category-Description: The sample belongs to the Aspose.BarCode barcode creation and logging category, illustrating how to use EncodeTypes, BarcodeGenerator, and related parameter settings. Developers often need to automate barcode production while capturing metadata for auditing, debugging, or downstream processing; this example shows a typical pattern for such tasks.
+// Title: Barcode generation with JSON logging of parameters and outcomes
+// Description: Demonstrates creating barcodes using Aspose.BarCode and logging each generation's parameters, results, and any errors to a structured JSON file.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to produce barcode images. Typical use cases include batch barcode creation for inventory, shipping, or marketing, where developers need to record generation details for auditing or troubleshooting. The pattern of logging to JSON helps integrate barcode workflows into automated pipelines and monitoring systems.
// Prompt: Implement logging of barcode generation parameters and outcomes to a structured JSON log file.
-// Tags: barcode, symbology, generation, json, logging, aspose.barcode, encodetypes
+// Tags: barcode generation, json logging, aspose.barcode, encode types, png output
using System;
-using System.Collections.Generic;
using System.IO;
-using System.Reflection;
using System.Text.Json;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
-namespace BarcodeLoggingExample
+///
+/// Generates barcodes for a set of sample data and logs generation details to a JSON file.
+///
+class Program
{
- // Represents a single log entry for barcode generation
- public class LogEntry
- {
- public DateTime Timestamp { get; set; }
- public string Symbology { get; set; }
- public string CodeText { get; set; }
- public string OutputFile { get; set; }
- public bool Success { get; set; }
- public string ErrorMessage { get; set; }
- }
-
///
- /// Demonstrates barcode generation and logging of each operation to a JSON file.
+ /// Entry point. Prepares output directories, iterates over sample barcodes, generates each barcode, and records results.
///
- class Program
+ static void Main()
{
- ///
- /// Entry point. Generates sample barcodes, logs details, and writes a JSON log.
- ///
- static void Main()
+ // Define where barcode images and the log file will be stored
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ string logFile = Path.Combine(Directory.GetCurrentDirectory(), "barcode_log.json");
+
+ // Ensure the output directory exists
+ if (!Directory.Exists(outputDir))
{
- // Define sample barcode specifications: symbology name and associated code text
- var samples = new (string Symbology, string CodeText)[]
- {
- ("Code128", "ABC123456"),
- ("QR", "https://example.com"),
- ("DataMatrix", "SampleDM")
- };
+ Directory.CreateDirectory(outputDir);
+ }
- // Collection to hold log entries for each barcode generation attempt
- var logEntries = new List();
+ // Sample data: each tuple contains a symbology name and the text to encode
+ var samples = new (string Symbology, string CodeText)[]
+ {
+ ("Code128", "123ABC"),
+ ("QR", "https://example.com"),
+ ("EAN13", "5901234123457")
+ };
- // Iterate over each sample definition
- foreach (var (symbologyName, codeText) in samples)
- {
- // Initialize a new log entry with basic information
- var entry = new LogEntry
- {
- Timestamp = DateTime.UtcNow,
- Symbology = symbologyName,
- CodeText = codeText,
- OutputFile = $"{symbologyName}.png"
- };
+ // Process each sample, generating a barcode and logging the outcome
+ foreach (var sample in samples)
+ {
+ string outputPath = Path.Combine(outputDir, $"{sample.Symbology}_{DateTime.Now:yyyyMMddHHmmssfff}.png");
+ GenerateAndLogBarcode(sample.Symbology, sample.CodeText, outputPath, logFile);
+ }
- // Resolve the symbology name to the corresponding EncodeTypes field using reflection
- var field = typeof(EncodeTypes).GetField(symbologyName, BindingFlags.Public | BindingFlags.Static);
- if (field == null)
- {
- // Symbology not found – record failure and continue to next sample
- entry.Success = false;
- entry.ErrorMessage = $"Unknown symbology: {symbologyName}";
- logEntries.Add(entry);
- continue;
- }
+ // Inform the user that processing is complete
+ Console.WriteLine("Barcode generation completed. Log written to:");
+ Console.WriteLine(logFile);
+ }
- try
- {
- // Retrieve the EncodeTypes value (BaseEncodeType) for the given symbology
- var encodeType = (BaseEncodeType)field.GetValue(null);
+ ///
+ /// Generates a barcode image for the specified symbology and text, then appends a JSON log entry describing the operation.
+ ///
+ /// The name of the barcode symbology (e.g., "Code128").
+ /// The text or data to encode in the barcode.
+ /// Full file path where the generated PNG image will be saved.
+ /// Full file path of the JSON log file to which the operation details will be appended.
+ static void GenerateAndLogBarcode(string symbologyName, string codeText, string outputPath, string logPath)
+ {
+ bool success = false;
+ string errorMessage = null;
+ string resolvedSymbology = null;
- // Create a barcode generator with the resolved type and provided code text
- using (var generator = new BarcodeGenerator(encodeType, codeText))
- {
- // Optional: adjust barcode parameters (e.g., X-dimension and image resolution)
- generator.Parameters.Barcode.XDimension.Point = 2f;
- generator.Parameters.Resolution = 150; // DPI
+ try
+ {
+ // Resolve the symbology name to an EncodeTypes field using reflection
+ var field = typeof(EncodeTypes).GetField(symbologyName);
+ if (field == null)
+ throw new ArgumentException($"Unknown symbology: {symbologyName}");
- // Save the generated barcode image to the specified file
- generator.Save(entry.OutputFile);
- }
+ var encodeType = (BaseEncodeType)field.GetValue(null);
+ resolvedSymbology = encodeType.TypeName;
- // Mark the operation as successful
- entry.Success = true;
- }
- catch (Exception ex)
- {
- // Capture any exception details for the log entry
- entry.Success = false;
- entry.ErrorMessage = ex.Message;
- }
+ // Create a barcode generator with the resolved type and the provided code text
+ using (var generator = new BarcodeGenerator(encodeType, codeText))
+ {
+ // Example of setting an optional parameter (X-dimension in points)
+ generator.Parameters.Barcode.XDimension.Point = 2f;
- // Add the completed log entry to the collection
- logEntries.Add(entry);
+ // Save the generated barcode as a PNG image
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Serialize the list of log entries to a formatted JSON string
- var jsonOptions = new JsonSerializerOptions { WriteIndented = true };
- string jsonLog = JsonSerializer.Serialize(logEntries, jsonOptions);
-
- // Write the JSON log to a file in the application directory
- const string logFileName = "barcode_log.json";
- File.WriteAllText(logFileName, jsonLog);
+ success = true;
}
+ catch (Exception ex)
+ {
+ // Capture any exception message for logging
+ errorMessage = ex.Message;
+ }
+
+ // Build a log entry object containing all relevant details
+ var logEntry = new
+ {
+ Timestamp = DateTime.UtcNow,
+ SymbologyRequested = symbologyName,
+ SymbologyResolved = resolvedSymbology,
+ CodeText = codeText,
+ OutputFile = outputPath,
+ Success = success,
+ ErrorMessage = errorMessage
+ };
+
+ // Serialize the log entry to a single-line JSON string and append it to the log file
+ string json = JsonSerializer.Serialize(logEntry);
+ File.AppendAllText(logPath, json + Environment.NewLine);
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/implement-retry-mechanism-for-barcode-generation-when-encountering-temporary-file-system-errors.cs b/postal-barcode-types/implement-retry-mechanism-for-barcode-generation-when-encountering-temporary-file-system-errors.cs
index 3f80252..ca461d4 100644
--- a/postal-barcode-types/implement-retry-mechanism-for-barcode-generation-when-encountering-temporary-file-system-errors.cs
+++ b/postal-barcode-types/implement-retry-mechanism-for-barcode-generation-when-encountering-temporary-file-system-errors.cs
@@ -1,85 +1,105 @@
-// Title: Barcode generation with retry on temporary file system errors
-// Description: Demonstrates how to generate a Code128 barcode and retry when IO exceptions occur, ensuring robust file handling.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of BarcodeGenerator, EncodeTypes, and AutoSizeMode. It illustrates typical scenarios where developers need to create barcode images while handling transient file system issues, such as locked files or insufficient permissions, by implementing a retry mechanism.
+// Title: Barcode Generation with Retry on File System Errors
+// Description: Demonstrates generating a Code128 barcode image and saving it to disk with a retry mechanism that handles temporary I/O errors.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator to create barcodes, save them to files, and implement robust error handling for common file system issues such as IOExceptions and UnauthorizedAccessExceptions. Developers often need to ensure reliable barcode creation in batch or automated processes where transient file errors may occur.
// Prompt: Implement a retry mechanism for barcode generation when encountering temporary file system errors.
-// Tags: barcode generation, retry, ioexception, code128, png, aspose.barcode, autosizemode
+// Tags: barcode, symbology, generation, retry, io, exception handling, aspose.barcode, png, code128
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
+using Aspose.BarCode.BarCodeRecognition;
///
-/// Generates a Code128 barcode image with a retry mechanism for handling temporary file system errors.
+/// Example program that generates a barcode image with retry logic for temporary file system errors.
///
class Program
{
///
- /// Entry point of the application. Attempts to generate a barcode image, retrying on IO exceptions.
+ /// Entry point. Sets up parameters and invokes the barcode generation with retry.
///
static void Main()
{
- // Output file path for the generated barcode image
- const string outputPath = "barcode.png";
+ // Define the output file path (current directory + filename)
+ string outputFile = Path.Combine(Directory.GetCurrentDirectory(), "barcode.png");
- // Text to encode in the barcode
- const string codeText = "RetryTest";
+ // Choose barcode symbology and text to encode
+ BaseEncodeType encodeType = EncodeTypes.Code128;
+ string codeText = "123ABC";
- // Maximum number of retry attempts
- const int maxAttempts = 3;
+ // Maximum number of retry attempts for transient file errors
+ int maxAttempts = 3;
- int attempt = 0;
- bool success = false;
+ try
+ {
+ // Attempt to generate and save the barcode with retry logic
+ GenerateBarcodeWithRetry(outputFile, encodeType, codeText, maxAttempts);
+ }
+ catch (Exception ex)
+ {
+ // Log failure after exhausting all retry attempts
+ Console.WriteLine($"Failed to generate barcode after {maxAttempts} attempts: {ex.Message}");
+ }
+ }
- // Loop until the barcode is generated successfully or the max attempts are reached
- while (attempt < maxAttempts && !success)
+ ///
+ /// Generates a barcode image and saves it to the specified path.
+ /// Retries the operation when temporary file system errors occur.
+ ///
+ /// Full file path to save the barcode image.
+ /// The barcode symbology type.
+ /// The text to encode.
+ /// Maximum number of retry attempts.
+ static void GenerateBarcodeWithRetry(string outputPath, BaseEncodeType encodeType, string codeText, int maxAttempts)
+ {
+ // Loop through attempts up to the maximum specified
+ for (int attempt = 1; attempt <= maxAttempts; attempt++)
{
- attempt++;
try
{
- // Initialize the barcode generator with Code128 symbology and the desired text
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ // Ensure the target directory exists before saving
+ string directory = Path.GetDirectoryName(outputPath);
+ if (!Directory.Exists(directory))
{
- // Use auto size mode to let the library determine optimal dimensions
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
-
- // Set barcode and background colors (optional)
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
-
- // Ensure the output directory exists
- string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath));
- if (!Directory.Exists(directory))
- {
- Directory.CreateDirectory(directory);
- }
+ Directory.CreateDirectory(directory);
+ }
- // Save the generated barcode image to the specified path
+ // Create the barcode generator and save the image to disk
+ using (var generator = new BarcodeGenerator(encodeType, codeText))
+ {
generator.Save(outputPath);
}
- Console.WriteLine($"Barcode generated successfully on attempt {attempt}.");
- success = true;
+ // Log success and exit the retry loop
+ Console.WriteLine($"Barcode successfully saved to '{outputPath}' on attempt {attempt}.");
+ break;
}
catch (IOException ioEx)
{
- // Handle temporary file system errors by logging and retrying
+ // Log I/O errors (e.g., file locked) and retry if attempts remain
Console.WriteLine($"IO exception on attempt {attempt}: {ioEx.Message}");
- if (attempt >= maxAttempts)
- {
- Console.WriteLine("Maximum retry attempts reached. Generation failed.");
- }
+ if (attempt == maxAttempts)
+ throw; // Rethrow after final attempt
+ }
+ catch (UnauthorizedAccessException uaEx)
+ {
+ // Log permission errors and retry if attempts remain
+ Console.WriteLine($"Access exception on attempt {attempt}: {uaEx.Message}");
+ if (attempt == maxAttempts)
+ throw;
+ }
+ catch (BarCodeException bcEx)
+ {
+ // Barcode-specific errors are not transient; abort without retry
+ Console.WriteLine($"Barcode generation error on attempt {attempt}: {bcEx.Message}");
+ throw;
}
catch (Exception ex)
{
- // Log unexpected errors and abort further attempts
- Console.WriteLine($"Unexpected error: {ex.Message}");
- break;
+ // Unexpected errors are not retried
+ Console.WriteLine($"Unexpected error on attempt {attempt}: {ex.Message}");
+ throw;
}
}
-
- // Exit with code 0 for success, 1 for failure
- Environment.Exit(success ? 0 : 1);
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/perform-batch-decoding-of-australia-post-barcodes-from-set-of-tiff-images-using-multi-threading.cs b/postal-barcode-types/perform-batch-decoding-of-australia-post-barcodes-from-set-of-tiff-images-using-multi-threading.cs
index 9e4caa7..e187306 100644
--- a/postal-barcode-types/perform-batch-decoding-of-australia-post-barcodes-from-set-of-tiff-images-using-multi-threading.cs
+++ b/postal-barcode-types/perform-batch-decoding-of-australia-post-barcodes-from-set-of-tiff-images-using-multi-threading.cs
@@ -1,107 +1,101 @@
-// Title: Batch decode Australia Post barcodes from TIFF images using multi‑threading
-// Description: Demonstrates how to read Australia Post barcodes from multi‑frame TIFF files in parallel, improving throughput for large image sets.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing multi‑threaded processing of image collections. It uses BarCodeReader, QualitySettings, and DecodeType classes to efficiently decode barcodes. Developers often need to batch‑process scanned documents or shipping labels, and this pattern illustrates best practices for parallel decoding and handling multi‑frame TIFFs.
+// Title: Batch decode Australia Post barcodes from TIFF images using multithreading
+// Description: Demonstrates generating a set of Australia Post barcodes, saving them as TIFF files, and decoding them in parallel across all CPU cores.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator, BarCodeReader, and ProcessorSettings classes for high‑throughput batch processing, a common requirement when handling large volumes of shipping labels or postal data. Developers often need to generate barcodes, store them as images, and later decode them efficiently using multi‑threading.
// Prompt: Perform batch decoding of Australia Post barcodes from a set of TIFF images using multi‑threading.
-// Tags: australia post, barcode, decoding, multithreading, tiff, aspose.barcode, qualitysettings
+// Tags: australia post, barcode, batch, decoding, multithreading, tiff, aspose.barcode
using System;
using System.IO;
+using System.Collections.Generic;
using System.Threading.Tasks;
using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Example program that decodes Australia Post barcodes from TIFF images using parallel processing.
+/// Demonstrates batch generation and multi‑threaded decoding of Australia Post barcodes stored as TIFF images.
///
class Program
{
///
- /// Entry point. Scans a folder for TIFF files, extracts each frame, and decodes Australia Post barcodes in parallel.
+ /// Entry point. Generates sample barcodes, saves them as TIFF files, then decodes them in parallel, finally cleaning up temporary files.
///
static void Main()
{
- // Folder containing TIFF images
- string folderPath = "Barcodes";
+ // Create a unique temporary folder for the sample images
+ string tempFolder = Path.Combine(Path.GetTempPath(), "BatchAustraliaPost_" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(tempFolder);
- // Verify the folder exists
- if (!Directory.Exists(folderPath))
+ // Sample Australia Post barcode texts
+ var sampleTexts = new List
{
- Console.WriteLine($"Folder not found: {folderPath}");
- return;
- }
+ "5912345678AB",
+ "5912345678CD",
+ "5912345678EF",
+ "5912345678GH",
+ "5912345678IJ"
+ };
- // Retrieve up to 5 TIFF files for a safe sample size
- string[] tiffFiles = Directory.GetFiles(folderPath, "*.tif");
- int maxFiles = Math.Min(tiffFiles.Length, 5);
- if (maxFiles == 0)
+ // Generate barcode images (TIFF) and keep the file list
+ var barcodeFiles = new List();
+ foreach (var text in sampleTexts)
{
- Console.WriteLine("No TIFF files found.");
- return;
+ string filePath = Path.Combine(tempFolder, $"{text}.tif");
+ using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, text))
+ {
+ // Use CTable interpreting type for customer information
+ generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable;
+ // Save as TIFF
+ generator.Save(filePath, BarCodeImageFormat.Tiff);
+ }
+ barcodeFiles.Add(filePath);
}
- // Configure the barcode processor to use all available CPU cores
+ // Configure processor settings to use all available cores
BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Environment.ProcessorCount;
- // Process each file in parallel, limiting degree of parallelism to the number of cores
- Parallel.ForEach(tiffFiles, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, (file, state, index) =>
+ // Decode the generated barcodes using parallel processing
+ var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };
+ Parallel.ForEach(barcodeFiles, parallelOptions, file =>
{
- // Enforce the sample size limit
- if (index >= maxFiles) return;
-
try
{
- // Load the TIFF image (supports multi‑frame TIFFs)
- using (Image tiffImage = Image.FromFile(file))
+ using (var reader = new BarCodeReader(file, DecodeType.AustraliaPost))
{
- // Identify the time dimension for frames (multi‑frame TIFF)
- FrameDimension frameDimension = FrameDimension.Time;
- int frameCount = tiffImage.GetFrameCount(frameDimension);
+ // Set decoding parameters matching the generation settings
+ reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
+ reader.BarcodeSettings.AustraliaPost.IgnoreEndingFillingPatternsForCTable = true;
- // Iterate through each frame in the TIFF
- for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
+ var results = reader.ReadBarCodes();
+ foreach (var result in results)
{
- tiffImage.SelectActiveFrame(frameDimension, frameIndex);
-
- // Convert the current frame to a PNG stream (Aspose.Drawing works well with PNG)
- using (MemoryStream ms = new MemoryStream())
- {
- tiffImage.Save(ms, ImageFormat.Png);
- ms.Position = 0;
-
- // Create a bitmap from the PNG stream for barcode reading
- using (Bitmap bitmap = new Bitmap(ms))
- {
- // Initialize the barcode reader for Australia Post symbology
- using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.AustraliaPost))
- {
- // Apply a high‑performance quality preset to speed up decoding
- reader.QualitySettings = QualitySettings.HighPerformance;
-
- // Optional: configure interpreting type if required
- // reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable;
-
- // Perform the decoding
- BarCodeResult[] results = reader.ReadBarCodes();
-
- // Output each decoded result
- foreach (BarCodeResult result in results)
- {
- var rect = result.Region.Rectangle;
- Console.WriteLine($"File: {Path.GetFileName(file)}, Frame: {frameIndex}, Type: {result.CodeTypeName}, Text: {result.CodeText}, Region: {rect}");
- }
- }
- }
- }
+ // Output the decoded information
+ Console.WriteLine($"File: {Path.GetFileName(file)} | Type: {result.CodeType} | Text: {result.CodeText}");
}
}
}
+ catch (ArgumentException ex) when (ex.Message.Contains("Image loading failed"))
+ {
+ // Image could not be loaded – log a warning and continue
+ Console.WriteLine($"Warning: Unable to load image '{Path.GetFileName(file)}'. Skipping.");
+ }
catch (Exception ex)
{
- // Log any errors encountered while processing the file
- Console.WriteLine($"Error processing file '{Path.GetFileName(file)}': {ex.Message}");
+ // Unexpected error – log details for troubleshooting
+ Console.WriteLine($"Error processing '{Path.GetFileName(file)}': {ex.Message}");
}
});
+
+ // Cleanup: delete the temporary folder and its contents
+ try
+ {
+ Directory.Delete(tempFolder, true);
+ }
+ catch
+ {
+ // If deletion fails (e.g., files still in use), ignore – the OS will clean up temp files later.
+ }
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/perform-batch-decoding-of-dutch-kix-barcodes-from-cloud-storage-container-and-log-failures.cs b/postal-barcode-types/perform-batch-decoding-of-dutch-kix-barcodes-from-cloud-storage-container-and-log-failures.cs
index d799459..d15e1d1 100644
--- a/postal-barcode-types/perform-batch-decoding-of-dutch-kix-barcodes-from-cloud-storage-container-and-log-failures.cs
+++ b/postal-barcode-types/perform-batch-decoding-of-dutch-kix-barcodes-from-cloud-storage-container-and-log-failures.cs
@@ -1,8 +1,8 @@
-// Title: Batch decode Dutch KIX barcodes from local folder and log failures
-// Description: Demonstrates generating sample Dutch KIX barcodes, decoding them in bulk, and writing any failures to a log file.
-// Category-Description: This example belongs to the Aspose.BarCode batch processing category, showcasing how to use BarcodeGenerator to create barcodes and BarCodeReader with DecodeType.DutchKIX to read them. Typical use cases include automated verification of large barcode sets stored in cloud or local containers, where developers need to handle success and failure reporting. The snippet highlights key classes such as BarcodeGenerator, BarCodeReader, and common parameters for image handling.
+// Title: Batch decode Dutch KIX (DotCode) barcodes from a folder and log failures
+// Description: Demonstrates generating sample Dutch KIX (DotCode) barcode images, then batch decoding them from a directory that simulates a cloud storage container, while recording any decoding failures.
+// Category-Description: This example belongs to the Aspose.BarCode barcode processing category, focusing on batch recognition of specific symbologies. It showcases the use of BarcodeGenerator for image creation, BarCodeReader with DecodeType.DutchKIX for recognition, and handling of results and errors. Developers often need to process large sets of barcode images from storage, extract data, and log problematic files for further analysis.
// Prompt: Perform batch decoding of Dutch KIX barcodes from a cloud storage container and log failures.
-// Tags: dutch kix, decoding, batch, log, aspose.barcode, barcodegenerator, barcodeReader, png
+// Tags: dotcode, dutchkix, batch-decoding, png, aspose.barcode, aspose.drawing
using System;
using System.IO;
@@ -12,98 +12,99 @@
using Aspose.Drawing.Imaging;
///
-/// Demonstrates batch decoding of Dutch KIX barcodes and logging failures.
+/// Demonstrates batch decoding of Dutch KIX (DotCode) barcodes from a simulated cloud storage container,
+/// including generation of sample images and logging of any decoding failures.
///
class Program
{
///
- /// Entry point. Generates sample barcodes if missing, decodes each PNG, and records any failures.
+ /// Entry point of the example. Generates sample barcode images, decodes them, and logs failures.
///
- static void Main()
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
- // Define the folder that will hold sample barcode images.
- string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
- if (!Directory.Exists(folderPath))
- {
- // Create the folder when it does not exist.
- Directory.CreateDirectory(folderPath);
- }
+ // Folder that represents the cloud storage container.
+ string inputFolder = "InputBarcodes";
+ string logFile = "failures.log";
- // Sample Dutch KIX code texts (5 items for safety).
- string[] sampleCodes = new[]
- {
- "1234567890",
- "0987654321",
- "1122334455",
- "5566778899",
- "0001112223"
- };
+ // Ensure a clean log file before starting.
+ if (File.Exists(logFile))
+ File.Delete(logFile);
- // Generate sample barcode images (if they do not already exist).
- for (int i = 0; i < sampleCodes.Length; i++)
+ // Create the input folder if it does not exist.
+ if (!Directory.Exists(inputFolder))
+ Directory.CreateDirectory(inputFolder);
+
+ // -----------------------------------------------------------------
+ // Generate a few sample Dutch KIX (DotCode) barcode images.
+ // In a real scenario these images would be downloaded from cloud storage.
+ // -----------------------------------------------------------------
+ string[] sampleTexts = { "123456", "ABCDEF", "9876543210" };
+ for (int i = 0; i < sampleTexts.Length; i++)
{
- string filePath = Path.Combine(folderPath, $"sample_{i + 1}.png");
- if (!File.Exists(filePath))
+ string filePath = Path.Combine(inputFolder, $"sample_{i + 1}.png");
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.DotCode, sampleTexts[i]))
{
- // EncodeTypes.DutchKIX is assumed to exist in the Aspose.BarCode library.
- using (var generator = new BarcodeGenerator(EncodeTypes.DutchKIX, sampleCodes[i]))
- {
- // Optional visual settings.
- generator.Parameters.Barcode.BarColor = Color.Black;
- generator.Parameters.BackColor = Color.White;
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 150f;
+ // Optional: set visual parameters for better readability.
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- // Save the generated barcode as PNG.
- generator.Save(filePath, BarCodeImageFormat.Png);
- }
+ // Save the generated barcode as a PNG image.
+ generator.Save(filePath, BarCodeImageFormat.Png);
}
}
- // Path to the log file that will capture any decoding failures.
- string logFilePath = Path.Combine(Directory.GetCurrentDirectory(), "decode_log.txt");
- using (var logWriter = new StreamWriter(logFilePath, false))
+ // -----------------------------------------------------------------
+ // Batch decode all PNG images in the folder as Dutch KIX barcodes.
+ // -----------------------------------------------------------------
+ string[] imageFiles = Directory.GetFiles(inputFolder, "*.png");
+ foreach (string imagePath in imageFiles)
{
- // Retrieve all PNG images from the folder.
- string[] imageFiles = Directory.GetFiles(folderPath, "*.png");
- foreach (string imagePath in imageFiles)
+ try
{
- try
+ // Use the DutchKIX decode type to recognize the specific symbology.
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.DutchKIX))
{
- // Initialize a reader for Dutch KIX barcodes.
- using (var reader = new BarCodeReader(imagePath, DecodeType.DutchKIX))
+ BarCodeResult[] results = reader.ReadBarCodes();
+
+ if (results.Length == 0)
{
- bool decoded = false;
+ // No barcode detected – log the failure.
+ LogFailure(logFile, imagePath, "No barcode detected.");
+ continue;
+ }
- // Iterate through all detected barcodes in the image.
- foreach (var result in reader.ReadBarCodes())
+ foreach (BarCodeResult result in results)
+ {
+ if (string.IsNullOrEmpty(result.CodeText))
{
- if (!string.IsNullOrEmpty(result.CodeText))
- {
- Console.WriteLine($"SUCCESS: File '{Path.GetFileName(imagePath)}' decoded as '{result.CodeText}'.");
- decoded = true;
- }
+ // Barcode detected but the text is empty – log the failure.
+ LogFailure(logFile, imagePath, "Detected barcode but CodeText is empty.");
}
-
- // If no barcode was decoded, log the failure.
- if (!decoded)
+ else
{
- string message = $"FAILURE: No Dutch KIX barcode detected in file '{Path.GetFileName(imagePath)}'.";
- Console.WriteLine(message);
- logWriter.WriteLine(message);
+ // Successful decode – output details to the console.
+ Console.WriteLine($"File: {Path.GetFileName(imagePath)} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
}
}
}
- catch (Exception ex)
- {
- // Log any exceptions that occur during processing.
- string errorMsg = $"ERROR: Exception processing file '{Path.GetFileName(imagePath)}' - {ex.Message}";
- Console.WriteLine(errorMsg);
- logWriter.WriteLine(errorMsg);
- }
+ }
+ catch (Exception ex)
+ {
+ // Unexpected exception – log the failure with the exception message.
+ LogFailure(logFile, imagePath, $"Exception: {ex.Message}");
}
}
- Console.WriteLine("Batch decoding completed. See 'decode_log.txt' for any failures.");
+ Console.WriteLine("Batch decoding completed.");
+ }
+
+ // Helper method to append failure information to the log file and echo it to the console.
+ static void LogFailure(string logPath, string imagePath, string message)
+ {
+ string logEntry = $"[FAIL] File: {Path.GetFileName(imagePath)} - {message}{Environment.NewLine}";
+ File.AppendAllText(logPath, logEntry);
+ Console.WriteLine(logEntry.TrimEnd());
}
}
\ No newline at end of file
diff --git a/postal-barcode-types/perform-batch-decoding-of-mailmark-barcodes-from-collection-of-base64-strings-and-aggregate-results.cs b/postal-barcode-types/perform-batch-decoding-of-mailmark-barcodes-from-collection-of-base64-strings-and-aggregate-results.cs
index c5cd873..cff21e6 100644
--- a/postal-barcode-types/perform-batch-decoding-of-mailmark-barcodes-from-collection-of-base64-strings-and-aggregate-results.cs
+++ b/postal-barcode-types/perform-batch-decoding-of-mailmark-barcodes-from-collection-of-base64-strings-and-aggregate-results.cs
@@ -1,136 +1,117 @@
-// Title: Batch decode Mailmark barcodes from Base64 strings
-// Description: Demonstrates how to generate Mailmark barcodes, encode them to Base64, decode them in bulk, and aggregate the parsed results.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on Mailmark symbology. It showcases the use of BarcodeGenerator, BarCodeReader, and ComplexCodetextReader to create, encode, and decode Mailmark barcodes, a common requirement for postal and logistics applications where bulk processing of barcode data is needed.
+// Title: Batch decode Mailmark barcodes from Base64 images
+// Description: Demonstrates how to decode multiple Mailmark barcodes supplied as Base64‑encoded PNG images and collect the decoded Mailmark objects.
+// Category-Description: This example belongs to the Aspose.BarCode recognition category, focusing on Mailmark symbology. It showcases the use of BarCodeReader with DecodeType.Mailmark and ComplexCodetextReader to extract structured Mailmark data from images. Typical scenarios include processing batches of scanned mail items, aggregating Mailmark information for tracking, and integrating barcode data into downstream systems. Developers working with bulk barcode processing, especially Mailmark, will find this pattern useful.
// Prompt: Perform batch decoding of Mailmark barcodes from a collection of base64 strings and aggregate results.
-// Tags: mailmark, barcode, decoding, batch, base64, aspose.barcode, generation, recognition, complexcodetext
+// Tags: mailmark, barcode, decoding, batch, base64, aspose.barcode, complexcodetext
using System;
-using System.Collections.Generic;
using System.IO;
-using System.Text;
-using Aspose.BarCode.Generation;
+using System.Collections.Generic;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.BarCode.ComplexBarcode;
///
-/// Example program that generates Mailmark barcodes, encodes them as Base64 strings,
-/// decodes them in a batch operation, and prints aggregated results.
+/// Example program that reads a collection of Base64‑encoded PNG images,
+/// decodes any Mailmark barcodes they contain, and aggregates the resulting
+/// Mailmark codetext objects.
///
class Program
{
///
- /// Entry point of the example. Performs the full workflow from creation to batch decoding.
+ /// Entry point of the example. Performs batch decoding of Mailmark barcodes.
///
static void Main()
{
// ------------------------------------------------------------
- // 1. Prepare sample Mailmark codetext objects for demonstration.
+ // Prepare a list of Base64‑encoded PNG images.
+ // Replace the placeholder strings with actual barcode images as needed.
// ------------------------------------------------------------
- var samples = new List
+ var base64Images = new List
{
- CreateMailmark(4, 1, "0", 384224, 16563762, "EF61AH8T "),
- CreateMailmark(4, 1, "1", 384225, 16563763, "EF61AH8T "),
- CreateMailmark(4, 1, "2", 384226, 16563764, "EF61AH8T ")
+ // 1x1 transparent PNG (no barcode)
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+XG6cAAAAASUVORK5CYII=",
+ // Add more base64 strings here
};
- // ------------------------------------------------------------
- // 2. Encode each Mailmark barcode image to a Base64 string.
- // ------------------------------------------------------------
- var base64Barcodes = new List();
- foreach (var mailmark in samples)
- {
- base64Barcodes.Add(EncodeMailmarkToBase64(mailmark));
- }
+ // Collection that will hold successfully decoded Mailmark objects.
+ var decodedResults = new List