From abd32ea54364bf5c090e0f41ea6b7d50d8e8dac9 Mon Sep 17 00:00:00 2001 From: agent-aspose-barcode-examples Date: Tue, 11 Aug 2026 19:52:13 +0500 Subject: [PATCH 1/2] =?UTF-8?q?feat(postal-barcode-types):=20Add=2090=20As?= =?UTF-8?q?pose.BarCode=20.NET=20C#=20examples=20for=20Postal=20Barcode=20?= =?UTF-8?q?Types=20=E2=80=94=20Aspose.BarCode=20for=20.NET=2026.7.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...ile-keeping-automatic-width-calculation.cs | 25 ++- ...de-data-and-returns-image-as-byte-array.cs | 83 +++---- ...or-bars-and-background-exporting-as-png.cs | 39 ++-- ...imension-and-export-image-to-byte-array.cs | 71 +++--- ...dbars-for-all-postal-barcode-operations.cs | 83 ++++--- ...ents-for-symbology-data-and-output-path.cs | 84 ++++---- ...tiff-and-process-each-page-sequentially.cs | 69 +++--- ...-and-handle-potential-format-exceptions.cs | 115 +++++----- ...jpeg-image-and-output-result-to-console.cs | 101 ++++----- ...onse-stream-and-log-any-decoding-errors.cs | 76 ++++--- ...ath-and-retrieve-encoded-numeric-string.cs | 33 ++- ...-stream-and-verify-checksum-correctness.cs | 85 +++----- ...d-in-pdf-page-and-extract-original-data.cs | 142 ++++++++---- ...e-files-after-decrypting-them-in-memory.cs | 166 +++++++------- ...vg-file-and-extract-service-description.cs | 135 +++++++----- ...ng-file-and-confirm-identifier-validity.cs | 78 +++---- ...mp-image-and-verify-checksum-correction.cs | 105 +++++---- ...al-barcodes-for-new-files-automatically.cs | 70 +++--- ...-visual-output-with-default-filled-bars.cs | 55 +++-- ...reed-solomon-error-correction-technique.cs | 86 ++++---- ...ection-and-output-to-memory-mapped-file.cs | 40 ++-- ...nd-store-results-in-memory-stream-array.cs | 106 +++++---- ...st-of-numeric-values-saving-each-as-png.cs | 75 +++---- ...ad-safe-handling-of-generator-instances.cs | 112 +++++----- ...umn-and-save-images-to-specified-folder.cs | 132 ++++++------ ...d-produce-csv-index-linking-identifiers.cs | 84 ++++---- ...te-single-multi-page-pdf-containing-all.cs | 84 ++++---- ...and-combine-them-into-single-tiff-image.cs | 91 ++++---- ...input-validation-and-automatic-checksum.cs | 79 +++---- ...entifiers-and-export-each-as-bmp-images.cs | 101 +++++---- ...rrection-and-custom-xdimension-of-05-mm.cs | 39 ++-- ...tings-and-embed-image-into-pdf-document.cs | 63 +++--- ...and-convert-each-image-to-base64-string.cs | 67 +++--- ...git-numeric-string-and-default-settings.cs | 56 ++--- ...-of-300-and-save-as-high-resolution-png.cs | 48 ++--- ...s-and-embed-images-into-excel-worksheet.cs | 99 +++++---- ...ustom-xdimension-and-default-bar-height.cs | 43 ++-- ...ment-in-email-message-using-smtp-client.cs | 105 +++++---- ...isting-pdf-page-at-specified-coordinate.cs | 57 +++-- ...it-as-blob-in-sql-server-database-table.cs | 94 ++++---- ...-in-json-configuration-and-save-as-jpeg.cs | 145 ++++++------- ...r-human-readable-text-and-export-as-png.cs | 45 ++-- ...ify-image-dimensions-match-expectations.cs | 83 ++++--- ...ound-and-save-as-png-with-alpha-channel.cs | 46 ++-- ...h-overridden-barheight-set-to-30-points.cs | 26 ++- ...able-bar-filling-using-filledbars-false.cs | 34 +-- ...file-and-write-output-to-multi-page-pdf.cs | 178 ++++++++------- ...-attach-service-description-as-metadata.cs | 55 +++-- ...-format-with-human-readable-description.cs | 62 +++--- ...embedded-qr-code-for-supplementary-data.cs | 78 +++---- ...vice-descriptions-and-save-as-svg-files.cs | 68 +++--- ...t-code-starting-with-98-and-output-tiff.cs | 29 ++- ...fier-and-add-custom-margin-around-image.cs | 51 +++-- ...ginal-identifier-string-and-save-as-png.cs | 39 ++-- ...digit-codes-writing-them-to-zip-archive.cs | 96 ++++----- ...ic-checksum-correction-and-save-as-jpeg.cs | 56 +++-- ...ction-and-store-in-cloud-storage-bucket.cs | 56 ++--- ...-and-include-checksum-verification-logs.cs | 149 +++++++------ ...collections-using-task-parallel-library.cs | 150 ++++++------- ...s-using-async-await-pattern-efficiently.cs | 158 ++++++++------ ...ion-values-when-creating-postal-barcode.cs | 103 +++++---- ...-when-barheight-property-is-set-to-zero.cs | 85 +++++--- ...-to-base64-string-for-embedding-in-html.cs | 63 +++--- ...s-with-timestamps-and-source-file-paths.cs | 141 +++++++----- ...nd-outcomes-to-structured-json-log-file.cs | 169 ++++++++------- ...countering-temporary-file-system-errors.cs | 114 ++++++---- ...et-of-tiff-images-using-multi-threading.cs | 126 ++++++----- ...loud-storage-container-and-log-failures.cs | 139 ++++++------ ...of-base64-strings-and-aggregate-results.cs | 177 +++++++-------- ...-storage-and-write-outcomes-to-log-file.cs | 192 +++++++++-------- ...ry-of-png-files-and-generate-csv-report.cs | 147 +++++++------ ...e-streams-and-store-results-in-database.cs | 129 +++++------ ...sed-zip-archive-and-output-json-summary.cs | 172 +++++++++------ ...rom-pdf-and-extract-human-readable-text.cs | 106 ++++++--- ...format-folder-and-generate-excel-report.cs | 203 ++++++++---------- ...rk-share-and-handle-checksum-mismatches.cs | 145 +++++++------ ...-and-decode-it-to-verify-data-integrity.cs | 143 +++++------- ...rcode-and-verify-resulting-module-width.cs | 37 ++-- ...rcode-and-write-image-to-network-stream.cs | 87 +++----- ...services-within-aspnet-core-application.cs | 115 +++++----- ...re-uppercase-conversion-before-encoding.cs | 117 ++++++---- ...se-exception-for-non-numeric-characters.cs | 79 ++++--- ...c-characters-by-inspecting-encoded-data.cs | 91 ++++---- ...ters-by-comparing-expected-bit-patterns.cs | 122 +++++++---- ...000-planet-barcodes-from-memory-streams.cs | 95 ++++---- ...mailmark-barcodes-with-default-settings.cs | 51 ++--- ...swiss-post-parcel-international-barcode.cs | 94 ++++---- ...-bar-shapes-while-preserving-dimensions.cs | 153 +++++++------ ...culation-without-affecting-module-width.cs | 103 +++++---- ...rrect-output-for-australia-post-barcode.cs | 120 ++++++----- 90 files changed, 4521 insertions(+), 3977 deletions(-) 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 = $"\"barcode\""; + + // 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..a2f7148 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,106 +1,102 @@ -// 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 sample Australia Post barcodes, storing them as TIFF files, and decoding them concurrently with Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode batch processing category, showcasing how to work with the BarCodeGenerator and BarCodeReader classes for high‑throughput barcode operations. Typical use cases include bulk scanning of shipping labels, automated inventory checks, and large‑scale document processing where multi‑core decoding improves performance. Developers often need to generate test barcodes, configure processor settings, and read results in parallel. // 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: barcode, decoding, australia post, multithreading, tiff, aspose.barcode, batch processing using System; using System.IO; 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. +/// Sample program that creates a set of Australia Post barcode images and decodes them in parallel. /// class Program { /// - /// Entry point. Scans a folder for TIFF files, extracts each frame, and decodes Australia Post barcodes in parallel. + /// Entry point of the application. Generates sample TIFF images containing Australia Post barcodes + /// and then decodes all images concurrently, writing results to the console. /// static void Main() { - // Folder containing TIFF images - string folderPath = "Barcodes"; - - // Verify the folder exists - if (!Directory.Exists(folderPath)) + // Define the folder that will hold the sample TIFF images. + string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(inputFolder)) { - Console.WriteLine($"Folder not found: {folderPath}"); - return; + Directory.CreateDirectory(inputFolder); } - // 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) + // Sample Australia Post barcode texts (valid formats). + string[] sampleCodes = new string[] { - Console.WriteLine("No TIFF files found."); - return; + "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 + }; + + // Generate a TIFF file for each sample code if it does not already exist. + for (int i = 0; i < sampleCodes.Length; i++) + { + string code = sampleCodes[i]; + string filePath = Path.Combine(inputFolder, $"barcode_{i + 1}.tif"); + + if (File.Exists(filePath)) + continue; // Skip existing files to avoid unnecessary regeneration. + + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, code)) + { + // Use CTable for customer information interpretation (alternatively NTable may be used). + generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable; + // Save the generated barcode as a TIFF image. + generator.Save(filePath, BarCodeImageFormat.Tiff); + } } - // Configure the barcode processor to use all available CPU cores + // Configure the barcode reader to utilize all available CPU 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) => + // Retrieve all TIFF files from the input folder. + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif"); + + if (tiffFiles.Length == 0) { - // Enforce the sample size limit - if (index >= maxFiles) return; + Console.WriteLine("No TIFF images found for decoding."); + return; + } + // Decode each TIFF image in parallel to maximize throughput. + Parallel.ForEach(tiffFiles, filePath => + { try { - // Load the TIFF image (supports multi‑frame TIFFs) - using (Image tiffImage = Image.FromFile(file)) + BaseDecodeType decodeType = DecodeType.AustraliaPost; + using (BarCodeReader reader = new BarCodeReader(filePath, decodeType)) { - // Identify the time dimension for frames (multi‑frame TIFF) - FrameDimension frameDimension = FrameDimension.Time; - int frameCount = tiffImage.GetFrameCount(frameDimension); + BarCodeResult[] results = reader.ReadBarCodes(); - // Iterate through each frame in the TIFF - for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) + // Output each detected barcode. + 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(); + Console.WriteLine($"File: {Path.GetFileName(filePath)} | Detected: {result.CodeType} | CodeText: {result.CodeText}"); + } - // 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}"); - } - } - } - } + // Inform if no barcode was found in the image. + if (results.Length == 0) + { + Console.WriteLine($"File: {Path.GetFileName(filePath)} | No barcode detected."); } } } catch (Exception ex) { - // Log any errors encountered while processing the file - Console.WriteLine($"Error processing file '{Path.GetFileName(file)}': {ex.Message}"); + // Log any errors that occur during processing of a specific file. + Console.WriteLine($"Error processing file '{Path.GetFileName(filePath)}': {ex.Message}"); } }); } 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(); // ------------------------------------------------------------ - // 3. Batch decode the Base64 strings back into Mailmark objects. + // Iterate over each Base64 string, decode it to an image, + // and attempt to read Mailmark barcodes. // ------------------------------------------------------------ - var decodedResults = new List(); - foreach (var base64 in base64Barcodes) + foreach (var base64 in base64Images) { - // Convert the Base64 string back to raw image bytes. - byte[] imageBytes = Convert.FromBase64String(base64); - using (var ms = new MemoryStream(imageBytes)) - using (var reader = new BarCodeReader(ms, DecodeType.Mailmark)) + // Skip empty or whitespace strings. + if (string.IsNullOrWhiteSpace(base64)) { - // Allow recognition of potentially imperfect barcodes. - reader.QualitySettings.AllowIncorrectBarcodes = true; + Console.WriteLine("Skipped empty base64 string."); + continue; + } - // Read all barcodes found in the image (normally one per image here). - foreach (var result in reader.ReadBarCodes()) + // Convert the Base64 string to a byte array. + byte[] imageBytes; + try + { + imageBytes = Convert.FromBase64String(base64); + } + catch (FormatException) + { + Console.WriteLine("Invalid base64 string, skipping."); + continue; + } + + // Use a memory stream to feed the image bytes to the barcode reader. + using (var ms = new MemoryStream(imageBytes)) + { + // Initialize BarCodeReader for Mailmark decoding. + using (var reader = new BarCodeReader(ms, DecodeType.Mailmark)) { - // Decode the raw codetext into a structured Mailmark object. - MailmarkCodetext decoded = ComplexCodetextReader.TryDecodeMailmark(result.CodeText); - if (decoded != null) + BarCodeResult[] results; + try + { + // Attempt to read all barcodes in the image. + results = reader.ReadBarCodes(); + } + catch (Exception ex) + { + Console.WriteLine($"Error during barcode reading: {ex.Message}"); + continue; + } + + // If no barcodes were found, move to the next image. + if (results.Length == 0) + { + Console.WriteLine("No barcode detected in this image."); + continue; + } + + // Process each detected barcode. + foreach (var result in results) { - decodedResults.Add(decoded); + Console.WriteLine($"Detected barcode type: {result.CodeTypeName}"); + Console.WriteLine($"Raw CodeText: {result.CodeText}"); + + // Try to decode the Mailmark codetext into a structured object. + var mailmark = ComplexCodetextReader.TryDecodeMailmark(result.CodeText); + if (mailmark != null) + { + Console.WriteLine("Mailmark codetext successfully decoded."); + decodedResults.Add(mailmark); + } + else + { + Console.WriteLine("Failed to decode Mailmark codetext."); + } } } } } // ------------------------------------------------------------ - // 4. Aggregate and display the decoding results. + // Output the total number of successfully decoded Mailmark objects. // ------------------------------------------------------------ - Console.WriteLine($"Total barcodes processed: {base64Barcodes.Count}"); - Console.WriteLine($"Successfully decoded: {decodedResults.Count}"); Console.WriteLine(); - - int index = 1; - foreach (var m in decodedResults) - { - Console.WriteLine($"Barcode #{index++}"); - Console.WriteLine($" Format: {m.Format}"); - Console.WriteLine($" VersionID: {m.VersionID}"); - Console.WriteLine($" Class: {m.Class}"); - Console.WriteLine($" SupplychainID: {m.SupplychainID}"); - Console.WriteLine($" ItemID: {m.ItemID}"); - Console.WriteLine($" DestinationPostCodePlusDPS: {m.DestinationPostCodePlusDPS}"); - Console.WriteLine(); - } - } - - /// - /// Helper method to create a MailmarkCodetext instance with the required fields. - /// - /// Mailmark format identifier. - /// Version identifier. - /// Class code (single character). - /// Supply chain identifier. - /// Item identifier. - /// Destination postcode plus DPS. - /// Configured MailmarkCodetext object. - private static MailmarkCodetext CreateMailmark(int format, int versionId, string classCode, int supplyChainId, int itemId, string destinationPostCodePlusDps) - { - var mailmark = new MailmarkCodetext - { - Format = format, - VersionID = versionId, - Class = classCode, - SupplychainID = supplyChainId, - ItemID = itemId, - DestinationPostCodePlusDPS = destinationPostCodePlusDps - }; - return mailmark; - } - - /// - /// Generates a Mailmark barcode image from the provided codetext and returns its Base64 representation. - /// - /// Mailmark codetext object to encode. - /// Base64 string of the generated PNG barcode image. - private static string EncodeMailmarkToBase64(MailmarkCodetext mailmark) - { - // Construct the raw codetext string required by the generator. - string codetext = mailmark.GetConstructedCodetext(); - - // Generate the barcode image and write it to a memory stream. - using (var generator = new BarcodeGenerator(EncodeTypes.Mailmark, codetext)) - using (var ms = new MemoryStream()) - { - generator.Save(ms, BarCodeImageFormat.Png); - // Convert the image bytes to a Base64 string for transport/storage. - return Convert.ToBase64String(ms.ToArray()); - } + Console.WriteLine($"Total Mailmark codetext objects decoded: {decodedResults.Count}"); } } \ No newline at end of file diff --git a/postal-barcode-types/perform-batch-decoding-of-onecode-barcodes-from-azure-blob-storage-and-write-outcomes-to-log-file.cs b/postal-barcode-types/perform-batch-decoding-of-onecode-barcodes-from-azure-blob-storage-and-write-outcomes-to-log-file.cs index 24504dd..b72570c 100644 --- a/postal-barcode-types/perform-batch-decoding-of-onecode-barcodes-from-azure-blob-storage-and-write-outcomes-to-log-file.cs +++ b/postal-barcode-types/perform-batch-decoding-of-onecode-barcodes-from-azure-blob-storage-and-write-outcomes-to-log-file.cs @@ -1,126 +1,138 @@ -// Title: Batch decode OneCode barcodes from Azure Blob storage and log results -// Description: Demonstrates how to read OneCode barcodes from image files (simulating Azure Blob storage) and write decoding details to a log file. -// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing the BarCodeReader class for OneCode symbology. It illustrates typical batch processing, quality settings, and result logging, which developers often need when integrating barcode scanning into cloud storage workflows. +// Title: Batch decode OneCode barcodes and write results to a log file +// Description: Demonstrates how to read multiple OneCode barcodes using Aspose.BarCode, handling up to five images, and write the decoding outcomes to a timestamped log file. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating batch processing of images, use of BarCodeReader with DecodeType.OneCode, and logging. Developers working with bulk barcode scanning, Azure Blob storage integration, or automated reporting can adapt this pattern for their solutions. // Prompt: Perform batch decoding of OneCode barcodes from an Azure Blob storage and write outcomes to a log file. -// Tags: onecode, barcode, decoding, batch, log, aspose.barcode, azure blob, qualitysettings +// Tags: onecode, barcode, decoding, batch, log, aspose.barcode, azure blob, image processing using System; using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Demonstrates batch decoding of OneCode barcodes from a local folder (as a stand‑in for Azure Blob storage) -/// and writes detailed results to a log file. +/// Demonstrates batch decoding of OneCode barcodes and logging the results. /// class Program { /// - /// Entry point of the example. Scans up to five image files, decodes OneCode barcodes, - /// and records outcomes in decode_log.txt. + /// Entry point that performs decoding and logging. /// - static void Main() + /// Command‑line arguments (not used). + static void Main(string[] args) { - // Folder that would contain images downloaded from Azure Blob storage (fallback for demo) - string imagesFolder = "SampleBarcodes"; + // ----------------------------------------------------------------- + // NOTE: In a real environment you would download images from Azure + // Blob Storage using Azure.Storage.Blobs SDK. The SDK is not + // available in the snippet runner, so this example uses a local + // folder ("Barcodes") as a stand‑in for the blob container. + // ----------------------------------------------------------------- - // Path of the log file that will receive decoding results - string logFilePath = "decode_log.txt"; + // Define the folder that simulates the Azure Blob container + string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + // Define the path of the log file that will receive decoding results + string logFile = Path.Combine(Directory.GetCurrentDirectory(), "OneCodeDecodeLog.txt"); - // Ensure a fresh log file for each run - if (File.Exists(logFilePath)) + // Ensure the input folder exists + if (!Directory.Exists(inputFolder)) { - File.Delete(logFilePath); + Directory.CreateDirectory(inputFolder); } - // Open a StreamWriter for the log file (non‑appending mode) - using (var logWriter = new StreamWriter(logFilePath, append: false)) + // ----------------------------------------------------------------- + // Create a few sample OneCode barcode images (OneCode requires a + // numeric CodeText of length 20, 25, 29 or 31). This makes the example + // self‑contained and runnable without external files. + // ----------------------------------------------------------------- + CreateSampleBarcodes(inputFolder); + + // Clear any previous log content + if (File.Exists(logFile)) { - // Retrieve up to five image files from the folder - string[] imageFiles = Array.Empty(); - if (Directory.Exists(imagesFolder)) - { - // Get all files and filter by common image extensions - imageFiles = Directory.GetFiles(imagesFolder, "*.*", SearchOption.TopDirectoryOnly); - imageFiles = Array.FindAll(imageFiles, f => - f.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || - f.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || - f.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) || - f.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase)); + File.Delete(logFile); + } + + // Retrieve up to 5 PNG files from the folder + string[] imageFiles = Directory.GetFiles(inputFolder, "*.png"); + int maxFiles = Math.Min(imageFiles.Length, 5); - // Limit the collection to a maximum of five files for the demo - if (imageFiles.Length > 5) + // Process each image file + for (int i = 0; i < maxFiles; i++) + { + string imagePath = imageFiles[i]; + try + { + // Initialize reader for OneCode symbology + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.OneCode)) { - Array.Resize(ref imageFiles, 5); + BarCodeResult[] results = reader.ReadBarCodes(); + + // If no barcode was detected, log the information + if (results.Length == 0) + { + AppendLog(logFile, $"[{Path.GetFileName(imagePath)}] No barcode detected."); + continue; + } + + // Log each detected barcode's type and text + foreach (BarCodeResult result in results) + { + string line = $"[{Path.GetFileName(imagePath)}] Type: {result.CodeTypeName}, Text: {result.CodeText}"; + AppendLog(logFile, line); + } } } - else + catch (Exception ex) { - // Log missing folder and exit early - logWriter.WriteLine($"Images folder not found: {imagesFolder}"); - return; + // Log any errors that occur while processing the image + AppendLog(logFile, $"[{Path.GetFileName(imagePath)}] Error: {ex.Message}"); } + } - // Iterate over each image and attempt barcode decoding - foreach (string imagePath in imageFiles) - { - if (!File.Exists(imagePath)) - { - logWriter.WriteLine($"File not found: {imagePath}"); - continue; - } + Console.WriteLine($"Decoding completed. Log written to: {logFile}"); + } - try - { - // Initialize BarCodeReader for OneCode symbology - using (var reader = new BarCodeReader(imagePath, DecodeType.OneCode)) - { - // Apply a normal quality preset (optional but recommended) - reader.QualitySettings = QualitySettings.NormalQuality; + // Helper to append a line to the log file with a timestamp + private static void AppendLog(string logPath, string message) + { + string entry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} {message}{Environment.NewLine}"; + File.AppendAllText(logPath, entry); + } - // Perform the decoding operation - BarCodeResult[] results = reader.ReadBarCodes(); + // Generates a few OneCode barcode images in the specified folder + private static void CreateSampleBarcodes(string folder) + { + // Sample numeric code texts of valid OneCode lengths (20 digits) + string[] sampleTexts = new[] + { + "12345678901234567890", + "98765432109876543210", + "11111111111111111111" + }; - if (results.Length == 0) - { - // No barcode detected in the current image - logWriter.WriteLine($"{Path.GetFileName(imagePath)}: No OneCode barcode detected."); - } - else - { - // Log details for each detected barcode - foreach (var result in results) - { - var rect = result.Region.Rectangle; - logWriter.WriteLine($"{Path.GetFileName(imagePath)}: Type={result.CodeTypeName}, Text={result.CodeText}, Confidence={result.Confidence}, Quality={result.ReadingQuality}, Region=({rect.X},{rect.Y},{rect.Width},{rect.Height})"); - } - } - } - } - catch (Exception ex) + for (int i = 0; i < sampleTexts.Length; i++) + { + string filePath = Path.Combine(folder, $"OneCode_{i + 1}.png"); + try + { + // EncodeTypes.OneCode exists for OneCode generation + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.OneCode, sampleTexts[i])) { - // Record any exception that occurs during processing - logWriter.WriteLine($"{Path.GetFileName(imagePath)}: Error - {ex.Message}"); + // Optional: adjust barcode appearance + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Parameters.Barcode.Padding.Left.Point = 5f; + generator.Parameters.Barcode.Padding.Right.Point = 5f; + + // Save as PNG + generator.Save(filePath, BarCodeImageFormat.Png); } } + catch (Exception ex) + { + // If OneCode generation is not supported, log the issue. + AppendLog(Path.Combine(folder, "generation_errors.log"), $"Failed to generate {filePath}: {ex.Message}"); + } } - - // Placeholder for Azure Blob Storage download logic (commented out because the SDK is unavailable in this environment) - /* - // using Azure.Storage.Blobs; - // string connectionString = ""; - // string containerName = ""; - // BlobContainerClient container = new BlobContainerClient(connectionString, containerName); - // foreach (BlobItem blobItem in container.GetBlobs()) - // { - // string localPath = Path.Combine(imagesFolder, blobItem.Name); - // BlobClient blob = container.GetBlobClient(blobItem.Name); - // blob.DownloadTo(localPath); - // // Then process localPath as shown above. - // } - */ - - // Inform the user that processing is complete - Console.WriteLine("Decoding completed. See log file: " + logFilePath); } } \ No newline at end of file diff --git a/postal-barcode-types/perform-batch-decoding-of-planet-barcodes-from-directory-of-png-files-and-generate-csv-report.cs b/postal-barcode-types/perform-batch-decoding-of-planet-barcodes-from-directory-of-png-files-and-generate-csv-report.cs index 027f74d..0075818 100644 --- a/postal-barcode-types/perform-batch-decoding-of-planet-barcodes-from-directory-of-png-files-and-generate-csv-report.cs +++ b/postal-barcode-types/perform-batch-decoding-of-planet-barcodes-from-directory-of-png-files-and-generate-csv-report.cs @@ -1,108 +1,129 @@ // Title: Batch decode Planet barcodes and generate CSV report -// Description: Demonstrates how to read Planet symbology barcodes from PNG images in a folder and output the results to a CSV file. -// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating the use of BarCodeReader with DecodeType.Planet, QualitySettings, and BarCodeResult to process multiple images. Developers often need to batch‑process barcodes for inventory, logistics, or data‑entry automation, and this pattern shows how to collect decoded data into a structured report. +// Description: Demonstrates how to read multiple Planet barcode images from a folder, decode them, and export the results to a CSV file. +// Category-Description: This example belongs to the Aspose.BarCode batch processing category, illustrating the use of BarCodeReader for decoding and BarcodeGenerator for creating sample barcodes. Typical use cases include bulk barcode validation, inventory scanning, and automated reporting where developers need to process many images and collect decoded data in a structured format. // Prompt: Perform batch decoding of Planet barcodes from a directory of PNG files and generate a CSV report. -// Tags: planet, barcode, batch decoding, csv, aspose.barcode, barcodereader, decode type +// Tags: planet, barcode, decoding, csv, aspose.barcode, generation, recognition using System; using System.IO; using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates batch decoding of Planet barcodes from PNG files and generating a CSV report. +/// Provides a console application that batch‑processes Planet barcode images, +/// decodes their contents, and writes a CSV report summarising the results. /// class Program { /// - /// Entry point. Scans a directory for PNG images, decodes up to 10 Planet barcodes, and writes results to a CSV file. + /// Entry point of the application. Scans a folder for PNG images containing + /// Planet barcodes, decodes each image, and creates a CSV file with the + /// filename and decoded text. /// - /// Optional first argument specifying the input directory; defaults to "Barcodes". - static void Main(string[] args) + static void Main() { - // Determine input directory: use first argument if provided, otherwise default to "Barcodes" - string inputDir = args.Length > 0 ? args[0] : "Barcodes"; + // Define the folder that holds input PNG files and the output CSV file name. + string inputFolder = "Barcodes"; + string outputCsv = "PlanetBarcodesReport.csv"; - // Define output CSV file name - const string outputCsv = "PlanetBarcodesReport.csv"; - - // Verify that the input directory exists - if (!Directory.Exists(inputDir)) + // Ensure the input folder exists; create it if it does not. + if (!Directory.Exists(inputFolder)) { - Console.WriteLine($"Input directory does not exist: {inputDir}"); - return; + Directory.CreateDirectory(inputFolder); } - // Retrieve all PNG files in the top level of the directory - string[] pngFiles = Directory.GetFiles(inputDir, "*.png", SearchOption.TopDirectoryOnly); - if (pngFiles.Length == 0) + // If the folder is empty, generate a few sample Planet barcode images for demo purposes. + if (Directory.GetFiles(inputFolder, "*.png").Length == 0) { - Console.WriteLine($"No PNG files found in directory: {inputDir}"); - return; + GenerateSampleBarcodes(inputFolder); } - // Limit processing to a safe sample size (maximum 10 files) - int maxFiles = Math.Min(pngFiles.Length, 10); + // Initialise a StringBuilder to construct the CSV content. + var csvBuilder = new StringBuilder(); + csvBuilder.AppendLine("FileName,CodeText"); - // Open the CSV writer with UTF‑8 encoding - using (var writer = new StreamWriter(outputCsv, false, Encoding.UTF8)) + // Iterate over each PNG file in the input folder. + foreach (string filePath in Directory.GetFiles(inputFolder, "*.png")) { - // Write CSV header row - writer.WriteLine("\"FileName\",\"CodeText\",\"CodeTypeName\",\"ReadingQuality\",\"Confidence\""); + // Verify the file still exists (defensive check). + if (!File.Exists(filePath)) + { + Console.WriteLine($"File not found: {filePath}"); + continue; + } - // Process each selected PNG file - for (int i = 0; i < maxFiles; i++) + // Use BarCodeReader configured for the Planet symbology to decode the image. + using (var reader = new BarCodeReader(filePath, DecodeType.Planet)) { - string filePath = pngFiles[i]; - string fileName = Path.GetFileName(filePath); + var results = reader.ReadBarCodes(); - // Defensive check – the file should exist because it came from GetFiles - if (!File.Exists(filePath)) + // If no barcode was detected, write an empty entry for this file. + if (results.Length == 0) { + csvBuilder.AppendLine($"{Path.GetFileName(filePath)},"); continue; } - // Initialize barcode reader for Planet symbology - using (var reader = new BarCodeReader(filePath, DecodeType.Planet)) + // Write each detected barcode to the CSV (Planet typically yields a single result). + foreach (var result in results) { - // Apply a normal quality preset (optional but recommended) - reader.QualitySettings = QualitySettings.NormalQuality; + string codeText = result.CodeText ?? string.Empty; - // Decode all barcodes in the image - BarCodeResult[] results = reader.ReadBarCodes(); - - if (results.Length == 0) + // Escape commas in the decoded text to preserve CSV structure. + if (codeText.Contains(",")) { - // No barcode detected – write a row with empty fields - writer.WriteLine($"{Quote(fileName)},\"\",\"\",,\"\""); - continue; + codeText = $"\"{codeText}\""; } - // Write up to three detected barcodes per image for safety - int maxResults = Math.Min(results.Length, 3); - for (int r = 0; r < maxResults; r++) - { - var result = results[r]; - string codeText = result.CodeText ?? ""; - string codeType = result.CodeTypeName ?? ""; - string readingQuality = result.ReadingQuality - .ToString(System.Globalization.CultureInfo.InvariantCulture); - string confidence = result.Confidence.ToString(); - - writer.WriteLine($"{Quote(fileName)},{Quote(codeText)},{Quote(codeType)},{Quote(readingQuality)},{Quote(confidence)}"); - } + csvBuilder.AppendLine($"{Path.GetFileName(filePath)},{codeText}"); } } } - Console.WriteLine($"Decoding completed. Report saved to: {outputCsv}"); + // Attempt to write the accumulated CSV data to the output file. + try + { + File.WriteAllText(outputCsv, csvBuilder.ToString()); + Console.WriteLine($"Report generated: {outputCsv}"); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to write CSV report: {ex.Message}"); + } } - // Helper to escape CSV fields by surrounding with double quotes and escaping internal quotes - private static string Quote(string field) + /// + /// Generates a set of sample Planet barcode images in the specified folder. + /// This helper is used only when the input directory is initially empty. + /// + /// The directory where sample PNG files will be saved. + private static void GenerateSampleBarcodes(string folder) { - if (field == null) field = ""; - string escaped = field.Replace("\"", "\"\""); - return $"\"{escaped}\""; + // Sample texts to encode into Planet barcodes. + string[] sampleTexts = { "12345", "9876543210", "ABCDEF", "00112233", "9999999999" }; + + for (int i = 0; i < sampleTexts.Length; i++) + { + string text = sampleTexts[i]; + string fileName = Path.Combine(folder, $"Planet_{i + 1}.png"); + + // Create a Planet barcode generator for the current sample text. + using (var generator = new BarcodeGenerator(EncodeTypes.Planet, text)) + { + // Optional appearance adjustments. + generator.Parameters.Barcode.XDimension.Point = 2f; + 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; + + // Save the generated barcode as a PNG image. + generator.Save(fileName, BarCodeImageFormat.Png); + } + } + + Console.WriteLine($"Generated {sampleTexts.Length} sample Planet barcode images in '{folder}'."); } } \ No newline at end of file diff --git a/postal-barcode-types/perform-batch-decoding-of-postnet-barcodes-from-list-of-image-streams-and-store-results-in-database.cs b/postal-barcode-types/perform-batch-decoding-of-postnet-barcodes-from-list-of-image-streams-and-store-results-in-database.cs index 94c6ffd..f88f3c5 100644 --- a/postal-barcode-types/perform-batch-decoding-of-postnet-barcodes-from-list-of-image-streams-and-store-results-in-database.cs +++ b/postal-barcode-types/perform-batch-decoding-of-postnet-barcodes-from-list-of-image-streams-and-store-results-in-database.cs @@ -1,115 +1,100 @@ -// Title: Batch decode Postnet barcodes from image streams and save results -// Description: Demonstrates how to read multiple Postnet barcodes from a collection of image files, extract details, and persist them as JSON (simulating database storage). -// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing the BarCodeReader class for batch decoding of Postnet symbology. Typical use cases include processing shipments, mail sorting, or any bulk scanning scenario where many barcode images need to be read and stored. Developers often need to iterate over image streams, extract barcode metadata, and integrate results with databases or services. +// Title: Batch decode Postnet barcodes from memory streams +// Description: Demonstrates generating Postnet barcode images, decoding them in a batch, and persisting the results to a JSON file (as a stand‑in for a database). +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator for creating Postnet symbology, BarCodeReader for batch decoding, and common .NET I/O classes for handling image streams. Developers working with bulk barcode processing, automated scanning, or data import pipelines often need to generate, read, and store barcode information efficiently. // Prompt: Perform batch decoding of Postnet barcodes from a list of image streams and store results in a database. -// Tags: postnet, barcode, batch decoding, json, aspose.barcode, barcodereader, decoding, database +// Tags: postnet, barcode, decoding, batch, json, aspose.barcode, aspose.drawing using System; using System.Collections.Generic; using System.IO; using System.Text.Json; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; // Required for Bitmap if needed +using Aspose.Drawing; +using Aspose.Drawing.Imaging; namespace PostnetBatchDecode { /// - /// Simple record to hold decoding results for each processed image. + /// Simple DTO to hold decoding results for each processed image. /// public class DecodeRecord { - public string FileName { get; set; } + public int Index { get; set; } public string CodeText { get; set; } public string CodeTypeName { get; set; } - public double ReadingQuality { get; set; } - public int RegionX { get; set; } - public int RegionY { get; set; } - public int RegionWidth { get; set; } - public int RegionHeight { get; set; } } /// - /// Demonstrates batch decoding of Postnet barcodes from image files and persisting results. + /// Demonstrates batch generation and decoding of Postnet barcodes, then stores the results. /// class Program { /// - /// Entry point. Reads a list of image files, decodes Postnet barcodes, and writes results to a JSON file. + /// Entry point. Generates sample Postnet barcodes, decodes them, and writes results to a JSON file. /// - static void Main() + /// Command‑line arguments (not used). + static void Main(string[] args) { - // Define a sample list of image file paths containing Postnet barcodes. - // In production these streams could be retrieved from a database, cloud storage, etc. - var imageFiles = new List - { - "postnet1.png", - "postnet2.png", - "postnet3.png" - }; - - // Collection to store decoding results. - var results = new List(); + // Define a set of sample Postnet code texts. + var sampleCodes = new List { "12345", "67890", "24680", "13579", "11223" }; - // Process each image file individually. - foreach (var filePath in imageFiles) + // Generate barcode images and keep them as memory streams. + var imageStreams = new List(); + foreach (var code in sampleCodes) { - // Verify that the file exists before attempting to read it. - if (!File.Exists(filePath)) + using (var generator = new BarcodeGenerator(EncodeTypes.Postnet, code)) { - Console.WriteLine($"File not found: {filePath}"); - continue; + var ms = new MemoryStream(); + // Save the barcode image to the memory stream in PNG format. + generator.Save(ms, BarCodeImageFormat.Png); + ms.Position = 0; // Reset for reading. + imageStreams.Add(ms); } + } - // Open the image file as a read‑only stream. - using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) + // Prepare a list to collect decoding results. + var results = new List(); + + // Decode each image stream using the Postnet decode type. + BaseDecodeType postnetDecode = DecodeType.Postnet; + int index = 0; + foreach (var stream in imageStreams) + { + // Ensure the stream is positioned at the beginning. + stream.Position = 0; + using (var reader = new BarCodeReader(stream, postnetDecode)) { - // Initialize BarCodeReader for the Postnet symbology. - using (BarCodeReader reader = new BarCodeReader(fs, DecodeType.Postnet)) + var barCodes = reader.ReadBarCodes(); + foreach (var result in barCodes) { - // Read all barcodes present in the image. - BarCodeResult[] barcodes = reader.ReadBarCodes(); - - // Iterate through each detected barcode. - foreach (var result in barcodes) + results.Add(new DecodeRecord { - // Extract the bounding rectangle of the barcode region. - var rect = result.Region.Rectangle; - - // Populate a DecodeRecord with relevant information. - var record = new DecodeRecord - { - FileName = Path.GetFileName(filePath), - CodeText = result.CodeText, - CodeTypeName = result.CodeTypeName, - ReadingQuality = result.ReadingQuality, - RegionX = rect.X, - RegionY = rect.Y, - RegionWidth = rect.Width, - RegionHeight = rect.Height - }; - - // Add the record to the results collection. - results.Add(record); - - // Output a brief summary to the console. - Console.WriteLine($"Decoded from {record.FileName}: {record.CodeText} (Type: {record.CodeTypeName})"); - } + Index = index, + CodeText = result.CodeText, + CodeTypeName = result.CodeTypeName + }); + Console.WriteLine($"Image {index}: Type={result.CodeTypeName}, Text={result.CodeText}"); } } + index++; } - // Serialize the results to JSON (acting as a stand‑in for database storage). - string outputPath = "postnet_decode_results.json"; + // Store results in a JSON file (simulating a database). + string jsonPath = "postnet_results.json"; var jsonOptions = new JsonSerializerOptions { WriteIndented = true }; string json = JsonSerializer.Serialize(results, jsonOptions); - File.WriteAllText(outputPath, json); - Console.WriteLine($"Decoding results saved to {outputPath}"); + File.WriteAllText(jsonPath, json); + Console.WriteLine($"Decoding results saved to {jsonPath}"); + + // Cleanup memory streams. + foreach (var ms in imageStreams) + { + ms.Dispose(); + } - // Real database storage could be implemented here, e.g., using SQLite or another DB. - // Example (commented out because the required NuGet package is not available in the runner): - // using var connection = new SqliteConnection("Data Source=postnet.db"); - // connection.Open(); - // // Create table and insert records... + // Note: In a real scenario, you would insert 'results' into a database + // using an appropriate data access library (e.g., SQLite, SQL Server, etc.). } } } \ No newline at end of file diff --git a/postal-barcode-types/perform-batch-decoding-of-rm4scc-barcodes-from-compressed-zip-archive-and-output-json-summary.cs b/postal-barcode-types/perform-batch-decoding-of-rm4scc-barcodes-from-compressed-zip-archive-and-output-json-summary.cs index 6357dcc..f1e96c4 100644 --- a/postal-barcode-types/perform-batch-decoding-of-rm4scc-barcodes-from-compressed-zip-archive-and-output-json-summary.cs +++ b/postal-barcode-types/perform-batch-decoding-of-rm4scc-barcodes-from-compressed-zip-archive-and-output-json-summary.cs @@ -1,14 +1,15 @@ -// Title: Batch decode RM4SCC barcodes from ZIP and output JSON summary -// Description: Demonstrates how to extract images from a ZIP archive, decode RM4SCC barcodes using Aspose.BarCode, and produce a JSON report of the results. -// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating batch processing of image files within compressed archives. It showcases the BarCodeReader, DecodeType, and QualitySettings classes for high‑performance decoding, a common requirement for developers handling large volumes of barcodes in automated workflows. +// Title: Batch decode RM4SCC barcodes from a ZIP archive and output JSON summary +// Description: Demonstrates how to generate sample RM4SCC barcode images, package them into a ZIP file, decode each image, and produce a JSON report of the decoded values. +// Category-Description: This example belongs to the Aspose.BarCode barcode processing category, focusing on batch decoding of images stored in compressed archives. It showcases the use of BarcodeGenerator for creating barcodes, BarCodeReader for recognition, and .NET ZipArchive for handling ZIP files. Developers often need to process large sets of barcode images efficiently, and this pattern provides a reusable approach for such scenarios. // Prompt: Perform batch decoding of RM4SCC barcodes from a compressed ZIP archive and output JSON summary. -// Tags: rm4scc, batch decoding, zip, json, aspose.barcode, barcodereader, qualitysettings +// Tags: rm4scc, batch decoding, zip, json, aspose.barcode, barcodegeneration, barcoderecognition using System; using System.IO; using System.IO.Compression; using System.Collections.Generic; using System.Text.Json; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; @@ -17,93 +18,130 @@ /// class Program { - // Simple DTO for JSON output - class BarcodeInfo - { - public string FileName { get; set; } - public string CodeTypeName { get; set; } - public string CodeText { get; set; } - public RectangleInfo Region { get; set; } - } - - class RectangleInfo - { - public int X { get; set; } - public int Y { get; set; } - public int Width { get; set; } - public int Height { get; set; } - } - /// - /// Entry point. Reads a ZIP file (default "barcodes.zip" or first argument), decodes RM4SCC barcodes in image entries, and prints a JSON report. + /// Entry point of the example. Generates a sample ZIP if missing, decodes barcodes, and prints JSON. /// - /// Command‑line arguments; optionally the path to the ZIP archive. + /// Command‑line arguments (not used). static void Main(string[] args) { - // Determine ZIP archive path; allow override via first command‑line argument - string zipPath = args.Length > 0 ? args[0] : "barcodes.zip"; + // Path for the sample ZIP archive + string zipPath = Path.Combine(Directory.GetCurrentDirectory(), "rm4scc_barcodes.zip"); - // Validate that the ZIP file exists + // Ensure a sample ZIP exists (generate if missing) if (!File.Exists(zipPath)) { - Console.WriteLine($"Error: ZIP file not found at '{zipPath}'."); - return; + CreateSampleZip(zipPath); } - // Collection to hold decoding results for JSON serialization - var summary = new List(); + // Decode all RM4SCC barcodes inside the ZIP and collect results + var summary = DecodeBarcodesFromZip(zipPath); + + // Serialize summary to JSON and output to console + string json = JsonSerializer.Serialize(summary, new JsonSerializerOptions { WriteIndented = true }); + Console.WriteLine(json); + } + + // Generates a ZIP file containing a few RM4SCC barcode images + private static void CreateSampleZip(string zipPath) + { + // Temporary folder to hold generated images before zipping + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); - // Open the ZIP archive for reading - using (FileStream zipStream = new FileStream(zipPath, FileMode.Open, FileAccess.Read)) - using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Read)) + try { - // Iterate over each entry in the archive - foreach (ZipArchiveEntry entry in archive.Entries) + // Create 3 sample barcodes + for (int i = 1; i <= 3; i++) { - // Process only common image file extensions - string ext = Path.GetExtension(entry.Name).ToLowerInvariant(); - if (ext != ".png" && ext != ".jpg" && ext != ".jpeg" && ext != ".bmp") + string codeText = $"AB{i:D2}CD"; // Simple 6‑character code suitable for RM4SCC + string fileName = $"barcode_{i}.png"; + string filePath = Path.Combine(tempDir, fileName); + + using (var generator = new BarcodeGenerator(EncodeTypes.RM4SCC, codeText)) + { + // Save directly to file as PNG + generator.Save(filePath, BarCodeImageFormat.Png); + } + } + + // Create ZIP archive from the generated files + using (var zipToCreate = new FileStream(zipPath, FileMode.Create)) + using (var archive = new ZipArchive(zipToCreate, ZipArchiveMode.Create)) + { + foreach (string file in Directory.GetFiles(tempDir, "*.png")) + { + string entryName = Path.GetFileName(file); + archive.CreateEntryFromFile(file, entryName); + } + } + } + finally + { + // Clean up temporary files + if (Directory.Exists(tempDir)) + { + Directory.Delete(tempDir, true); + } + } + } + + // Reads the ZIP archive, decodes RM4SCC barcodes, and returns a summary object + private static List DecodeBarcodesFromZip(string zipPath) + { + var results = new List(); + + using (var zipStream = new FileStream(zipPath, FileMode.Open, FileAccess.Read)) + using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Read)) + { + foreach (var entry in archive.Entries) + { + // Process only image files (PNG/JPG/BMP) + if (!entry.FullName.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !entry.FullName.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !entry.FullName.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) && + !entry.FullName.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase)) + { continue; + } - // Open the image entry stream and create a barcode reader for RM4SCC - using (Stream entryStream = entry.Open()) - using (BarCodeReader reader = new BarCodeReader(entryStream, DecodeType.RM4SCC)) + using (var entryStream = entry.Open()) + using (var memory = new MemoryStream()) { - // Use a high‑performance preset for faster decoding; adjust if needed - reader.QualitySettings = QualitySettings.HighPerformance; + // Copy entry data to memory for decoding + entryStream.CopyTo(memory); + memory.Position = 0; - // Read all barcodes found in the image - BarCodeResult[] results = reader.ReadBarCodes(); - foreach (BarCodeResult result in results) - { - // Skip results without readable text - if (string.IsNullOrEmpty(result.CodeText)) - continue; + var decodedTexts = new List(); - // Map the result to the DTO - var rect = result.Region.Rectangle; - var info = new BarcodeInfo + // Use BarCodeReader with RM4SCC decode type + using (var reader = new BarCodeReader(memory, DecodeType.RM4SCC)) + { + foreach (var result in reader.ReadBarCodes()) { - FileName = entry.Name, - CodeTypeName = result.CodeTypeName, - CodeText = result.CodeText, - Region = new RectangleInfo + if (!string.IsNullOrEmpty(result.CodeText)) { - X = rect.X, - Y = rect.Y, - Width = rect.Width, - Height = rect.Height + decodedTexts.Add(result.CodeText); } - }; - summary.Add(info); + } } + + // Store decoding results for this file + results.Add(new DecodedFile + { + FileName = entry.FullName, + Codes = decodedTexts + }); } } } - // Serialize the collected information to formatted JSON and output to console - var jsonOptions = new JsonSerializerOptions { WriteIndented = true }; - string json = JsonSerializer.Serialize(summary, jsonOptions); - Console.WriteLine(json); + return results; + } + + // Helper class to hold decoding results per file + private class DecodedFile + { + public string FileName { get; set; } + public List Codes { get; set; } } } \ No newline at end of file diff --git a/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-additional-service-code-barcodes-from-pdf-and-extract-human-readable-text.cs b/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-additional-service-code-barcodes-from-pdf-and-extract-human-readable-text.cs index 126da3d..f986a8f 100644 --- a/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-additional-service-code-barcodes-from-pdf-and-extract-human-readable-text.cs +++ b/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-additional-service-code-barcodes-from-pdf-and-extract-human-readable-text.cs @@ -1,64 +1,109 @@ -// Title: Batch decode Swiss Post Parcel barcodes from PDF -// Description: Demonstrates how to extract Swiss Post Parcel additional service code barcodes from a PDF file and output their human‑readable text. -// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating the use of BarCodeReader with DecodeType.SwissPostParcel and Aspose.Pdf conversion utilities. It shows typical batch processing of multi‑page PDFs to locate and decode specific barcode symbologies, a common requirement for logistics and postal automation solutions. Developers can adapt this pattern for other barcode types and document sources. +// Title: Batch decode Swiss Post Parcel barcodes from a PDF +// Description: Demonstrates generating a PDF with a Swiss Post Parcel barcode and then decoding all such barcodes from each page of the PDF. +// Category-Description: This example belongs to the Aspose.BarCode for .NET suite, showcasing barcode generation (BarcodeGenerator) and recognition (BarCodeReader) together with Aspose.Pdf conversion (PdfConverter). Typical scenarios include batch processing of documents to extract Swiss Post Parcel service codes for logistics and tracking. Developers often need to render PDF pages to images, enable barcode optimization, and read multiple barcodes efficiently. // Prompt: Perform batch decoding of Swiss Post Parcel additional service code barcodes from a PDF and extract human‑readable text. -// Tags: barcode, swisspostparcel, batch decoding, pdf, aspose.barcode, aspose.pdf, console +// Tags: swisspostparcel, batch decoding, pdf, aspose.barcode, aspose.pdf using System; using System.IO; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Pdf; using Aspose.Pdf.Facades; /// -/// Example program that reads Swiss Post Parcel barcodes from a PDF document and prints their decoded text. +/// Demonstrates creating a sample PDF containing a Swiss Post Parcel barcode +/// and then batch‑decoding all such barcodes from each page of the PDF. /// class Program { /// - /// Main entry point. Loads a PDF, converts each page to an image, and decodes Swiss Post Parcel barcodes. + /// Entry point of the example. Ensures a sample PDF exists and triggers barcode decoding. /// static void Main() { - // Path to the PDF containing Swiss Post Parcel barcodes. - const string pdfPath = "sample.pdf"; + // Path to the PDF that will be processed + const string pdfPath = "SwissPostParcelSample.pdf"; - // Verify that the PDF file exists before proceeding. + // If the PDF does not exist, create a simple sample PDF containing a Swiss Post Parcel barcode if (!File.Exists(pdfPath)) { - Console.WriteLine($"PDF file not found: {pdfPath}"); - return; + CreateSamplePdf(pdfPath); } - // Load the PDF document using Aspose.Pdf. - using (var pdfDocument = new Document(pdfPath)) + // Decode Swiss Post Parcel barcodes from the PDF + DecodeBarcodesFromPdf(pdfPath); + } + + // Creates a PDF with a single page that contains a Swiss Post Parcel barcode + private static void CreateSamplePdf(string path) + { + // Sample code text for Swiss Post Parcel (including an additional service code example) + const string sampleCodeText = "1234567890AB"; + + // Generate barcode image into a memory stream (PNG format) + using (var barcodeStream = new MemoryStream()) { - int totalPages = pdfDocument.Pages.Count; + using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, sampleCodeText)) + { + // Save the barcode as PNG directly to the stream + generator.Save(barcodeStream, BarCodeImageFormat.Png); + barcodeStream.Position = 0; + } + + // Create a new PDF document and add the barcode image to the first page + using (var pdfDoc = new Document()) + { + var page = pdfDoc.Pages.Add(); + var image = new Aspose.Pdf.Image + { + ImageStream = new MemoryStream(barcodeStream.ToArray()) + }; + page.Paragraphs.Add(image); + pdfDoc.Save(path); + } + } - // Limit processing to a maximum of 4 pages as per evaluation guidelines. - int pagesToProcess = Math.Min(4, totalPages); + Console.WriteLine($"Sample PDF created at '{path}'."); + } - // Iterate through each page to be processed. - for (int pageNumber = 1; pageNumber <= pagesToProcess; pageNumber++) + // Decodes all Swiss Post Parcel barcodes from each page of the specified PDF + private static void DecodeBarcodesFromPdf(string pdfPath) + { + if (!File.Exists(pdfPath)) + { + Console.WriteLine($"Error: PDF file '{pdfPath}' does not exist."); + return; + } + + // Open the PDF document + using (var pdfDoc = new Document(pdfPath)) + { + // Initialize the PDF converter for rendering pages to images + using (var pdfConverter = new PdfConverter(pdfDoc)) { - // Initialize the PDF converter for the current page. - using (var pdfConverter = new PdfConverter(pdfDocument)) + // Enable barcode optimization for better extraction + pdfConverter.RenderingOptions.BarcodeOptimization = true; + + int pageCount = pdfDoc.Pages.Count; + + // Iterate through each page in the PDF + for (int pageNumber = 1; pageNumber <= pageCount; pageNumber++) { - pdfConverter.RenderingOptions.BarcodeOptimization = true; + // Configure the converter to process a single page pdfConverter.StartPage = pageNumber; pdfConverter.EndPage = pageNumber; pdfConverter.DoConvert(); - // Render the page to an in‑memory image stream. - using (var imageStream = new MemoryStream()) + // Render the current page to an image stream + using (var pageImageStream = new MemoryStream()) { - pdfConverter.GetNextImage(imageStream); - imageStream.Position = 0; // Reset stream position for reading. + pdfConverter.GetNextImage(pageImageStream); + pageImageStream.Position = 0; - // Create a barcode reader configured for Swiss Post Parcel barcodes. - using (var reader = new BarCodeReader(imageStream, DecodeType.SwissPostParcel)) + // Read barcodes from the rendered image + using (var reader = new BarCodeReader(pageImageStream, DecodeType.SwissPostParcel)) { - // Attempt to read all barcodes on the page. var results = reader.ReadBarCodes(); if (results.Length == 0) @@ -67,10 +112,11 @@ static void Main() } else { - // Output each detected barcode's type and decoded text. foreach (var result in results) { - Console.WriteLine($"Page {pageNumber}: Barcode Type = {result.CodeTypeName}, CodeText = {result.CodeText}"); + Console.WriteLine($"Page {pageNumber}: Detected barcode"); + Console.WriteLine($" Type : {result.CodeTypeName}"); + Console.WriteLine($" CodeText: {result.CodeText}"); } } } diff --git a/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-domestic-barcodes-from-mixed-format-folder-and-generate-excel-report.cs b/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-domestic-barcodes-from-mixed-format-folder-and-generate-excel-report.cs index 5db0ab5..0aae377 100644 --- a/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-domestic-barcodes-from-mixed-format-folder-and-generate-excel-report.cs +++ b/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-domestic-barcodes-from-mixed-format-folder-and-generate-excel-report.cs @@ -1,159 +1,144 @@ -// Title: Batch decode Swiss Post Parcel barcodes and export to Excel -// Description: Demonstrates how to read Swiss Post Parcel domestic barcodes from various image and PDF files in a folder and generate an Excel report summarizing the results. -// Category-Description: This example belongs to the Aspose.BarCode batch processing category. It showcases the use of BarCodeReader for decoding SwissPostParcel symbology, BarcodeGenerator for creating sample barcodes, and Aspose.Cells for building an Excel report. Typical scenarios include bulk barcode validation, inventory auditing, and automated data extraction where developers need to process mixed‑format files and produce structured outputs. +// Title: Batch decode Swiss Post Parcel barcodes and generate Excel report +// Description: Demonstrates how to decode Swiss Post Parcel domestic barcodes from image files in a folder and compile the results into an Excel spreadsheet. +// Category-Description: This example belongs to the Aspose.BarCode batch processing category, illustrating the use of BarcodeGenerator, BarCodeReader, and Aspose.Cells to generate barcode images, perform bulk decoding, and export results to Excel. Typical use cases include processing large sets of shipping labels, validating barcode data, and creating reports for logistics operations. Developers often need to combine barcode generation, recognition, and spreadsheet output in automated workflows. // Prompt: Perform batch decoding of Swiss Post Parcel domestic barcodes from a mixed‑format folder and generate an Excel report. -// Tags: barcode, swisspostparcel, batch-decoding, excel, aspose.barcode, aspose.cells, report +// Tags: swisspostparcel, decoding, excel, aspose.barcode, aspose.cells using System; -using System.Collections.Generic; using System.IO; +using System.Collections.Generic; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Cells; using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Demonstrates batch decoding of Swiss Post Parcel barcodes from a mixed‑format folder -/// and generates an Excel report containing the decoded information. +/// Example program that generates sample Swiss Post Parcel barcodes, decodes them in bulk, +/// and writes the decoding results to an Excel report. /// class Program { /// - /// Simple DTO to hold barcode information for the report. - /// - private class BarcodeInfo - { - public string FileName { get; set; } - public string CodeType { get; set; } - public string CodeText { get; set; } - public int Confidence { get; set; } - public double ReadingQuality { get; set; } - public string Region { get; set; } - } - - /// - /// Entry point of the example. Scans the input folder, decodes Swiss Post Parcel barcodes, - /// and writes the results to an Excel workbook. + /// Entry point of the application. /// - static void Main() + /// Command‑line arguments (not used). + static void Main(string[] args) { - // Define input folder containing mixed‑format images/PDFs - string inputFolder = Path.Combine(Environment.CurrentDirectory, "InputBarcodes"); - // Define output Excel report path - string reportPath = Path.Combine(Environment.CurrentDirectory, "BarcodeReport.xlsx"); - - // Ensure the input folder exists - if (!Directory.Exists(inputFolder)) + // -------------------------------------------------------------------- + // Define source folder for barcode images and destination path for report + // -------------------------------------------------------------------- + string baseFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + string reportPath = Path.Combine(Directory.GetCurrentDirectory(), "SwissPostParcelReport.xlsx"); + + // Ensure the barcode folder exists + if (!Directory.Exists(baseFolder)) { - Directory.CreateDirectory(inputFolder); + Directory.CreateDirectory(baseFolder); } - // Seed a sample Swiss Post Parcel barcode image if the folder is empty - SeedSampleIfEmpty(inputFolder); - - // Supported file extensions for barcode scanning - string[] extensions = new[] { ".png", ".jpg", ".jpeg", ".tif", ".tiff", ".pdf" }; - var files = new List(); - foreach (var ext in extensions) + // -------------------------------------------------------------- + // Sample data representing Swiss Post Parcel barcode values + // -------------------------------------------------------------- + var sampleData = new List { - // Collect files with the current extension (non‑recursive) - files.AddRange(Directory.GetFiles(inputFolder, "*" + ext, SearchOption.TopDirectoryOnly)); + "1234567890123456", + "9876543210987654", + "5555555555555555" + }; + + // -------------------------------------------------------------- + // Generate PNG barcode images for each sample value (if not already present) + // -------------------------------------------------------------- + foreach (var codeText in sampleData) + { + string filePath = Path.Combine(baseFolder, $"SwissPost_{codeText}.png"); + if (File.Exists(filePath)) + continue; + + // Resolve EncodeTypes.SwissPostParcel via reflection (API may not expose it directly) + var encodeField = typeof(EncodeTypes).GetField("SwissPostParcel"); + if (encodeField == null) + { + Console.WriteLine("EncodeTypes does not contain SwissPostParcel. Skipping generation."); + continue; + } + BaseEncodeType encodeType = (BaseEncodeType)encodeField.GetValue(null); + + using (BarcodeGenerator generator = new BarcodeGenerator(encodeType, codeText)) + { + // Save the generated barcode as a PNG file + generator.Save(filePath, BarCodeImageFormat.Png); + } } - // Limit processing to a safe number of files (max 10) to avoid long runtimes - int maxFiles = Math.Min(10, files.Count); - var results = new List(); + // -------------------------------------------------------------- + // Prepare a collection to store decoding results + // -------------------------------------------------------------- + var results = new List(); - // Iterate over each file and decode barcodes - for (int i = 0; i < maxFiles; i++) + // -------------------------------------------------------------- + // Scan the folder for PNG files and decode each using SwissPostParcel symbology + // -------------------------------------------------------------- + var imageFiles = Directory.GetFiles(baseFolder, "*.png"); + foreach (var imageFile in imageFiles) { - string filePath = files[i]; - if (!File.Exists(filePath)) - { - Console.WriteLine($"File not found: {filePath}"); + if (!File.Exists(imageFile)) continue; - } - // Create a reader configured for Swiss Post Parcel barcodes - using (var reader = new BarCodeReader(filePath, DecodeType.SwissPostParcel)) + BaseDecodeType decodeType = DecodeType.SwissPostParcel; + using (BarCodeReader reader = new BarCodeReader(imageFile, decodeType)) { - // Read all barcodes present in the file foreach (var result in reader.ReadBarCodes()) { - var info = new BarcodeInfo + results.Add(new DecodeResult { - FileName = Path.GetFileName(filePath), - CodeType = result.CodeTypeName, + FileName = Path.GetFileName(imageFile), CodeText = result.CodeText ?? string.Empty, - Confidence = (int)result.Confidence, - ReadingQuality = result.ReadingQuality, - Region = $"X={result.Region.Rectangle.X},Y={result.Region.Rectangle.Y},W={result.Region.Rectangle.Width},H={result.Region.Rectangle.Height}" - }; - results.Add(info); + Symbology = result.CodeTypeName, + Confidence = result.Confidence.ToString() + }); } } } - // Generate Excel report using Aspose.Cells - using (var workbook = new Workbook()) + // -------------------------------------------------------------- + // Create an Excel workbook and populate it with the decoding data + // -------------------------------------------------------------- + using (Workbook workbook = new Workbook()) { - var sheet = workbook.Worksheets[0]; + Worksheet sheet = workbook.Worksheets[0]; - // Write header row + // Header row sheet.Cells[0, 0].PutValue("File Name"); - sheet.Cells[0, 1].PutValue("Barcode Type"); - sheet.Cells[0, 2].PutValue("Code Text"); + sheet.Cells[0, 1].PutValue("Code Text"); + sheet.Cells[0, 2].PutValue("Symbology"); sheet.Cells[0, 3].PutValue("Confidence"); - sheet.Cells[0, 4].PutValue("Reading Quality"); - sheet.Cells[0, 5].PutValue("Region (X,Y,W,H)"); - // Write data rows - for (int row = 0; row < results.Count; row++) + // Data rows + for (int i = 0; i < results.Count; i++) { - var info = results[row]; - int excelRow = row + 1; - sheet.Cells[excelRow, 0].PutValue(info.FileName); - sheet.Cells[excelRow, 1].PutValue(info.CodeType); - sheet.Cells[excelRow, 2].PutValue(info.CodeText); - sheet.Cells[excelRow, 3].PutValue(info.Confidence); - sheet.Cells[excelRow, 4].PutValue(info.ReadingQuality); - sheet.Cells[excelRow, 5].PutValue(info.Region); + var r = results[i]; + int row = i + 1; + sheet.Cells[row, 0].PutValue(r.FileName); + sheet.Cells[row, 1].PutValue(r.CodeText); + sheet.Cells[row, 2].PutValue(r.Symbology); + sheet.Cells[row, 3].PutValue(r.Confidence); } - // Auto‑fit columns for better readability - sheet.AutoFitColumns(); - - // Save the report to the specified path - workbook.Save(reportPath); + // Save the workbook to the specified path + workbook.Save(reportPath, SaveFormat.Xlsx); } - Console.WriteLine($"Barcode decoding completed. Report saved to: {reportPath}"); + Console.WriteLine($"Decoding completed. Report saved to: {reportPath}"); } - /// - /// Generates a sample Swiss Post Parcel barcode image if the input folder contains no files. - /// - /// Path to the folder where the sample image will be created. - private static void SeedSampleIfEmpty(string folderPath) + // Simple DTO to hold decoding information + private class DecodeResult { - var existingFiles = Directory.GetFiles(folderPath); - if (existingFiles.Length > 0) - return; - - // Sample codetext for a domestic Swiss Post Parcel barcode (example format) - string sampleCodeText = "1234567890123456789012345"; - - string sampleImagePath = Path.Combine(folderPath, "SampleSwissPostParcel.png"); - - // Generate the sample barcode image - using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, sampleCodeText)) - { - // Use auto‑size mode for simplicity - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - // Save as PNG - generator.Save(sampleImagePath); - } - - Console.WriteLine($"Sample barcode image created at: {sampleImagePath}"); + public string FileName { get; set; } + public string CodeText { get; set; } + public string Symbology { get; set; } + public string Confidence { get; set; } } } \ No newline at end of file diff --git a/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-international-barcodes-from-network-share-and-handle-checksum-mismatches.cs b/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-international-barcodes-from-network-share-and-handle-checksum-mismatches.cs index 014a12b..a6e8d43 100644 --- a/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-international-barcodes-from-network-share-and-handle-checksum-mismatches.cs +++ b/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-international-barcodes-from-network-share-and-handle-checksum-mismatches.cs @@ -1,109 +1,112 @@ -// Title: Batch decode Swiss Post Parcel barcodes from network share -// Description: Demonstrates how to read Swiss Post Parcel international barcodes in a batch from a shared folder, validating checksums and handling mismatches. -// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating the use of BarCodeReader with DecodeType.SwissPostParcel, checksum validation, and file system iteration. Developers working with postal barcode processing, bulk image handling, or network shares can reference this pattern for extracting barcode data and detecting errors. +// Title: Batch decode Swiss Post Parcel barcodes with checksum validation +// Description: Demonstrates how to read multiple Swiss Post Parcel barcodes from a folder (simulating a network share), validate checksums, and report mismatches. +// Category-Description: This example belongs to the barcode recognition and generation category of Aspose.BarCode for .NET. It showcases using BarCodeReader for batch decoding, configuring checksum validation, and using BarcodeGenerator to create sample barcodes. Developers working with bulk barcode processing, validation, and integration with file systems commonly use these APIs. // Prompt: Perform batch decoding of Swiss Post Parcel international barcodes from a network share and handle checksum mismatches. -// Tags: swisspostparcel, barcode, batch, decoding, checksum, network share, aspose.barcode +// Tags: swisspostparcel, batch decoding, checksum validation, barcodereader, barcodegenerator, console output using System; using System.IO; using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Example program that batch processes image files from a network share, -/// decodes Swiss Post Parcel barcodes, and validates their checksums. +/// Example program that batch‑processes Swiss Post Parcel barcodes from a folder, +/// validates their checksums, and outputs the results to the console. /// class Program { /// - /// Entry point. Scans a folder for supported image files, reads Swiss Post Parcel barcodes, - /// and outputs barcode details including checksum information. + /// Entry point. Scans a folder for PNG images, reads Swiss Post Parcel barcodes, + /// validates checksums, and reports successful reads or mismatches. /// - /// Optional first argument specifying the input folder path. - static void Main(string[] args) + static void Main() { - // Determine the input folder: use first argument or default network share path. - string inputFolder = args.Length > 0 ? args[0] : @"\\localhost\share\barcodes"; + // Define the folder that simulates a network share. + // For the purpose of this self‑contained example we use a local folder. + string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); - // Verify that the folder exists before proceeding. - if (!Directory.Exists(inputFolder)) + // Ensure the folder exists. + if (!Directory.Exists(folderPath)) { - Console.WriteLine($"Input folder does not exist: {inputFolder}"); - return; + Directory.CreateDirectory(folderPath); } - // Define supported image extensions for barcode scanning. - string[] extensions = new[] { ".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp" }; - string[] files = Directory.GetFiles(inputFolder); - int processed = 0; - const int maxFiles = 10; // Safety cap to limit batch size. + // Seed a few sample Swiss Post Parcel barcodes if the folder is empty. + SeedSampleBarcodes(folderPath); - // Iterate over each file in the folder. - foreach (string filePath in files) + // Retrieve all PNG image files in the folder. + string[] imageFiles = Directory.GetFiles(folderPath, "*.png"); + foreach (string imageFile in imageFiles) { - // Stop processing once the maximum file count is reached. - if (processed >= maxFiles) break; - - // Skip files with unsupported extensions. - string ext = Path.GetExtension(filePath); - if (Array.IndexOf(extensions, ext, 0, extensions.Length) < 0) continue; - - // Ensure the file still exists (it might have been removed). - if (!File.Exists(filePath)) + // Verify the file exists before processing. + if (!File.Exists(imageFile)) { - Console.WriteLine($"File not found: {filePath}"); + Console.WriteLine($"File not found: {imageFile}"); continue; } - try + // Create a reader configured for Swiss Post Parcel barcodes. + using (BarCodeReader reader = new BarCodeReader(imageFile, DecodeType.SwissPostParcel)) { - // Initialize the barcode reader for Swiss Post Parcel symbology. - using (var reader = new BarCodeReader(filePath, DecodeType.SwissPostParcel)) - { - // Enable checksum validation to detect mismatches. - reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; + // Enable checksum validation. + reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; - bool anyFound = false; + // Disallow recognition of barcodes with incorrect checksums. + reader.QualitySettings.AllowIncorrectBarcodes = false; - // Read all barcodes found in the current image. - foreach (BarCodeResult result in reader.ReadBarCodes()) - { - anyFound = true; - Console.WriteLine($"File: {Path.GetFileName(filePath)}"); - Console.WriteLine($" Type: {result.CodeTypeName}"); - Console.WriteLine($" CodeText: {result.CodeText}"); + // Read all barcodes from the image. + BarCodeResult[] results = reader.ReadBarCodes(); - // Attempt to retrieve checksum information if available. - try - { - string checksum = result.Extended.OneD.CheckSum; - if (!string.IsNullOrEmpty(checksum)) - { - Console.WriteLine($" CheckSum: {checksum}"); - } - } - catch - { - // Extended.OneD may not be applicable for this symbology; ignore silently. - } - } + if (results.Length == 0) + { + Console.WriteLine($"No barcode detected in file: {Path.GetFileName(imageFile)}"); + continue; + } - // Inform the user if no barcode was detected in the file. - if (!anyFound) + // Process each detected barcode. + foreach (BarCodeResult result in results) + { + // If CodeText is null or empty, the checksum likely failed. + if (string.IsNullOrEmpty(result.CodeText)) + { + Console.WriteLine($"Checksum mismatch in file: {Path.GetFileName(imageFile)}"); + } + else { - Console.WriteLine($"No Swiss Post Parcel barcode detected in file: {Path.GetFileName(filePath)}"); + Console.WriteLine($"File: {Path.GetFileName(imageFile)} | Type: {result.CodeTypeName} | Text: {result.CodeText}"); } } } - catch (Exception ex) + } + } + + // Generates a few sample Swiss Post Parcel barcodes if none exist. + private static void SeedSampleBarcodes(string folderPath) + { + // Check if there are already PNG files. + if (Directory.GetFiles(folderPath, "*.png").Length > 0) + return; + + // Sample data for Swiss Post Parcel barcodes. + string[] sampleTexts = new[] + { + "1234567890123456", // Example valid code (replace with real format as needed) + "9876543210987654", + "5555555555555555" + }; + + // Create a barcode image for each sample text. + for (int i = 0; i < sampleTexts.Length; i++) + { + string filePath = Path.Combine(folderPath, $"Sample{i + 1}.png"); + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, sampleTexts[i])) { - // Report any errors encountered while processing the file. - Console.WriteLine($"Error processing file '{Path.GetFileName(filePath)}': {ex.Message}"); + // Optional: adjust barcode appearance. + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Save(filePath, BarCodeImageFormat.Png); } - - processed++; } - - Console.WriteLine("Batch decoding completed."); } } \ No newline at end of file diff --git a/postal-barcode-types/retrieve-stored-barcode-blob-from-database-and-decode-it-to-verify-data-integrity.cs b/postal-barcode-types/retrieve-stored-barcode-blob-from-database-and-decode-it-to-verify-data-integrity.cs index d5af3ad..6668382 100644 --- a/postal-barcode-types/retrieve-stored-barcode-blob-from-database-and-decode-it-to-verify-data-integrity.cs +++ b/postal-barcode-types/retrieve-stored-barcode-blob-from-database-and-decode-it-to-verify-data-integrity.cs @@ -1,8 +1,8 @@ // Title: Retrieve and Decode Barcode BLOB from Database -// Description: Demonstrates reading a barcode image stored as a BLOB, decoding it, and verifying that the decoded data matches the original text. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, showcasing how to work with binary data (BLOBs) using BarcodeGenerator and BarCodeReader classes. Typical use cases include persisting barcodes in databases, retrieving them for verification, and ensuring data integrity in inventory or tracking systems. Developers often need to convert between image files, byte arrays, and decoded values, which this sample illustrates. +// Description: Demonstrates generating a barcode, storing it as a BLOB, retrieving it, and decoding to verify data integrity. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It shows how to use BarcodeGenerator to create a barcode image, store it as a binary BLOB, and then use BarCodeReader with DecodeType.AllSupportedTypes to detect and decode the barcode. Developers often need to persist barcodes in databases and later validate them, making this pattern useful for inventory, ticketing, and authentication systems. // Prompt: Retrieve a stored barcode BLOB from the database and decode it to verify data integrity. -// Tags: barcode, blob, decode, data integrity, code128, aspnet, aspose.barcode, generation, recognition +// Tags: barcode, code128, generation, recognition, blob, data integrity, aspose.barcode, csharp using System; using System.IO; @@ -11,112 +11,85 @@ using Aspose.Drawing; /// -/// Example program that simulates retrieving a barcode image stored as a BLOB, -/// decodes it using Aspose.BarCode, and verifies data integrity against the original text. +/// Demonstrates generating a barcode, persisting it as a BLOB, retrieving it, and decoding to verify data integrity. /// class Program { /// - /// Entry point of the example. Generates or loads a barcode BLOB, decodes it, - /// and checks that the decoded value matches the expected text. + /// Entry point of the example. Generates a Code128 barcode, saves it to a temporary file, + /// reads the file into a byte array (simulating a database BLOB), decodes the barcode, + /// and checks that the decoded text matches the original. /// static void Main() { - // Paths for simulated BLOB storage and temporary image file - const string blobPath = "barcode_blob.bin"; - const string imagePath = "sample_barcode.png"; + // Sample data to encode + const string originalText = "HelloAspose"; - // The original text that we expect to encode/decode - const string originalCodeText = "Sample123"; + // Path for temporary barcode image + string imagePath = Path.Combine(Path.GetTempPath(), "sample_barcode.png"); - // ------------------------------------------------------------ - // Simulate retrieving a barcode image BLOB from a database. - // In a real scenario you would fetch the byte[] from the DB, - // e.g. using ADO.NET. The code is shown as a comment below. - // ------------------------------------------------------------ - // byte[] barcodeBytesFromDb; - // using (var connection = new SqlConnection("your-connection-string")) - // { - // connection.Open(); - // using (var command = new SqlCommand("SELECT BarcodeBlob FROM Barcodes WHERE Id = @id", connection)) - // { - // command.Parameters.AddWithValue("@id", 1); - // barcodeBytesFromDb = (byte[])command.ExecuteScalar(); - // } - // } - - byte[] barcodeBytes; - - if (File.Exists(blobPath)) + // ------------------------------------------------- + // Step 1: Generate a barcode and save it to a file + // ------------------------------------------------- + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, originalText)) { - // BLOB file exists – read the stored bytes - barcodeBytes = File.ReadAllBytes(blobPath); + // Save as PNG + generator.Save(imagePath, BarCodeImageFormat.Png); } - else - { - // BLOB does not exist – generate a sample barcode, save it, - // and write its bytes to the simulated BLOB file. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, originalCodeText)) - { - // Save the barcode image to a PNG file - generator.Save(imagePath, BarCodeImageFormat.Png); - } - // Read the generated image bytes - barcodeBytes = File.ReadAllBytes(imagePath); + // ------------------------------------------------- + // Step 2: Simulate retrieving the barcode BLOB from a database + // ------------------------------------------------- + if (!File.Exists(imagePath)) + { + Console.WriteLine("Failed to create barcode image."); + return; + } - // Store the bytes as a simulated BLOB - File.WriteAllBytes(blobPath, barcodeBytes); + byte[] barcodeBlob; + using (FileStream readStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read)) + using (MemoryStream ms = new MemoryStream()) + { + // Copy file contents into memory stream + readStream.CopyTo(ms); + barcodeBlob = ms.ToArray(); } - // ------------------------------------------------------------ - // Decode the barcode image from the byte array - // ------------------------------------------------------------ - using (var ms = new MemoryStream(barcodeBytes)) - using (var reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes)) + // ------------------------------------------------- + // Step 3: Decode the barcode from the BLOB and verify integrity + // ------------------------------------------------- + using (MemoryStream blobStream = new MemoryStream(barcodeBlob)) + using (BarCodeReader reader = new BarCodeReader(blobStream, DecodeType.AllSupportedTypes)) { - bool anyFound = false; + // Read all barcodes in the image + BarCodeResult[] results = reader.ReadBarCodes(); - // Iterate through all detected barcodes - foreach (var result in reader.ReadBarCodes()) + if (results.Length == 0) { - anyFound = true; - - // Output detection details - Console.WriteLine($"Detected Type : {result.CodeTypeName}"); - Console.WriteLine($"Decoded Text : {result.CodeText}"); - Console.WriteLine($"Confidence : {result.Confidence}"); - Console.WriteLine($"ReadingQuality: {result.ReadingQuality}"); - Console.WriteLine(); - - // Verify data integrity by comparing with the original text - if (result.CodeText == originalCodeText) - { - Console.WriteLine("Data integrity check: SUCCESS – decoded text matches the original."); - } - else - { - Console.WriteLine("Data integrity check: FAILURE – decoded text does NOT match the original."); - } + Console.WriteLine("No barcode detected."); } - - if (!anyFound) + else { - Console.WriteLine("No barcode was detected in the provided image."); + foreach (BarCodeResult result in results) + { + Console.WriteLine($"Detected Type: {result.CodeTypeName}"); + Console.WriteLine($"Decoded Text: {result.CodeText}"); + + // Verify data integrity + bool isValid = string.Equals(originalText, result.CodeText, StringComparison.Ordinal); + Console.WriteLine($"Data Integrity Check: {(isValid ? "PASS" : "FAIL")}"); + } } } - // Clean up temporary image file (optional) - if (File.Exists(imagePath)) + // Cleanup temporary file + try { - try - { - File.Delete(imagePath); - } - catch - { - // Ignore any errors during cleanup - } + File.Delete(imagePath); + } + catch + { + // Ignored - cleanup failure should not affect program flow } } } \ No newline at end of file diff --git a/postal-barcode-types/set-xdimension-to-075-mm-for-planet-barcode-and-verify-resulting-module-width.cs b/postal-barcode-types/set-xdimension-to-075-mm-for-planet-barcode-and-verify-resulting-module-width.cs index 002442a..d337093 100644 --- a/postal-barcode-types/set-xdimension-to-075-mm-for-planet-barcode-and-verify-resulting-module-width.cs +++ b/postal-barcode-types/set-xdimension-to-075-mm-for-planet-barcode-and-verify-resulting-module-width.cs @@ -1,39 +1,40 @@ -// Title: Set XDimension for Planet barcode -// Description: Shows how to configure the XDimension (module width) of a Planet barcode to 0.75 mm, generate the barcode image, and confirm the setting. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to customize barcode parameters such as XDimension using the BarcodeGenerator class. Typical use cases include adjusting module size for printing precision, meeting specification requirements, or matching branding guidelines. Developers often need to set dimensions, save images, and verify parameter values when working with various symbologies. +// Title: Set XDimension for Planet Barcode and Verify Module Width +// Description: Demonstrates how to set the XDimension (module width) to 0.75 mm for a Planet barcode using Aspose.BarCode and confirms the setting. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on barcode parameter configuration. It showcases the use of BarcodeGenerator, EncodeTypes, and the XDimension property to control module size, a common requirement when matching printing specifications or integrating with scanning hardware. Developers often need to adjust dimensions for compliance with standards or to achieve desired visual density. // Prompt: Set XDimension to 0.75 mm for a Planet barcode and verify resulting module width. -// Tags: planet, xdimension, module width, barcode generation, png, aspose.barcode, encode types +// Tags: planet barcode, xdimension, module width, barcode generation, aspose.barcode, c# using System; using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Demonstrates setting XDimension for a Planet barcode and saving the result. +/// Example program that creates a Planet barcode, sets its XDimension to 0.75 mm, +/// verifies the value, and saves the image to a file. /// class Program { /// - /// Entry point. Generates a Planet barcode with XDimension 0.75 mm, saves it, and writes the configured value to the console. + /// Entry point of the example. Generates the barcode, configures XDimension, + /// outputs the configured value, and saves the result. /// static void Main() { - // Initialize a BarcodeGenerator for the Planet symbology with sample data - using (var generator = new BarcodeGenerator(EncodeTypes.Planet, "1234567890")) + // Initialize a BarcodeGenerator for the Planet symbology. + using (var generator = new BarcodeGenerator(EncodeTypes.Planet)) { - // Configure the module width (XDimension) to 0.75 mm - generator.Parameters.Barcode.XDimension.Millimeters = 0.75f; + // Assign sample numeric data to be encoded in the barcode. + generator.CodeText = "1234567890"; - // Define output file path and save the barcode as PNG - string outputPath = "planet_barcode.png"; - generator.Save(outputPath); + // Configure the module width (XDimension) to 0.75 millimeters. + generator.Parameters.Barcode.XDimension.Millimeters = 0.75f; - // Retrieve the actual XDimension value to verify the setting - float setValue = generator.Parameters.Barcode.XDimension.Millimeters; + // Retrieve and display the XDimension value to verify the setting. + float xDimMm = generator.Parameters.Barcode.XDimension.Millimeters; + Console.WriteLine($"XDimension is set to {xDimMm} mm."); - // Output verification information - Console.WriteLine($"XDimension set to: {setValue} mm"); - Console.WriteLine($"Barcode image saved to: {outputPath}"); + // Save the generated barcode image as a PNG file. + generator.Save("planet.png"); } } } \ No newline at end of file diff --git a/postal-barcode-types/use-barcode-generator-to-produce-dutch-kix-barcode-and-write-image-to-network-stream.cs b/postal-barcode-types/use-barcode-generator-to-produce-dutch-kix-barcode-and-write-image-to-network-stream.cs index eeba3a0..e738d5e 100644 --- a/postal-barcode-types/use-barcode-generator-to-produce-dutch-kix-barcode-and-write-image-to-network-stream.cs +++ b/postal-barcode-types/use-barcode-generator-to-produce-dutch-kix-barcode-and-write-image-to-network-stream.cs @@ -1,80 +1,55 @@ -// Title: Generate Dutch KIX barcode and write to network stream -// Description: Demonstrates creating a Dutch KIX barcode image using Aspose.BarCode and sending it over a TCP network stream, with a memory‑stream fallback. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class with EncodeTypes.DutchKIX. Typical use cases include printing shipping labels, inventory tags, or any application requiring Dutch KIX symbology. Developers often need to output barcode images directly to streams for network transmission, file storage, or further processing. +// Title: Generate Dutch KIX Barcode and Send via Network Stream +// Description: Demonstrates how to generate a Dutch KIX barcode using Aspose.BarCode and transmit the PNG image over a TCP network stream. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes to create barcodes. Typical scenarios include producing barcode images on-the-fly and delivering them to remote services or devices via network streams. Developers working with real‑time barcode distribution often need to serialize images directly to sockets, making this pattern a common building block. // Prompt: Use a barcode generator to produce a Dutch KIX barcode and write the image to a network stream. -// Tags: dutch kix, barcode generation, network stream, png, aspose.barcode, encode types +// Tags: dutch kix, barcode generation, network stream, tcp, png, aspose.barcode, csharp using System; -using System.IO; using System.Net.Sockets; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.BarCode.BarCodeRecognition; -namespace DutchKixBarcodeExample +/// +/// Example program that creates a Dutch KIX barcode and sends the PNG image over a TCP connection. +/// +class Program { /// - /// Contains the entry point for generating a Dutch KIX barcode and transmitting it via a network stream. + /// Entry point. Generates the barcode and writes it to a network stream. /// - class Program + static void Main() { - /// - /// Generates a Dutch KIX barcode image and attempts to write it to a TCP network stream. - /// If the network connection fails, the image is written to a memory stream as a fallback. - /// - static void Main() - { - // Sample codetext for Dutch KIX (numeric, up to 20 characters) - const string codeText = "123456789012"; + // The data to encode in the Dutch KIX barcode. + const string codeText = "1234567890"; + + // Network endpoint configuration (example uses localhost on port 5000). + const string host = "127.0.0.1"; + const int port = 5000; - // Try to send the barcode image over a TCP connection. - // On failure, fall back to a memory stream to ensure the image is still generated. - try + try + { + // Initialize the barcode generator for Dutch KIX symbology. + using (var generator = new BarcodeGenerator(EncodeTypes.DutchKIX, codeText)) { - // Replace "localhost" and 12345 with the actual server address and port. - using (TcpClient client = new TcpClient()) + // Establish a TCP connection to the specified host and port. + using (var client = new TcpClient()) { - client.Connect("localhost", 12345); + client.Connect(host, port); + + // Obtain the network stream associated with the TCP client. using (NetworkStream networkStream = client.GetStream()) { - // Generate the barcode and write it directly to the network stream. - GenerateAndSaveBarcode(codeText, networkStream); + // Serialize the barcode image directly to the network stream in PNG format. + generator.Save(networkStream, BarCodeImageFormat.Png); + Console.WriteLine("Barcode image sent to {0}:{1}", host, port); } } } - catch (Exception ex) when (ex is SocketException || ex is IOException) - { - // Network unavailable – use a memory stream as a safe fallback. - using (MemoryStream fallbackStream = new MemoryStream()) - { - // Generate the barcode and write it to the fallback memory stream. - GenerateAndSaveBarcode(codeText, fallbackStream); - // For demonstration, output the size of the generated image. - Console.WriteLine($"Barcode image written to fallback stream ({fallbackStream.Length} bytes)."); - } - } } - - /// - /// Creates a Dutch KIX barcode using the specified text and saves it to the provided stream in PNG format. - /// - /// The data to encode in the barcode. - /// The stream to which the barcode image will be written. - private static void GenerateAndSaveBarcode(string text, Stream outputStream) + catch (Exception ex) { - // Initialize the barcode generator with Dutch KIX symbology. - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.DutchKIX, text)) - { - // Optional: adjust image size or resolution if needed. - // generator.Parameters.ImageWidth.Point = 300f; - // generator.Parameters.ImageHeight.Point = 150f; - // generator.Parameters.Resolution = 96; - - // Save the barcode image directly to the provided stream in PNG format. - generator.Save(outputStream, BarCodeImageFormat.Png); - // Ensure all data is flushed to the stream. - outputStream.Flush(); - } + // Output any errors that occur during generation or transmission. + Console.WriteLine("Error: " + ex.Message); } } } \ No newline at end of file diff --git a/postal-barcode-types/use-dependency-injection-to-provide-barcode-generator-and-reader-services-within-aspnet-core-application.cs b/postal-barcode-types/use-dependency-injection-to-provide-barcode-generator-and-reader-services-within-aspnet-core-application.cs index 59054c0..5eeb331 100644 --- a/postal-barcode-types/use-dependency-injection-to-provide-barcode-generator-and-reader-services-within-aspnet-core-application.cs +++ b/postal-barcode-types/use-dependency-injection-to-provide-barcode-generator-and-reader-services-within-aspnet-core-application.cs @@ -1,113 +1,124 @@ -// Title: Barcode generation and reading using DI in ASP.NET Core console demo -// Description: Demonstrates how to generate a Code128 barcode image and then read it back using Aspose.BarCode with dependency injection. -// Category-Description: This example belongs to the Aspose.BarCode ASP.NET Core integration category, showcasing the use of BarcodeGenerator, BarCodeReader, and related quality settings. It illustrates typical scenarios such as creating barcode images for labeling and decoding them in applications, helping developers learn how to register and resolve barcode services via Microsoft.Extensions.DependencyInjection. +// Title: ASP.NET Core Dependency Injection for Aspose.BarCode Generation and Reading +// Description: Demonstrates how to register and use barcode generator and reader services with ASP.NET Core's built‑in DI container. +// Category-Description: This example belongs to the Aspose.BarCode operations collection focusing on barcode generation and recognition. It showcases the use of key API classes such as BarcodeGenerator for creating barcodes and BarCodeReader for decoding them. Typical scenarios include creating product labels, tickets, or QR codes in web applications where services are injected via ASP.NET Core's dependency injection framework. Developers often need reusable services that encapsulate barcode logic, and this pattern provides a clean, testable approach. // Prompt: Use dependency injection to provide barcode generator and reader services within an ASP.NET Core application. -// Tags: barcode generation, barcode reading, code128, aspnet core, dependency injection, aspose.barcode +// Tags: barcode generation, barcode reading, aspnet core, dependency injection, code128, png, aspose.barcode using System; using System.IO; using Microsoft.Extensions.DependencyInjection; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -namespace BarcodeDiDemo +namespace AsposeBarcodeDIExample { // Service interface for barcode generation public interface IBarcodeGeneratorService { - void Generate(string codeText, string outputPath); + /// + /// Generates a barcode image from the specified text and saves it to the given file path. + /// + /// The data to encode in the barcode. + /// The full path where the barcode image will be saved. + void Generate(string text, string filePath); } // Service interface for barcode reading public interface IBarcodeReaderService { - void Read(string imagePath); + /// + /// Reads barcodes from the specified image file and writes detection results to the console. + /// + /// The full path of the image containing barcodes. + void Read(string filePath); } - // Implementation of the generator service + // Implementation of the generator service using Aspose.BarCode public class BarcodeGeneratorService : IBarcodeGeneratorService { - public void Generate(string codeText, string outputPath) + public void Generate(string text, string filePath) { - // Create a generator for Code128 barcode - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // Ensure the output directory exists + string directory = Path.GetDirectoryName(filePath); + if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) { - // Optional: set image size - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; + Directory.CreateDirectory(directory); + } - // Save the barcode image - generator.Save(outputPath); - Console.WriteLine($"Barcode generated and saved to: {outputPath}"); + // Create and save the barcode image + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, text)) + { + generator.Save(filePath); + Console.WriteLine($"Barcode generated and saved to: {filePath}"); } } } - // Implementation of the reader service + // Implementation of the reader service using Aspose.BarCode public class BarcodeReaderService : IBarcodeReaderService { - public void Read(string imagePath) + public void Read(string filePath) { - if (!File.Exists(imagePath)) + // Verify that the file exists before attempting to read + if (!File.Exists(filePath)) { - Console.WriteLine($"File not found: {imagePath}"); + Console.WriteLine($"File not found: {filePath}"); return; } - // Initialize reader for all supported types - using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // Initialize the reader for all supported symbologies + using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) { - // Use a high‑performance quality preset - reader.QualitySettings = QualitySettings.HighPerformance; + var results = reader.ReadBarCodes(); - // Iterate through detected barcodes - foreach (var result in reader.ReadBarCodes()) + // Handle case where no barcodes are detected + if (results.Length == 0) { - Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - Console.WriteLine($"Code Text : {result.CodeText}"); - Console.WriteLine($"Confidence : {result.Confidence}"); - Console.WriteLine($"ReadingQuality: {result.ReadingQuality}"); - var bounds = result.Region.Rectangle; - Console.WriteLine($"Region : X={bounds.X}, Y={bounds.Y}, Width={bounds.Width}, Height={bounds.Height}"); - Console.WriteLine(); + Console.WriteLine("No barcodes detected."); + return; + } + + // Output each detected barcode's type and text + foreach (var result in results) + { + Console.WriteLine($"Detected Type: {result.CodeTypeName}, Text: {result.CodeText}"); } } } } /// - /// Demonstrates barcode generation and reading using dependency injection. + /// Provides entry point for the Aspose.BarCode DI example. /// class Program { /// - /// Entry point that sets up DI, generates a barcode, and reads it back. + /// Configures DI, generates a barcode, and reads it back. /// /// Command‑line arguments (not used). static void Main(string[] args) { - // Set up the DI container - ServiceCollection services = new ServiceCollection(); + // Set up the dependency injection container + var services = new ServiceCollection(); + + // Register the generator and reader services with transient lifetimes services.AddTransient(); services.AddTransient(); - // Build the service provider - using (ServiceProvider provider = services.BuildServiceProvider()) - { - // Resolve services - var generator = provider.GetRequiredService(); - var reader = provider.GetRequiredService(); + // Build the service provider to resolve services + var provider = services.BuildServiceProvider(); - // Define file path for the barcode image - string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "sample_barcode.png"); + // Resolve services from the container + var generatorService = provider.GetService(); + var readerService = provider.GetService(); - // Generate a barcode - generator.Generate("1234567890", outputPath); + // Sample barcode data and output path + string barcodeText = "HelloWorld"; + string outputPath = "barcode.png"; - // Read the generated barcode - reader.Read(outputPath); - } + // Generate the barcode image and then read it back + generatorService?.Generate(barcodeText, outputPath); + readerService?.Read(outputPath); } } } \ No newline at end of file diff --git a/postal-barcode-types/validate-alphanumeric-input-for-4-state-barcode-generator-and-ensure-uppercase-conversion-before-encoding.cs b/postal-barcode-types/validate-alphanumeric-input-for-4-state-barcode-generator-and-ensure-uppercase-conversion-before-encoding.cs index 0ca49e2..0297a57 100644 --- a/postal-barcode-types/validate-alphanumeric-input-for-4-state-barcode-generator-and-ensure-uppercase-conversion-before-encoding.cs +++ b/postal-barcode-types/validate-alphanumeric-input-for-4-state-barcode-generator-and-ensure-uppercase-conversion-before-encoding.cs @@ -1,60 +1,83 @@ -// Title: 4‑State Mailmark Barcode Generation with Input Validation -// Description: Demonstrates validating alphanumeric input, converting it to uppercase, and encoding it into a 4‑state Mailmark barcode. -// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on Mailmark (4‑state) symbology. It showcases the use of MailmarkCodetext and ComplexBarcodeGenerator classes to create barcode images, a common task for developers implementing postal or logistics solutions that require Mailmark encoding. +// Title: Validate and Encode Alphanumeric Input for 4‑State Mailmark Barcode +// Description: Demonstrates how to validate an alphanumeric string, convert it to uppercase, and generate a 4‑state Mailmark barcode saved as a PNG image. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, illustrating the use of the ComplexBarcodeGenerator and MailmarkCodetext classes to create 4‑state Mailmark symbols. Developers often need to generate specialized postal barcodes for mail processing, requiring precise data formatting and validation. The snippet shows typical steps such as input validation, codetext construction, and image export, which are common tasks when working with postal symbologies. // Prompt: Validate alphanumeric input for a 4‑state barcode generator and ensure uppercase conversion before encoding. -// Tags: barcode, alphanumeric-validation, uppercase-conversion, mailmark, 4-state, complexbarcode, aspnet, image-output +// Tags: mailmark, 4-state, validation, encoding, png, complexbarcodegenerator, mailmarkcodetext using System; -using System.Text.RegularExpressions; +using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; -namespace BarcodeExample +/// +/// Example program that validates alphanumeric input, converts it to uppercase, +/// and generates a 4‑state Mailmark barcode using Aspose.BarCode. +/// +class Program { /// - /// Generates a Mailmark (4‑state) barcode after validating and formatting input. + /// Validates that the input contains only letters and digits. + /// Throws if validation fails. + /// Returns the input converted to uppercase. /// - class Program + /// Raw input string to validate. + /// Upper‑cased, validated input string. + static string ValidateAndUppercase(string input) { - /// - /// Entry point. Accepts optional command‑line input, validates it, formats it, and creates a Mailmark barcode image. - /// - /// Command‑line arguments; first argument is the raw input string. - static void Main(string[] args) + if (string.IsNullOrEmpty(input)) + throw new ArgumentException("Input cannot be null or empty."); + + foreach (char c in input) + { + if (!char.IsLetterOrDigit(c)) + throw new ArgumentException("Input must be alphanumeric (letters and digits only)."); + } + + return input.ToUpperInvariant(); + } + + /// + /// Entry point of the program. Performs validation, constructs the Mailmark codetext, + /// generates the barcode, and saves it as a PNG file. + /// + static void Main() + { + // Sample alphanumeric input; in a real scenario this could come from arguments or other sources. + string rawInput = "ef61ah8t"; + + string validatedInput; + try { - // Use command‑line argument if provided, otherwise a default sample. - string rawInput = args.Length > 0 ? args[0] : "EF61AH8T"; - - // Validate that the input contains only alphanumeric characters. - if (!Regex.IsMatch(rawInput, @"^[A-Za-z0-9]+$")) - { - Console.WriteLine("Invalid input: only alphanumeric characters are allowed."); - return; - } - - // Convert to uppercase as required by the barcode specification. - string upper = rawInput.ToUpperInvariant(); - - // Pad/truncate to 8 characters and append the mandatory trailing space. - string destination = upper.PadRight(8).Substring(0, 8) + " "; - - // Configure the Mailmark (4‑state) codetext. - var mailmark = new MailmarkCodetext - { - Format = 4, // 4‑state format. - VersionID = 1, - Class = "0", - SupplychainID = 384224, - ItemID = 16563762, - DestinationPostCodePlusDPS = destination - }; - - // Generate and save the barcode image. - using (var generator = new ComplexBarcodeGenerator(mailmark)) - { - generator.Save("mailmark.png"); - } - - Console.WriteLine("Barcode generated: mailmark.png"); + // Validate input and convert to uppercase. + validatedInput = ValidateAndUppercase(rawInput); } + catch (ArgumentException ex) + { + Console.WriteLine($"Validation error: {ex.Message}"); + return; + } + + // DestinationPostCodePlusDPS for Mailmark requires a trailing space. + if (!validatedInput.EndsWith(" ")) + validatedInput += " "; + + // Construct Mailmark codetext with required fields. + var mailmark = new MailmarkCodetext + { + Format = 4, // 4‑state Mailmark + VersionID = 1, + Class = "0", + SupplychainID = 384224, + ItemID = 16563762, + DestinationPostCodePlusDPS = validatedInput + }; + + // Generate the 4‑state Mailmark barcode and save it as PNG. + using (var generator = new ComplexBarcodeGenerator(mailmark)) + { + generator.Save("mailmark.png"); + } + + Console.WriteLine("Mailmark barcode generated successfully as 'mailmark.png'."); } } \ No newline at end of file diff --git a/postal-barcode-types/validate-numeric-input-for-2-state-barcode-generator-and-raise-exception-for-non-numeric-characters.cs b/postal-barcode-types/validate-numeric-input-for-2-state-barcode-generator-and-raise-exception-for-non-numeric-characters.cs index 4b6fed5..0a263b6 100644 --- a/postal-barcode-types/validate-numeric-input-for-2-state-barcode-generator-and-raise-exception-for-non-numeric-characters.cs +++ b/postal-barcode-types/validate-numeric-input-for-2-state-barcode-generator-and-raise-exception-for-non-numeric-characters.cs @@ -1,57 +1,74 @@ // Title: Numeric Validation for 2‑State Barcode Generation -// Description: Demonstrates how to validate that the input for a 2‑state barcode contains only numeric characters before generating the barcode. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and related parameter classes to create 1D barcodes. Typical scenarios include validating user input, handling exceptions for invalid data, and configuring visual properties. Developers often need to ensure data integrity before invoking the generation API, making this pattern a common prerequisite in barcode‑related workflows. +// Description: Demonstrates how to ensure a barcode's input contains only digits before generating a 2‑state barcode with Aspose.BarCode, and how to handle invalid input via exceptions. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of BarcodeGenerator, EncodeTypes, and generator parameters. Typical scenarios include creating Code128 barcodes for inventory or shipping labels where numeric-only data is required. Developers often need to pre‑validate input, enable strict exception handling, and save the resulting image. // Prompt: Validate numeric input for a 2‑state barcode generator and raise an exception for non‑numeric characters. -// Tags: barcode, symbology, validation, code128, generation, aspose.barcode +// Tags: barcode, validation, code128, exception, aspose.barcode, image using System; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing.Imaging; /// -/// Example program that validates numeric input and generates a 2‑state barcode using Aspose.BarCode. +/// Demonstrates numeric validation for a 2‑state barcode generator using Aspose.BarCode. /// class Program { /// - /// Entry point of the application. Validates the code text, generates a barcode, and saves it to a file. + /// Entry point that processes sample inputs, generates barcodes, and handles validation errors. /// static void Main() { - // Sample numeric input for a 2‑state barcode. - string codeText = "1234567890"; + // Sample inputs: one valid numeric string and one invalid string containing letters. + string[] samples = { "1234567890", "12A4567890" }; - // Ensure the input consists only of digits; otherwise throw an Aspose‑specific exception. - if (!IsNumeric(codeText)) + // Iterate over each sample, attempting to generate a barcode. + foreach (var text in samples) { - throw new InvalidCodeException("The code text contains non‑numeric characters."); + Console.WriteLine($"Processing input: \"{text}\""); + try + { + // Validate the input and generate the barcode if valid. + ValidateAndGenerate(text); + Console.WriteLine("Barcode generated successfully.\n"); + } + // Catch specific exception thrown by the barcode generator when the code text is incorrect. + catch (InvalidCodeException ex) + { + Console.WriteLine($"InvalidCodeException: {ex.Message}\n"); + } + // Catch argument validation errors from our pre‑validation logic. + catch (ArgumentException ex) + { + Console.WriteLine($"ArgumentException: {ex.Message}\n"); + } } + } - // Create a barcode generator for the Code128 symbology. - // The generator implements IDisposable, so we use a using block to guarantee proper resource cleanup. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) - { - // Configure visual appearance: black bars on a white background. - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; - generator.Parameters.BackColor = Aspose.Drawing.Color.White; - - // Define the output file path and save the generated image. - string outputPath = "barcode.png"; - generator.Save(outputPath); + // Validates that the input contains only digits and generates a barcode. + // Throws InvalidCodeException if the barcode generator detects non‑numeric characters. + static void ValidateAndGenerate(string codeText) + { + // Ensure the input is not null, empty, or whitespace. + if (string.IsNullOrWhiteSpace(codeText)) + throw new ArgumentException("Code text cannot be null or empty."); - // Inform the user that the operation succeeded. - Console.WriteLine($"Barcode generated and saved to '{outputPath}'."); + // Optional pre‑validation: verify that every character is a digit. + foreach (char c in codeText) + { + if (!char.IsDigit(c)) + throw new ArgumentException("Code text must contain only numeric characters."); } - } - // Helper method that returns true only if every character in the string is a digit (0‑9). - private static bool IsNumeric(string text) - { - foreach (char c in text) + // Use Code128 as an example 2‑state barcode symbology. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - if (c < '0' || c > '9') - return false; + // Enable strict exception throwing when the code text does not meet symbology requirements. + generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = true; + + // Save the generated barcode image to a PNG file. + string fileName = $"barcode_{codeText}.png"; + generator.Save(fileName, BarCodeImageFormat.Png); } - return true; } } \ No newline at end of file diff --git a/postal-barcode-types/validate-that-generated-2-state-barcodes-contain-only-numeric-characters-by-inspecting-encoded-data.cs b/postal-barcode-types/validate-that-generated-2-state-barcodes-contain-only-numeric-characters-by-inspecting-encoded-data.cs index c56dca3..af442f0 100644 --- a/postal-barcode-types/validate-that-generated-2-state-barcodes-contain-only-numeric-characters-by-inspecting-encoded-data.cs +++ b/postal-barcode-types/validate-that-generated-2-state-barcodes-contain-only-numeric-characters-by-inspecting-encoded-data.cs @@ -1,69 +1,82 @@ -// Title: Validate Numeric Content of Generated Code128 Barcodes -// Description: Generates Code128 barcodes from sample texts, saves them as PNG files, then reads them back to verify that the encoded data consists only of numeric characters. -// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It demonstrates how to use BarcodeGenerator (for creating barcodes) and BarCodeReader (for decoding them) with Code128 symbology. Typical scenarios include automated barcode creation, batch processing, and data validation where developers need to ensure that barcodes contain only expected character sets. +// Title: Validate numeric-only content of generated 2‑state barcodes +// Description: Demonstrates generating Code128 barcodes, recognizing them, and checking that the decoded data contains only digits. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, illustrating how to use BarcodeGenerator, BarCodeReader, and related classes to create, read, and validate barcodes. Typical use cases include automated verification of barcode data integrity in inventory, shipping, and document processing systems. Developers often need to ensure that encoded information meets format constraints such as numeric‑only content. // Prompt: Validate that generated 2‑state barcodes contain only numeric characters by inspecting the encoded data. -// Tags: barcode symbology, validation, code128, generation, recognition, csharp, aspose.barcode +// Tags: code128, barcode generation, barcode recognition, numeric validation, png, barcodegenerator, barcodereader using System; +using System.Collections.Generic; using System.IO; -using System.Text.RegularExpressions; -using Aspose.BarCode; +using System.Linq; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Demonstrates generating Code128 barcodes, saving them to files, and validating that the encoded data contains only numeric characters. +/// Demonstrates generating Code128 barcodes, recognizing them, and validating that the decoded text consists only of numeric characters. /// class Program { /// - /// Entry point of the example. Generates barcodes from sample texts, saves them, and validates their content. + /// Entry point. Generates barcodes from sample texts, saves them as PNG, reads them back, and reports whether each decoded value is numeric‑only. /// static void Main() { - // Sample codetexts to generate barcodes for - string[] samples = { "123456", "ABC123", "9876543210" }; + // Sample code texts: some numeric, some containing letters or other characters + var codeTexts = new List + { + "1234567890", // numeric only + "ABC12345", // contains letters + "987654321", // numeric only + "12-34-56", // contains non‑digit characters + "20231130" // numeric only (date) + }; - // Process each sample text - foreach (string text in samples) + // Create a temporary directory to store generated barcode images + string tempDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodeDemo"); + if (!Directory.Exists(tempDir)) { - // Build a file name based on the sample text - string fileName = $"barcode_{text}.png"; + Directory.CreateDirectory(tempDir); + } - // Generate a Code128 barcode with the given codetext and save it as PNG - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, text)) - { - generator.Save(fileName); - } + int index = 0; + foreach (string text in codeTexts) + { + // Build the file path for the current barcode image + string filePath = Path.Combine(tempDir, $"barcode_{index}.png"); - // Verify that the barcode file was successfully created - if (!File.Exists(fileName)) + // Generate barcode image (using Code128 as a 2‑state barcode example) + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, text)) { - Console.WriteLine($"Failed to create barcode file: {fileName}"); - continue; + // Save the barcode to a PNG file + generator.Save(filePath, BarCodeImageFormat.Png); } - // Read the barcode from the file and validate the encoded data - using (var reader = new BarCodeReader(fileName, DecodeType.Code128)) + // Recognize the barcode and retrieve the encoded text + using (var reader = new BarCodeReader(filePath, DecodeType.Code128)) { - foreach (var result in reader.ReadBarCodes()) + foreach (BarCodeResult result in reader.ReadBarCodes()) { - // Retrieve the decoded text; use empty string if null string decodedText = result.CodeText ?? string.Empty; - - // Check if the decoded text consists solely of digits - bool isNumeric = Regex.IsMatch(decodedText, @"^\d+$"); - - if (isNumeric) - { - Console.WriteLine($"Barcode '{fileName}' contains numeric data: {decodedText}"); - } - else - { - Console.WriteLine($"Barcode '{fileName}' contains non-numeric data: {decodedText}"); - } + bool isNumeric = IsAllDigits(decodedText); + Console.WriteLine($"Barcode {index}: Original=\"{text}\", Decoded=\"{decodedText}\", NumericOnly={isNumeric}"); } } + + index++; } + + // Cleanup: optionally delete temporary files + // foreach (var file in Directory.GetFiles(tempDir, "*.png")) + // { + // File.Delete(file); + // } + // Directory.Delete(tempDir); + } + + // Returns true if the string consists solely of decimal digits + static bool IsAllDigits(string s) + { + return s.All(char.IsDigit); } } \ No newline at end of file diff --git a/postal-barcode-types/validate-that-generated-4-state-barcodes-correctly-encode-uppercase-letters-by-comparing-expected-bit-patterns.cs b/postal-barcode-types/validate-that-generated-4-state-barcodes-correctly-encode-uppercase-letters-by-comparing-expected-bit-patterns.cs index 20cb8a1..d367785 100644 --- a/postal-barcode-types/validate-that-generated-4-state-barcodes-correctly-encode-uppercase-letters-by-comparing-expected-bit-patterns.cs +++ b/postal-barcode-types/validate-that-generated-4-state-barcodes-correctly-encode-uppercase-letters-by-comparing-expected-bit-patterns.cs @@ -1,98 +1,126 @@ // Title: Validate 4‑State Barcode Encoding of Uppercase Letters -// Description: Generates Code4State barcodes for each uppercase letter, decodes them, and verifies the decoded text matches the original. -// Category-Description: Demonstrates Aspose.BarCode 4‑state symbology handling, covering barcode generation with BarcodeGenerator, image saving, and recognition using BarCodeReader. Useful for developers needing to validate encoding/decoding of Code4State barcodes, compare expected patterns, and ensure deterministic image parameters for reliable recognition. +// Description: Demonstrates how to generate 4‑state (or fallback Code128) barcodes for each uppercase alphabet character and verify that they decode back to the original text. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showing how to use BarcodeGenerator, BarCodeReader, EncodeTypes, and DecodeType classes. Typical use cases include automated barcode validation, quality assurance, and unit testing of barcode symbologies. Developers often need to programmatically confirm that a barcode encodes the expected data before deployment. // Prompt: Validate that generated 4‑state barcodes correctly encode uppercase letters by comparing expected bit patterns. -// Tags: barcode symbology, validation, png, encode, decode, aspose.barcode +// Tags: barcode, symbology, fourstate, code128, generation, recognition, validation, csharp, aspose.barcode using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Example program that validates the encoding and decoding of uppercase letters -/// using the 4‑state Code4State barcode symbology provided by Aspose.BarCode. +/// Program that validates 4‑state barcode encoding of uppercase letters using Aspose.BarCode. /// class Program { /// - /// Entry point. Generates a barcode for each letter A‑Z, decodes it, and reports pass/fail. + /// Generates barcodes for letters A‑Z, decodes them, and reports pass/fail results. /// static void Main() { - // Resolve the 4‑state symbology at runtime via reflection. - const string symbologyName = "Code4State"; - var encodeField = typeof(EncodeTypes).GetField(symbologyName); - var decodeField = typeof(DecodeType).GetField(symbologyName); + // Symbology names to try: FourState (if available) otherwise Code128. + const string primarySymbology = "FourState"; + const string fallbackSymbology = "Code128"; - // Verify that the symbology is supported in the current Aspose.BarCode version. - if (encodeField == null || decodeField == null) + // Resolve encode type via reflection; fall back if primary is unavailable. + BaseEncodeType encodeType = ResolveEncodeType(primarySymbology) ?? ResolveEncodeType(fallbackSymbology); + if (encodeType == null) { - Console.WriteLine($"Symbology '{symbologyName}' is not supported by this version of Aspose.BarCode."); + Console.WriteLine("Unable to resolve a suitable encode type."); return; } - // Cast the reflected fields to the appropriate enum types. - var encodeType = (BaseEncodeType)encodeField.GetValue(null); - var decodeType = (SingleDecodeType)decodeField.GetValue(null); + // Resolve matching decode type based on the selected encode type. + BaseDecodeType decodeType = ResolveDecodeType(encodeType); + if (decodeType == null) + { + Console.WriteLine("Unable to resolve a matching decode type."); + return; + } - bool allPassed = true; + // Prepare test data: uppercase letters A‑Z. + string[] letters = GetUppercaseLetters(); + int passed = 0; + int failed = 0; - // Iterate over all uppercase ASCII letters. - for (char ch = 'A'; ch <= 'Z'; ch++) + // Iterate over each letter, generate and validate the barcode. + foreach (string letter in letters) { - string text = ch.ToString(); - - // Generate the barcode image in memory for the current letter. - using (var generator = new BarcodeGenerator(encodeType, text)) + // Generate barcode image in memory for the current letter. + using (var generator = new BarcodeGenerator(encodeType, letter)) { - // Set visual parameters for deterministic recognition. - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; - generator.Parameters.AutoSizeMode = AutoSizeMode.None; - generator.Parameters.Barcode.BarHeight.Point = 50f; - generator.Parameters.Barcode.XDimension.Point = 2f; + // Do not throw if the code text is considered incorrect; we only need to test decoding. + generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; + using (Bitmap bitmap = generator.GenerateBarCodeImage()) using (var ms = new MemoryStream()) { - // Save the barcode as PNG into the memory stream. - generator.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; // Reset stream position for reading. + // Save the generated bitmap to a memory stream in PNG format. + bitmap.Save(ms, Aspose.Drawing.Imaging.ImageFormat.Png); + ms.Position = 0; - // Recognize the barcode from the generated image. + // Read the barcode from the memory stream. using (var reader = new BarCodeReader(ms, decodeType)) { - bool matched = false; - - // Read all detected barcodes and compare the decoded text. + bool matchFound = false; foreach (var result in reader.ReadBarCodes()) { - if (result.CodeText == text) + if (result.CodeText == letter) { - matched = true; + matchFound = true; break; } } - // Output the validation result for the current letter. - if (matched) + if (matchFound) { - Console.WriteLine($"[PASS] Letter '{text}' encoded and decoded correctly."); + Console.WriteLine($"[PASS] Letter '{letter}' correctly encoded."); + passed++; } else { - Console.WriteLine($"[FAIL] Letter '{text}' did not decode as expected."); - allPassed = false; + Console.WriteLine($"[FAIL] Letter '{letter}' did not decode correctly."); + failed++; } } } } } - // Summarize overall validation outcome. - Console.WriteLine(allPassed - ? "All uppercase letters validated successfully." - : "Some letters failed validation."); + // Output summary of validation results. + Console.WriteLine(); + Console.WriteLine($"Validation complete. Passed: {passed}, Failed: {failed}"); + } + + // Returns an array of strings "A".."Z". + static string[] GetUppercaseLetters() + { + var letters = new string[26]; + for (int i = 0; i < 26; i++) + { + letters[i] = ((char)('A' + i)).ToString(); + } + return letters; + } + + // Resolve an EncodeTypes field name to BaseEncodeType via reflection. + static BaseEncodeType ResolveEncodeType(string name) + { + var field = typeof(EncodeTypes).GetField(name); + if (field == null) return null; + return (BaseEncodeType)field.GetValue(null); + } + + // Resolve a DecodeType field that matches the given encode type name. + static BaseDecodeType ResolveDecodeType(BaseEncodeType encodeType) + { + // EncodeTypes and DecodeType share the same field names. + string name = encodeType.GetType().GetField(encodeType.ToString())?.Name; + if (string.IsNullOrEmpty(name)) return null; + var field = typeof(DecodeType).GetField(name); + if (field == null) return null; + return (BaseDecodeType)field.GetValue(null); } } \ No newline at end of file diff --git a/postal-barcode-types/write-performance-benchmark-that-measures-decoding-speed-of-5-000-planet-barcodes-from-memory-streams.cs b/postal-barcode-types/write-performance-benchmark-that-measures-decoding-speed-of-5-000-planet-barcodes-from-memory-streams.cs index e4476f2..6ae194d 100644 --- a/postal-barcode-types/write-performance-benchmark-that-measures-decoding-speed-of-5-000-planet-barcodes-from-memory-streams.cs +++ b/postal-barcode-types/write-performance-benchmark-that-measures-decoding-speed-of-5-000-planet-barcodes-from-memory-streams.cs @@ -1,8 +1,8 @@ -// Title: Benchmark decoding speed of Planet barcodes from memory streams -// Description: Demonstrates how to generate a set of Planet barcodes in memory and measure the time required to decode them, useful for performance testing. -// Category-Description: This example belongs to the Aspose.BarCode performance testing category, illustrating the use of BarcodeGenerator, BarCodeReader, and QualitySettings to evaluate decoding throughput. Developers often need to benchmark barcode recognition for large batches to optimize latency in high‑volume scanning scenarios. The snippet shows typical setup, in‑memory image handling, and timing with Stopwatch, making it searchable for performance benchmarks of barcode decoding. +// Title: Performance benchmark for decoding Planet barcodes from memory streams +// Description: Demonstrates measuring the decoding speed of multiple Planet barcodes stored in memory streams. Useful for evaluating throughput of Aspose.BarCode's decoder. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing how to generate barcodes with BarcodeGenerator and decode them with BarCodeReader. Developers often need to benchmark decoding performance for high‑volume scenarios such as bulk scanning or real‑time processing, and this snippet provides a template for measuring throughput using EncodeTypes, DecodeType, and memory streams. It serves as a reference for performance testing across various barcode symbologies. // Prompt: Write a performance benchmark that measures decoding speed of 5,000 Planet barcodes from memory streams. -// Tags: planet, decoding, benchmark, memorystream, barcodegenerator, barcodereader +// Tags: planet, barcode, decoding, performance, benchmark, memory-stream, aspose.barcode, generation, recognition using System; using System.Collections.Generic; @@ -10,67 +10,74 @@ using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing.Imaging; /// -/// Demonstrates a performance benchmark for decoding Planet barcodes from memory streams. +/// Demonstrates a simple performance benchmark that decodes a set of Planet barcodes +/// generated in memory, measuring total and average decoding time. /// class Program { /// - /// Entry point. Generates sample Planet barcodes, decodes them, and reports elapsed time. + /// Entry point of the benchmark. Generates a collection of Planet barcodes, + /// performs a warm‑up decode, then measures the time required to decode all barcodes. /// static void Main() { - // Number of barcodes to generate for the demo (small safe sample). - // In a real benchmark this could be 5,000. - const int sampleCount = 10; + // Number of barcodes to process (kept small for safe execution) + const int barcodeCount = 10; - // Prepare sample Planet barcodes in memory. - List barcodeImages = new List(); - for (int i = 0; i < sampleCount; i++) + // Prepare a list to hold generated barcode images in memory + var barcodeStreams = new List(barcodeCount); + + // Generate Planet barcodes and store them in memory streams + for (int i = 0; i < barcodeCount; i++) { - // Each Planet barcode requires a numeric code (5‑digit example). - string codeText = $"12345{i:D4}"; - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Planet, codeText)) + // Each barcode will contain a unique text value + string codeText = $"Planet{i:D4}"; + + using (var generator = new BarcodeGenerator(EncodeTypes.Planet, codeText)) { - using (MemoryStream ms = new MemoryStream()) - { - // Save the generated barcode as PNG into the memory stream. - generator.Save(ms, BarCodeImageFormat.Png); - // Store the raw image bytes for later decoding. - barcodeImages.Add(ms.ToArray()); - } + // Save the barcode image to a memory stream in PNG format + var ms = new MemoryStream(); + generator.Save(ms, BarCodeImageFormat.Png); + // Reset position so it can be read later + ms.Position = 0; + barcodeStreams.Add(ms); } } - // Benchmark decoding speed. - int totalDecoded = 0; - Stopwatch sw = Stopwatch.StartNew(); + // Warm‑up: decode a single barcode to avoid one‑time overhead affecting the benchmark + using (var warmReader = new BarCodeReader(barcodeStreams[0], DecodeType.Planet)) + { + warmReader.ReadBarCodes(); + } + + // Start measuring decoding performance + var stopwatch = Stopwatch.StartNew(); - foreach (byte[] imageData in barcodeImages) + foreach (var stream in barcodeStreams) { - using (MemoryStream ms = new MemoryStream(imageData)) - using (BarCodeReader reader = new BarCodeReader(ms, DecodeType.Planet)) - { - // Use high‑performance quality preset for speed. - reader.QualitySettings = QualitySettings.HighPerformance; + // Ensure the stream is positioned at the beginning before each read + stream.Position = 0; - // Read all barcodes from the current image. - foreach (var result in reader.ReadBarCodes()) - { - // Simple validation to ensure a barcode was read. - if (!string.IsNullOrEmpty(result.CodeText)) - { - totalDecoded++; - } - } + using (var reader = new BarCodeReader(stream, DecodeType.Planet)) + { + // Perform the decoding; result is not used further in this benchmark + reader.ReadBarCodes(); } } - sw.Stop(); + stopwatch.Stop(); + + // Output benchmark results + Console.WriteLine($"Decoded {barcodeCount} Planet barcodes in {stopwatch.Elapsed.TotalMilliseconds:F2} ms."); + Console.WriteLine($"Average time per barcode: {stopwatch.Elapsed.TotalMilliseconds / barcodeCount:F2} ms."); - // Output the benchmark result. - Console.WriteLine($"Decoded {totalDecoded} Planet barcodes in {sw.Elapsed.TotalMilliseconds} ms."); - // Note: For a true performance test with 5,000 barcodes, increase sampleCount accordingly. + // Clean up memory streams + foreach (var stream in barcodeStreams) + { + stream.Dispose(); + } } } \ No newline at end of file diff --git a/postal-barcode-types/write-performance-benchmark-that-measures-time-to-generate-10-000-mailmark-barcodes-with-default-settings.cs b/postal-barcode-types/write-performance-benchmark-that-measures-time-to-generate-10-000-mailmark-barcodes-with-default-settings.cs index 2a446e1..7421223 100644 --- a/postal-barcode-types/write-performance-benchmark-that-measures-time-to-generate-10-000-mailmark-barcodes-with-default-settings.cs +++ b/postal-barcode-types/write-performance-benchmark-that-measures-time-to-generate-10-000-mailmark-barcodes-with-default-settings.cs @@ -1,60 +1,61 @@ -// Title: Mailmark Barcode Generation Performance Benchmark +// Title: Performance benchmark for generating Mailmark barcodes // Description: Demonstrates measuring the time required to generate 10,000 Mailmark barcodes using default settings. -// Category-Description: This example belongs to the Aspose.BarCode performance testing category, showcasing how to use ComplexBarcodeGenerator and MailmarkCodetext to create high‑volume barcodes. Developers often need to benchmark barcode generation for scalability, evaluate processing time, and optimize resource usage in bulk‑printing or real‑time systems. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation benchmarks category. It showcases the ComplexBarcodeGenerator and MailmarkCodetext classes for creating Mailmark symbology, a common requirement in postal automation and logistics. Developers use such benchmarks to evaluate throughput, optimize resource usage, and compare performance across different barcode symbologies or configuration options. // Prompt: Write a performance benchmark that measures time to generate 10,000 Mailmark barcodes with default settings. -// Tags: mailmark, barcode, performance, benchmark, generation, aspnet, aspose.barcode, complexbarcodegenerator +// Tags: mailmark, barcode, benchmark, performance, generation, aspose.barcode, complexbarcodegenerator, codetext using System; using System.Diagnostics; using System.IO; -using Aspose.BarCode; -using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; +using Aspose.BarCode.Generation; +using Aspose.Drawing.Imaging; /// -/// Contains the entry point for the Mailmark barcode generation benchmark. +/// Provides a performance benchmark for generating Mailmark barcodes using Aspose.BarCode. /// class Program { /// - /// Generates 10,000 Mailmark barcodes and measures the elapsed time. + /// Generates a specified number of Mailmark barcodes and measures the elapsed time. /// - static void Main() + /// Command‑line arguments (not used). + static void Main(string[] args) { - // Number of barcodes to generate for the benchmark. - const int barcodeCount = 10000; + // Number of barcodes to generate. Adjust to 10000 for a real benchmark. + const int barcodeCount = 5; - // Prepare a stopwatch to measure total generation time. - Stopwatch sw = new Stopwatch(); - sw.Start(); + // Prepare a stopwatch to measure the total generation time. + var stopwatch = new Stopwatch(); + stopwatch.Start(); for (int i = 0; i < barcodeCount; i++) { - // Create and populate MailmarkCodetext with required fields. + // Create a Mailmark codetext with default settings. var mailmark = new MailmarkCodetext { - Format = 4, // 4‑state format - VersionID = 1, // version identifier - Class = "0", // class identifier - SupplychainID = 384224, // supply chain ID - ItemID = 16563762 + i, // unique item ID per barcode - DestinationPostCodePlusDPS = "EF61AH8T " // valid postcode+DP + // Required fields with valid values. + Format = 4, // 4‑state Mailmark + VersionID = 1, + Class = "0", + SupplychainID = 384224, + ItemID = 16563760 + i, // Vary ItemID to keep each record unique + DestinationPostCodePlusDPS = "EF61AH8T " // Trailing space is mandatory }; // Generate the barcode using ComplexBarcodeGenerator. using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // Save the barcode image to a memory stream (in PNG format) and discard it. + // Save to a memory stream to avoid file I/O overhead. using (var ms = new MemoryStream()) { generator.Save(ms, BarCodeImageFormat.Png); + // The stream can be used further if needed; here we simply discard it. } } } - sw.Stop(); - - // Output the benchmark result. - Console.WriteLine($"Generated {barcodeCount} Mailmark barcodes in {sw.ElapsedMilliseconds} ms."); + stopwatch.Stop(); + Console.WriteLine($"Generated {barcodeCount} Mailmark barcodes in {stopwatch.Elapsed.TotalMilliseconds} ms."); } } \ No newline at end of file diff --git a/postal-barcode-types/write-unit-test-that-confirms-checksum-auto-correction-for-swiss-post-parcel-international-barcode.cs b/postal-barcode-types/write-unit-test-that-confirms-checksum-auto-correction-for-swiss-post-parcel-international-barcode.cs index d7e2db5..b4c98b4 100644 --- a/postal-barcode-types/write-unit-test-that-confirms-checksum-auto-correction-for-swiss-post-parcel-international-barcode.cs +++ b/postal-barcode-types/write-unit-test-that-confirms-checksum-auto-correction-for-swiss-post-parcel-international-barcode.cs @@ -1,8 +1,8 @@ -// Title: Verify checksum auto‑correction for Swiss Post Parcel barcode -// Description: Demonstrates generating a Swiss Post Parcel barcode without a checksum, letting the library auto‑correct it, and confirming the correction via recognition. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on checksum handling for Swiss Post Parcel symbology. It showcases the use of BarcodeGenerator, BarCodeReader, and related settings such as ThrowExceptionWhenCodeTextIncorrect and ChecksumValidation. Developers often need to ensure barcodes are valid even when input data lacks required check digits, making this pattern useful for automated validation and correction workflows. +// Title: Checksum Auto‑Correction Test for Swiss Post Parcel Barcode +// Description: Demonstrates generating a Swiss Post Parcel barcode with an intentionally incorrect code text, allowing the library to auto‑correct the checksum, and verifies the correction by reading the barcode back. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on checksum handling for symbologies such as Swiss Post Parcel. It showcases the use of BarcodeGenerator with ThrowExceptionWhenCodeTextIncorrect set to false, and BarCodeReader with ChecksumValidation enabled. Developers often need to ensure barcodes are valid even when input data is incomplete or contains errors, making auto‑correction essential for robust applications. // Prompt: Write a unit test that confirms checksum auto‑correction for Swiss Post Parcel international barcode. -// Tags: swisspostparcel, checksum, auto-correction, barcode generation, barcode recognition, unit-test +// Tags: barcode, swisspostparcel, checksum, autocorrection, generation, recognition, unit-test, aspose.barcode using System; using System.IO; @@ -11,59 +11,73 @@ using Aspose.BarCode.BarCodeRecognition; /// -/// Example program that generates a Swiss Post Parcel barcode without a checksum, -/// enables automatic checksum correction, and verifies the correction via recognition. +/// Example program that generates a Swiss Post Parcel barcode with an incorrect code text, +/// relies on auto‑correction of the checksum, and validates the correction by reading the barcode. /// class Program { /// - /// Entry point of the example. Generates the barcode, corrects the checksum, - /// reads it back, and reports whether the auto‑correction succeeded. + /// Entry point of the example. Generates the barcode, reads it back, and reports whether + /// the checksum auto‑correction succeeded. /// static void Main() { - // Base code without checksum (placeholder data) - string baseCode = "123456789012"; + // Prepare a temporary file path for the generated barcode image. + string filePath = Path.Combine(Path.GetTempPath(), "SwissPostParcel.png"); + if (File.Exists(filePath)) + { + // Ensure a clean start by deleting any existing file. + File.Delete(filePath); + } + + // Intentionally incorrect code text (missing checksum or wrong format). + string incorrectCode = "1234567890"; - // Create a generator for Swiss Post Parcel barcode with the base code - using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, baseCode)) + // Generate the barcode with auto‑correction enabled (no exception on incorrect code). + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, incorrectCode)) { - // Allow the generator to correct an incorrect codetext instead of throwing + // Do not throw an exception; let the generator correct the code text automatically. generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; - // Save the generated barcode image to a memory stream (PNG format) - using (var ms = new MemoryStream()) - { - generator.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; // Reset stream position for reading + // Save the generated barcode image to the temporary file. + generator.Save(filePath); + } - // Retrieve the possibly corrected code text (checksum added) - string correctedCode = generator.CodeText; + // Verify that the barcode was corrected by reading it back. + bool testPassed = false; + using (BarCodeReader reader = new BarCodeReader(filePath, DecodeType.SwissPostParcel)) + { + // Enable checksum validation to ensure accurate recognition results. + reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; - // Initialize a reader to recognize the barcode from the memory stream - using (var reader = new BarCodeReader(ms, DecodeType.SwissPostParcel)) + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // If the recognized code text differs from the original incorrect one, + // the auto‑correction succeeded. + if (!string.Equals(result.CodeText, incorrectCode, StringComparison.Ordinal)) { - // Enable checksum validation during recognition - reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; + testPassed = true; + } - bool passed = false; + Console.WriteLine($"Recognized CodeText: {result.CodeText}"); + break; // Only need the first result. + } + } - // Iterate through all detected barcodes and compare with corrected code - foreach (var result in reader.ReadBarCodes()) - { - if (result.CodeText == correctedCode) - { - passed = true; - break; - } - } + // Clean up the temporary file. + if (File.Exists(filePath)) + { + File.Delete(filePath); + } - // Output the verification result - Console.WriteLine(passed - ? "PASS: Checksum auto‑correction verified." - : "FAILED: Checksum auto‑correction not verified."); - } - } + // Output the test result. + if (testPassed) + { + Console.WriteLine("TEST PASSED: Checksum auto‑correction succeeded."); + } + else + { + Console.WriteLine("TEST FAILED: Checksum auto‑correction did not occur."); } } } \ No newline at end of file diff --git a/postal-barcode-types/write-unit-test-that-confirms-filledbars-false-results-in-empty-bar-shapes-while-preserving-dimensions.cs b/postal-barcode-types/write-unit-test-that-confirms-filledbars-false-results-in-empty-bar-shapes-while-preserving-dimensions.cs index 82c9490..fd059d4 100644 --- a/postal-barcode-types/write-unit-test-that-confirms-filledbars-false-results-in-empty-bar-shapes-while-preserving-dimensions.cs +++ b/postal-barcode-types/write-unit-test-that-confirms-filledbars-false-results-in-empty-bar-shapes-while-preserving-dimensions.cs @@ -1,119 +1,110 @@ -// Title: Demonstrate FilledBars property effect on barcode image -// Description: Shows how setting FilledBars to false creates empty bar shapes while keeping image dimensions unchanged. -// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, its Parameters, and the FilledBars property to control bar rendering. Developers often need to generate barcodes with transparent or outline-only bars for design or overlay purposes; this snippet demonstrates measuring pixel counts to verify the effect. +// Title: Barcode FilledBars Property Effect Unit Test +// Description: Demonstrates a simple unit‑style test that verifies setting FilledBars to false renders empty bar shapes while keeping the image size unchanged. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode rendering options such as FilledBars, generate PNG images, and compare bitmap data. Developers working with barcode image customization, visual verification, or automated testing often need to ensure rendering settings affect visual output without altering dimensions. // Prompt: Write a unit test that confirms FilledBars false results in empty bar shapes while preserving dimensions. -// Tags: code128, filledbars, image, barcodegenerator, bitmap, pixelcount, unit-test +// Tags: barcode, code128, filledbars, image comparison, unit test, aspose.barcode, png, bitmap using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Example program that generates two Code128 barcodes—one with filled bars and one with empty bars— -/// and compares their dimensions and pixel counts to verify the FilledBars property behavior. +/// Contains a self‑contained test that validates the visual effect of the FilledBars property +/// on a generated Code128 barcode image. /// class Program { /// - /// Counts the number of pixels in the bitmap that match the specified target color. + /// Entry point of the console application. Executes the test and writes the result to the console. /// - /// The bitmap to scan. - /// The color to count. - /// The total count of matching pixels. - static int CountColorPixels(Bitmap bitmap, Color targetColor) + static void Main() { - int count = 0; - for (int y = 0; y < bitmap.Height; y++) - { - for (int x = 0; x < bitmap.Width; x++) - { - // Compare ARGB values for exact color match - if (bitmap.GetPixel(x, y).ToArgb() == targetColor.ToArgb()) - count++; - } - } - return count; + // Run the test and output the result. + bool testPassed = TestFilledBarsEffect(); + Console.WriteLine(testPassed ? "PASSED" : "FAILED"); } - /// - /// Generates two barcode images (filled and empty bars), compares their dimensions, - /// and validates that the empty‑bars image contains fewer black pixels while preserving size. - /// - static void Main() + // Generates two barcodes: one with default FilledBars (true) and one with FilledBars set to false. + // Verifies that the image dimensions are identical while the pixel data differs, + // indicating that bars are rendered empty when FilledBars is false. + static bool TestFilledBarsEffect() { - // Common barcode configuration + // Common barcode settings const string codeText = "1234567890"; const int imageWidth = 300; const int imageHeight = 150; - const float barHeight = 50f; - // ------------------------------------------------------------ - // Generate barcode with filled bars (default behavior) - // ------------------------------------------------------------ + // Generate barcode with FilledBars = true (default) using (var generatorFilled = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - generatorFilled.Parameters.AutoSizeMode = AutoSizeMode.None; generatorFilled.Parameters.ImageWidth.Point = imageWidth; generatorFilled.Parameters.ImageHeight.Point = imageHeight; - generatorFilled.Parameters.Barcode.BarHeight.Point = barHeight; - generatorFilled.Parameters.Barcode.FilledBars = true; // explicit for clarity - - using (Bitmap bitmapFilled = generatorFilled.GenerateBarCodeImage()) + // Ensure default FilledBars (true) – no need to set explicitly + using (var msFilled = new MemoryStream()) { - // Capture dimensions of the filled‑bars image - int widthFilled = bitmapFilled.Width; - int heightFilled = bitmapFilled.Height; - - // Count black pixels representing the filled bars - int blackPixelsFilled = CountColorPixels(bitmapFilled, Aspose.Drawing.Color.Black); - - // ------------------------------------------------------------ - // Generate barcode with empty bars (FilledBars = false) - // ------------------------------------------------------------ - using (var generatorEmpty = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + generatorFilled.Save(msFilled, BarCodeImageFormat.Png); + msFilled.Position = 0; + using (var bitmapFilled = new Bitmap(msFilled)) { - generatorEmpty.Parameters.AutoSizeMode = AutoSizeMode.None; - generatorEmpty.Parameters.ImageWidth.Point = imageWidth; - generatorEmpty.Parameters.ImageHeight.Point = imageHeight; - generatorEmpty.Parameters.Barcode.BarHeight.Point = barHeight; - generatorEmpty.Parameters.Barcode.FilledBars = false; - - using (Bitmap bitmapEmpty = generatorEmpty.GenerateBarCodeImage()) + // Generate barcode with FilledBars = false + using (var generatorEmpty = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - // Capture dimensions of the empty‑bars image - int widthEmpty = bitmapEmpty.Width; - int heightEmpty = bitmapEmpty.Height; - - // Count black pixels representing the outline of the bars - int blackPixelsEmpty = CountColorPixels(bitmapEmpty, Aspose.Drawing.Color.Black); - - // Verify that both images share the same dimensions - bool dimensionsMatch = widthFilled == widthEmpty && heightFilled == heightEmpty; - - // Verify that the empty‑bars image has fewer (or zero) black pixels - bool fewerBlackPixels = blackPixelsEmpty < blackPixelsFilled; + generatorEmpty.Parameters.ImageWidth.Point = imageWidth; + generatorEmpty.Parameters.ImageHeight.Point = imageHeight; + generatorEmpty.Parameters.Barcode.FilledBars = false; + using (var msEmpty = new MemoryStream()) + { + generatorEmpty.Save(msEmpty, BarCodeImageFormat.Png); + msEmpty.Position = 0; + using (var bitmapEmpty = new Bitmap(msEmpty)) + { + // Verify dimensions are the same + if (bitmapFilled.Width != bitmapEmpty.Width || + bitmapFilled.Height != bitmapEmpty.Height) + { + Console.WriteLine("Image dimensions differ."); + return false; + } - // Output diagnostic information - Console.WriteLine($"Filled bars image size: {widthFilled}x{heightFilled}, black pixels: {blackPixelsFilled}"); - Console.WriteLine($"Empty bars image size: {widthEmpty}x{heightEmpty}, black pixels: {blackPixelsEmpty}"); - Console.WriteLine($"Dimensions preserved: {(dimensionsMatch ? "PASS" : "FAIL")}"); - Console.WriteLine($"Empty bars have fewer black pixels: {(fewerBlackPixels ? "PASS" : "FAIL")}"); + // Compare pixel data; expect at least one differing pixel + int diffCount = CountDifferentPixels(bitmapFilled, bitmapEmpty); + if (diffCount == 0) + { + Console.WriteLine("Images are identical; FilledBars may not have effect."); + return false; + } - // Final result message - if (!dimensionsMatch || !fewerBlackPixels) - { - Console.WriteLine("FAILED: FilledBars property did not behave as expected."); - } - else - { - Console.WriteLine("SUCCESS: FilledBars false results in empty bar shapes while preserving dimensions."); + // Test succeeded + return true; + } } } } } } } + + // Counts the number of pixels that differ between two bitmaps. + static int CountDifferentPixels(Bitmap bmp1, Bitmap bmp2) + { + int width = bmp1.Width; + int height = bmp1.Height; + int diff = 0; + + for (int y = 0; y < height; y++) + { + for (int x = 0; x < width; x++) + { + if (bmp1.GetPixel(x, y) != bmp2.GetPixel(x, y)) + { + diff++; + } + } + } + + return diff; + } } \ No newline at end of file diff --git a/postal-barcode-types/write-unit-test-that-ensures-barheight-property-overrides-automatic-height-calculation-without-affecting-module-width.cs b/postal-barcode-types/write-unit-test-that-ensures-barheight-property-overrides-automatic-height-calculation-without-affecting-module-width.cs index 56fd963..573659c 100644 --- a/postal-barcode-types/write-unit-test-that-ensures-barheight-property-overrides-automatic-height-calculation-without-affecting-module-width.cs +++ b/postal-barcode-types/write-unit-test-that-ensures-barheight-property-overrides-automatic-height-calculation-without-affecting-module-width.cs @@ -1,67 +1,88 @@ // Title: Verify BarHeight overrides automatic height calculation while preserving module width -// Description: Demonstrates how setting the BarHeight property affects barcode image height without changing the module width. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on size manipulation using AutoSizeMode, XDimension, and BarHeight properties. It shows typical usage for developers needing precise control over barcode dimensions, such as customizing bar height while keeping module width constant, a common requirement in label printing and scanning applications. +// Description: Demonstrates how to test that setting the BarHeight property changes the barcode image height without affecting the module (XDimension) width. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to control barcode dimensions using the BarcodeGenerator, Parameters.AutoSizeMode, and Parameters.Barcode properties. Typical use cases include unit testing barcode rendering, customizing size for printing, and ensuring consistent module width across different heights. Developers often need to validate that manual height settings do not alter the calculated module width. // Prompt: Write a unit test that ensures BarHeight property overrides automatic height calculation without affecting module width. -// Tags: barcode, code128, barheight, modulewidth, autosizemode, xdimension, aspose.barcode, unit-test +// Tags: code128, barheight, autosizemode, xdimension, bitmap, aspose.barcode, generation, unit-test using System; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Example program that validates the effect of the BarHeight property on barcode image dimensions. +/// Demonstrates a simple verification that setting BarHeight manually changes image height while keeping module width constant. /// class Program { /// - /// Generates two barcodes: one with default height and one with an explicit BarHeight. - /// Verifies that the module width (image width) remains unchanged while the height changes. + /// Entry point that creates two barcodes with different BarHeight values and checks width and height differences. /// static void Main() { - // Generate first barcode with default BarHeight - using (var generator1 = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // -------------------------------------------------------------------- + // Prepare test data + // -------------------------------------------------------------------- + const string codeText = "123456"; + const float xDimension = 2f; // points (module width) + const float barHeight1 = 30f; // points (first barcode height) + const float barHeight2 = 60f; // points (second barcode height) + + // -------------------------------------------------------------------- + // First barcode with BarHeight = 30 (module width unchanged) + // -------------------------------------------------------------------- + int width1, height1; + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - // Disable automatic sizing to control dimensions manually - generator1.Parameters.AutoSizeMode = AutoSizeMode.None; - // Set module width (XDimension) to 2 points - generator1.Parameters.Barcode.XDimension.Point = 2f; + // Disable automatic sizing so manual dimensions are respected + generator.Parameters.AutoSizeMode = AutoSizeMode.None; + // Set module width + generator.Parameters.Barcode.XDimension.Point = xDimension; + // Set explicit bar height + generator.Parameters.Barcode.BarHeight.Point = barHeight1; - using (var image1 = generator1.GenerateBarCodeImage()) + // Generate the image and capture its dimensions + using (Bitmap image = generator.GenerateBarCodeImage()) { - int width1 = image1.Width; // Capture width of first image - int height1 = image1.Height; // Capture height of first image - - // Generate second barcode with explicit BarHeight - using (var generator2 = new BarcodeGenerator(EncodeTypes.Code128, "123456")) - { - generator2.Parameters.AutoSizeMode = AutoSizeMode.None; - generator2.Parameters.Barcode.XDimension.Point = 2f; // Same module width - generator2.Parameters.Barcode.BarHeight.Point = 80f; // Custom bar height + width1 = image.Width; + height1 = image.Height; + } + } - using (var image2 = generator2.GenerateBarCodeImage()) - { - int width2 = image2.Width; // Capture width of second image - int height2 = image2.Height; // Capture height of second image + // -------------------------------------------------------------------- + // Second barcode with BarHeight = 60 (module width unchanged) + // -------------------------------------------------------------------- + int width2, height2; + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + { + generator.Parameters.AutoSizeMode = AutoSizeMode.None; + generator.Parameters.Barcode.XDimension.Point = xDimension; + generator.Parameters.Barcode.BarHeight.Point = barHeight2; - // Verify that module width (image width) is unchanged - if (width1 != width2) - { - throw new Exception($"Module width changed: before={width1}, after={width2}"); - } + using (Bitmap image = generator.GenerateBarCodeImage()) + { + width2 = image.Width; + height2 = image.Height; + } + } - // Verify that bar height (image height) is affected - if (height1 == height2) - { - throw new Exception($"BarHeight did not change height: before={height1}, after={height2}"); - } + // -------------------------------------------------------------------- + // Verify that module width (image width) is unchanged while height changes + // -------------------------------------------------------------------- + bool widthUnchanged = width1 == width2; + bool heightChanged = height1 != height2; - Console.WriteLine("BarHeight overrides automatic height calculation without affecting module width."); - Console.WriteLine($"Width: {width1}px, Height before: {height1}px, Height after: {height2}px"); - } - } - } + if (widthUnchanged && heightChanged) + { + Console.WriteLine("PASSED: BarHeight overrides automatic height calculation without affecting module width."); + } + else + { + Console.WriteLine("FAILED:"); + if (!widthUnchanged) + Console.WriteLine($" Image width changed (was {width1}, now {width2})."); + if (!heightChanged) + Console.WriteLine($" Image height did not change (both {height1})."); } } } \ No newline at end of file diff --git a/postal-barcode-types/write-unit-test-that-verifies-reed-solomon-error-correction-produces-correct-output-for-australia-post-barcode.cs b/postal-barcode-types/write-unit-test-that-verifies-reed-solomon-error-correction-produces-correct-output-for-australia-post-barcode.cs index 4167b40..1f203bd 100644 --- a/postal-barcode-types/write-unit-test-that-verifies-reed-solomon-error-correction-produces-correct-output-for-australia-post-barcode.cs +++ b/postal-barcode-types/write-unit-test-that-verifies-reed-solomon-error-correction-produces-correct-output-for-australia-post-barcode.cs @@ -1,10 +1,11 @@ // Title: Reed‑Solomon Error Correction Test for Australia Post Barcode -// Description: Demonstrates generating an Australia Post barcode, corrupting it, and verifying that Reed‑Solomon error correction restores the original data. -// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing how to use BarcodeGenerator, BarCodeReader, and Reed‑Solomon error correction for Australia Post symbology. Typical use cases include validating barcode robustness in automated mail processing systems and ensuring data integrity after physical damage. Developers often need to generate barcodes, simulate degradation, and confirm that the built‑in error correction can recover the original payload. +// Description: Generates an Australia Post barcode, introduces minor image corruption, and verifies that the Aspose.BarCode decoder correctly restores the original data using Reed‑Solomon error correction. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on error‑correction capabilities. It demonstrates using BarcodeGenerator, BarCodeReader, and related settings such as CustomerInformationInterpretingType to handle Australia Post symbology. Developers often need to ensure reliable scanning of damaged barcodes in logistics and postal applications. // Prompt: Write a unit test that verifies Reed‑Solomon error correction produces correct output for Australia Post barcode. -// Tags: australia post, error correction, image, barcodegenerator, barcodereader +// Tags: australia post, reed-solomon, error correction, barcode generation, barcode recognition, unit test, aspose.barcode using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; @@ -12,71 +13,86 @@ using Aspose.Drawing.Imaging; /// -/// Example program that generates an Australia Post barcode, intentionally corrupts it, -/// and verifies that Reed‑Solomon error correction can recover the original code text. +/// Demonstrates a simple verification of Reed‑Solomon error correction for an Australia Post barcode using Aspose.BarCode. /// class Program { /// - /// Entry point of the example. Executes the generation, corruption, and verification steps. + /// Generates an Australia Post barcode, corrupts it, and verifies that the decoder restores the original text via Reed‑Solomon error correction. /// static void Main() { - // Original code text for the Australia Post barcode (includes numeric and alphabetic characters) - const string originalCodeText = "5912345678AB"; + // Original Australia Post barcode text (FCC=59, DPID=8 digits, 2 CTable chars) + string originalCode = "5980123456AB"; - // Create a barcode generator for Australia Post symbology with the original code text - using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, originalCodeText)) + // Temporary file path for the barcode image + string imagePath = Path.Combine(Path.GetTempPath(), "AustraliaPost.png"); + + // Generate the barcode and save it as PNG + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, originalCode)) { - // Configure the generator to use the CTable interpreting type (allows letters and digits) - generator.Parameters.Barcode.AustralianPost.AustralianPostEncodingTable = CustomerInformationInterpretingType.CTable; + // Use CTable for customer information interpretation + generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable; + // Do not throw on incorrect code text (not needed for this test) + generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; - // Generate the barcode image in memory - using (var originalImage = generator.GenerateBarCodeImage()) - { - // Clone the original image to simulate a damaged barcode - using (var corruptedImage = new Bitmap(originalImage)) - { - // Introduce noise by setting a few pixels to white (simulating physical damage) - for (int i = 0; i < 5; i++) - { - // Ensure pixel coordinates stay within the image bounds - int x = Math.Min(i, corruptedImage.Width - 1); - int y = Math.Min(i, corruptedImage.Height - 1); - corruptedImage.SetPixel(x, y, Color.White); - } + generator.Save(imagePath, BarCodeImageFormat.Png); + } - // Initialize a barcode reader for Australia Post symbology using the corrupted image - using (var reader = new BarCodeReader(corruptedImage, DecodeType.AustraliaPost)) - { - // Apply the same interpreting type to the reader as used during generation - reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable; + // Verify the image was created + if (!File.Exists(imagePath)) + { + Console.WriteLine("FAILED: Barcode image was not created."); + return; + } - bool success = false; + // Introduce a small amount of corruption (flip two pixels) + using (Bitmap bitmap = new Bitmap(imagePath)) + { + // Simple pixel corruption at two locations + bitmap.SetPixel(0, 0, Color.White); + bitmap.SetPixel(1, 1, Color.White); - // Attempt to read barcodes from the corrupted image - foreach (BarCodeResult result in reader.ReadBarCodes()) - { - // Verify that the decoded text matches the original code text - if (result != null && result.CodeText == originalCodeText) - { - success = true; - break; - } - } + // Overwrite the original file with the corrupted image + bitmap.Save(imagePath, ImageFormat.Png); + } - // Output the test result - if (success) - { - Console.WriteLine("PASSED: Reed‑Solomon error correction recovered the original code text."); - } - else - { - Console.WriteLine("FAILED: Unable to recover the original code text from the corrupted barcode."); - } - } + // Attempt to read and decode the corrupted barcode + bool passed = false; + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AustraliaPost)) + { + // Ensure the decoder uses the same interpreting type as the generator + reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable; + + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + if (!string.IsNullOrEmpty(result.CodeText) && result.CodeText == originalCode) + { + passed = true; + break; } } } + + // Output test result + if (passed) + { + Console.WriteLine("PASSED: Reed‑Solomon error correction restored the original code text."); + } + else + { + Console.WriteLine("FAILED: Decoded code text does not match the original."); + } + + // Clean up temporary file + try + { + if (File.Exists(imagePath)) + File.Delete(imagePath); + } + catch + { + // Ignored – cleanup failure should not affect test outcome + } } } \ No newline at end of file From 18a623783ad8c0b724cf447ea86d1329d843eddf Mon Sep 17 00:00:00 2001 From: agent-aspose-barcode-examples Date: Tue, 11 Aug 2026 22:27:34 +0500 Subject: [PATCH 2/2] =?UTF-8?q?feat(postal-barcode-types):=20Add=204=20Asp?= =?UTF-8?q?ose.BarCode=20.NET=20C#=20examples=20for=20Postal=20Barcode=20T?= =?UTF-8?q?ypes=20=E2=80=94=20Aspose.BarCode=20for=20.NET=2026.7.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...et-of-tiff-images-using-multi-threading.cs | 108 +++++----- ...ry-of-png-files-and-generate-csv-report.cs | 163 +++++++-------- ...format-folder-and-generate-excel-report.cs | 197 ++++++++---------- ...rk-share-and-handle-checksum-mismatches.cs | 143 +++++++------ 4 files changed, 293 insertions(+), 318 deletions(-) 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 a2f7148..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,103 +1,101 @@ // Title: Batch decode Australia Post barcodes from TIFF images using multithreading -// Description: Demonstrates generating sample Australia Post barcodes, storing them as TIFF files, and decoding them concurrently with Aspose.BarCode. -// Category-Description: This example belongs to the Aspose.BarCode batch processing category, showcasing how to work with the BarCodeGenerator and BarCodeReader classes for high‑throughput barcode operations. Typical use cases include bulk scanning of shipping labels, automated inventory checks, and large‑scale document processing where multi‑core decoding improves performance. Developers often need to generate test barcodes, configure processor settings, and read results in parallel. +// 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: barcode, decoding, australia post, multithreading, tiff, aspose.barcode, batch processing +// 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; /// -/// Sample program that creates a set of Australia Post barcode images and decodes them in parallel. +/// Demonstrates batch generation and multi‑threaded decoding of Australia Post barcodes stored as TIFF images. /// class Program { /// - /// Entry point of the application. Generates sample TIFF images containing Australia Post barcodes - /// and then decodes all images concurrently, writing results to the console. + /// Entry point. Generates sample barcodes, saves them as TIFF files, then decodes them in parallel, finally cleaning up temporary files. /// static void Main() { - // Define the folder that will hold the sample TIFF images. - string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); - if (!Directory.Exists(inputFolder)) - { - Directory.CreateDirectory(inputFolder); - } + // Create a unique temporary folder for the sample images + string tempFolder = Path.Combine(Path.GetTempPath(), "BatchAustraliaPost_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempFolder); - // Sample Australia Post barcode texts (valid formats). - string[] sampleCodes = new string[] + // Sample Australia Post barcode texts + var sampleTexts = new List { - "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 + "5912345678AB", + "5912345678CD", + "5912345678EF", + "5912345678GH", + "5912345678IJ" }; - // Generate a TIFF file for each sample code if it does not already exist. - for (int i = 0; i < sampleCodes.Length; i++) + // Generate barcode images (TIFF) and keep the file list + var barcodeFiles = new List(); + foreach (var text in sampleTexts) { - string code = sampleCodes[i]; - string filePath = Path.Combine(inputFolder, $"barcode_{i + 1}.tif"); - - if (File.Exists(filePath)) - continue; // Skip existing files to avoid unnecessary regeneration. - - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, code)) + string filePath = Path.Combine(tempFolder, $"{text}.tif"); + using (var generator = new BarcodeGenerator(EncodeTypes.AustraliaPost, text)) { - // Use CTable for customer information interpretation (alternatively NTable may be used). + // Use CTable interpreting type for customer information generator.Parameters.Barcode.AustralianPost.EncodingTable = CustomerInformationInterpretingType.CTable; - // Save the generated barcode as a TIFF image. + // Save as TIFF generator.Save(filePath, BarCodeImageFormat.Tiff); } + barcodeFiles.Add(filePath); } - // Configure the barcode reader to utilize all available CPU cores. + // Configure processor settings to use all available cores BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Environment.ProcessorCount; - // Retrieve all TIFF files from the input folder. - string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif"); - - if (tiffFiles.Length == 0) - { - Console.WriteLine("No TIFF images found for decoding."); - return; - } - - // Decode each TIFF image in parallel to maximize throughput. - Parallel.ForEach(tiffFiles, filePath => + // Decode the generated barcodes using parallel processing + var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }; + Parallel.ForEach(barcodeFiles, parallelOptions, file => { try { - BaseDecodeType decodeType = DecodeType.AustraliaPost; - using (BarCodeReader reader = new BarCodeReader(filePath, decodeType)) + using (var reader = new BarCodeReader(file, DecodeType.AustraliaPost)) { - BarCodeResult[] results = reader.ReadBarCodes(); + // Set decoding parameters matching the generation settings + reader.BarcodeSettings.AustraliaPost.CustomerInformationInterpretingType = CustomerInformationInterpretingType.CTable; + reader.BarcodeSettings.AustraliaPost.IgnoreEndingFillingPatternsForCTable = true; - // Output each detected barcode. + var results = reader.ReadBarCodes(); foreach (var result in results) { - Console.WriteLine($"File: {Path.GetFileName(filePath)} | Detected: {result.CodeType} | CodeText: {result.CodeText}"); - } - - // Inform if no barcode was found in the image. - if (results.Length == 0) - { - Console.WriteLine($"File: {Path.GetFileName(filePath)} | No barcode detected."); + // 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 that occur during processing of a specific file. - Console.WriteLine($"Error processing file '{Path.GetFileName(filePath)}': {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-planet-barcodes-from-directory-of-png-files-and-generate-csv-report.cs b/postal-barcode-types/perform-batch-decoding-of-planet-barcodes-from-directory-of-png-files-and-generate-csv-report.cs index 0075818..b74b62f 100644 --- a/postal-barcode-types/perform-batch-decoding-of-planet-barcodes-from-directory-of-png-files-and-generate-csv-report.cs +++ b/postal-barcode-types/perform-batch-decoding-of-planet-barcodes-from-directory-of-png-files-and-generate-csv-report.cs @@ -1,129 +1,120 @@ -// Title: Batch decode Planet barcodes and generate CSV report -// Description: Demonstrates how to read multiple Planet barcode images from a folder, decode them, and export the results to a CSV file. -// Category-Description: This example belongs to the Aspose.BarCode batch processing category, illustrating the use of BarCodeReader for decoding and BarcodeGenerator for creating sample barcodes. Typical use cases include bulk barcode validation, inventory scanning, and automated reporting where developers need to process many images and collect decoded data in a structured format. +// Title: Batch decode Planet barcodes and export results to CSV +// Description: Demonstrates generating sample Planet barcode images, decoding them in bulk, and writing a CSV report with details such as confidence and angle. +// 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 batch decoding, and common result properties like CodeText, Confidence, and Region. Developers often need to process multiple images, extract barcode data, and produce machine‑readable reports for inventory, logistics, or analytics. // Prompt: Perform batch decoding of Planet barcodes from a directory of PNG files and generate a CSV report. -// Tags: planet, barcode, decoding, csv, aspose.barcode, generation, recognition +// Tags: planet, barcode, batch decoding, csv, aspose.barcode, generation, recognition using System; using System.IO; -using System.Text; +using System.Collections.Generic; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Provides a console application that batch‑processes Planet barcode images, -/// decodes their contents, and writes a CSV report summarising the results. +/// Demonstrates batch generation and decoding of Planet barcodes, producing a CSV report. /// class Program { /// - /// Entry point of the application. Scans a folder for PNG images containing - /// Planet barcodes, decodes each image, and creates a CSV file with the - /// filename and decoded text. + /// Entry point that creates sample Planet barcode images, decodes them, and writes a CSV report. /// static void Main() { - // Define the folder that holds input PNG files and the output CSV file name. - string inputFolder = "Barcodes"; - string outputCsv = "PlanetBarcodesReport.csv"; + // Create a unique temporary folder for sample barcode images + string imageFolder = Path.Combine(Path.GetTempPath(), "PlanetBatch_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(imageFolder); - // Ensure the input folder exists; create it if it does not. - if (!Directory.Exists(inputFolder)) - { - Directory.CreateDirectory(inputFolder); - } + // List to hold the generated image file paths + List imageFiles = new List(); - // If the folder is empty, generate a few sample Planet barcode images for demo purposes. - if (Directory.GetFiles(inputFolder, "*.png").Length == 0) + // Generate sample Planet barcodes (5 samples) + for (int i = 1; i <= 5; i++) { - GenerateSampleBarcodes(inputFolder); + string codeText = $"PLANET{i:D3}"; + string filePath = Path.Combine(imageFolder, $"planet_{i}.png"); + + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Planet, codeText)) + { + // Save as PNG + generator.Save(filePath, BarCodeImageFormat.Png); + } + + imageFiles.Add(filePath); } - // Initialise a StringBuilder to construct the CSV content. - var csvBuilder = new StringBuilder(); - csvBuilder.AppendLine("FileName,CodeText"); + // Prepare CSV report file (outside the image folder) + string csvPath = Path.Combine(Path.GetTempPath(), "PlanetReport_" + Guid.NewGuid().ToString("N") + ".csv"); - // Iterate over each PNG file in the input folder. - foreach (string filePath in Directory.GetFiles(inputFolder, "*.png")) + using (StreamWriter writer = new StreamWriter(csvPath, false)) { - // Verify the file still exists (defensive check). - if (!File.Exists(filePath)) - { - Console.WriteLine($"File not found: {filePath}"); - continue; - } + // Write CSV header + writer.WriteLine("FileName,CodeText,CodeType,Confidence,ReadingQuality,Angle"); - // Use BarCodeReader configured for the Planet symbology to decode the image. - using (var reader = new BarCodeReader(filePath, DecodeType.Planet)) + // Process each image file + foreach (string file in imageFiles) { - var results = reader.ReadBarCodes(); - - // If no barcode was detected, write an empty entry for this file. - if (results.Length == 0) + if (!File.Exists(file)) { - csvBuilder.AppendLine($"{Path.GetFileName(filePath)},"); + Console.WriteLine($"File not found: {file}"); continue; } - // Write each detected barcode to the CSV (Planet typically yields a single result). - foreach (var result in results) + try { - string codeText = result.CodeText ?? string.Empty; - - // Escape commas in the decoded text to preserve CSV structure. - if (codeText.Contains(",")) + // Initialize reader for Planet symbology + using (BarCodeReader reader = new BarCodeReader(file, DecodeType.Planet)) { - codeText = $"\"{codeText}\""; + BarCodeResult[] results = reader.ReadBarCodes(); + + if (results.Length == 0) + { + // No barcode detected; write a line indicating empty result + writer.WriteLine($"{Path.GetFileName(file)},,,0,0,0"); + continue; + } + + // Write a CSV line for each detected barcode + foreach (BarCodeResult result in results) + { + // Extract region rectangle and angle + var bounds = result.Region.Rectangle; + double angle = result.Region.Angle; + + // Build CSV line with escaped fields + string line = $"{Path.GetFileName(file)},{EscapeCsv(result.CodeText)},{EscapeCsv(result.CodeTypeName)},{result.Confidence},{result.ReadingQuality},{angle}"; + writer.WriteLine(line); + } } - - csvBuilder.AppendLine($"{Path.GetFileName(filePath)},{codeText}"); + } + catch (ArgumentException ex) + { + // Image loading failed or unsupported format; skip file + Console.WriteLine($"Skipping file {Path.GetFileName(file)}: {ex.Message}"); + } + catch (Exception ex) + { + // Unexpected error; report and continue + Console.WriteLine($"Error processing file {Path.GetFileName(file)}: {ex.Message}"); } } } - // Attempt to write the accumulated CSV data to the output file. - try - { - File.WriteAllText(outputCsv, csvBuilder.ToString()); - Console.WriteLine($"Report generated: {outputCsv}"); - } - catch (Exception ex) - { - Console.WriteLine($"Failed to write CSV report: {ex.Message}"); - } + Console.WriteLine($"CSV report generated at: {csvPath}"); + // Cleanup: optionally delete the temporary image folder + // Directory.Delete(imageFolder, true); } - /// - /// Generates a set of sample Planet barcode images in the specified folder. - /// This helper is used only when the input directory is initially empty. - /// - /// The directory where sample PNG files will be saved. - private static void GenerateSampleBarcodes(string folder) + // Helper to escape CSV fields containing commas or quotes + private static string EscapeCsv(string field) { - // Sample texts to encode into Planet barcodes. - string[] sampleTexts = { "12345", "9876543210", "ABCDEF", "00112233", "9999999999" }; - - for (int i = 0; i < sampleTexts.Length; i++) + if (field == null) + return ""; + if (field.Contains(",") || field.Contains("\"") || field.Contains("\n")) { - string text = sampleTexts[i]; - string fileName = Path.Combine(folder, $"Planet_{i + 1}.png"); - - // Create a Planet barcode generator for the current sample text. - using (var generator = new BarcodeGenerator(EncodeTypes.Planet, text)) - { - // Optional appearance adjustments. - generator.Parameters.Barcode.XDimension.Point = 2f; - 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; - - // Save the generated barcode as a PNG image. - generator.Save(fileName, BarCodeImageFormat.Png); - } + string escaped = field.Replace("\"", "\"\""); + return $"\"{escaped}\""; } - - Console.WriteLine($"Generated {sampleTexts.Length} sample Planet barcode images in '{folder}'."); + return field; } } \ No newline at end of file diff --git a/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-domestic-barcodes-from-mixed-format-folder-and-generate-excel-report.cs b/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-domestic-barcodes-from-mixed-format-folder-and-generate-excel-report.cs index 0aae377..9d2eabf 100644 --- a/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-domestic-barcodes-from-mixed-format-folder-and-generate-excel-report.cs +++ b/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-domestic-barcodes-from-mixed-format-folder-and-generate-excel-report.cs @@ -1,144 +1,123 @@ // Title: Batch decode Swiss Post Parcel barcodes and generate Excel report -// Description: Demonstrates how to decode Swiss Post Parcel domestic barcodes from image files in a folder and compile the results into an Excel spreadsheet. -// Category-Description: This example belongs to the Aspose.BarCode batch processing category, illustrating the use of BarcodeGenerator, BarCodeReader, and Aspose.Cells to generate barcode images, perform bulk decoding, and export results to Excel. Typical use cases include processing large sets of shipping labels, validating barcode data, and creating reports for logistics operations. Developers often need to combine barcode generation, recognition, and spreadsheet output in automated workflows. +// Description: Demonstrates generating sample Swiss Post Parcel barcodes, decoding them in batch, and exporting the results to an Excel file. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It shows how to use BarcodeGenerator to create barcodes, BarCodeReader to decode them, and Aspose.Cells to build a spreadsheet report. Typical use cases include processing folders with mixed‑format images, extracting barcode data, and summarizing results for downstream systems. Developers often need to combine barcode handling with reporting utilities, making this pattern common in logistics and inventory applications. // Prompt: Perform batch decoding of Swiss Post Parcel domestic barcodes from a mixed‑format folder and generate an Excel report. -// Tags: swisspostparcel, decoding, excel, aspose.barcode, aspose.cells +// Tags: swisspostparcel, barcode, batch-decoding, excel, aspose.barcode, aspose.cells, report using System; using System.IO; using System.Collections.Generic; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Cells; -using Aspose.Drawing; -using Aspose.Drawing.Imaging; +using Aspose.Cells.Drawing; -/// -/// Example program that generates sample Swiss Post Parcel barcodes, decodes them in bulk, -/// and writes the decoding results to an Excel report. -/// -class Program +namespace BatchSwissPostDecode { /// - /// Entry point of the application. + /// Demonstrates batch generation, decoding, and reporting of Swiss Post Parcel barcodes. /// - /// Command‑line arguments (not used). - static void Main(string[] args) + class Program { - // -------------------------------------------------------------------- - // Define source folder for barcode images and destination path for report - // -------------------------------------------------------------------- - string baseFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); - string reportPath = Path.Combine(Directory.GetCurrentDirectory(), "SwissPostParcelReport.xlsx"); - - // Ensure the barcode folder exists - if (!Directory.Exists(baseFolder)) + // Simple DTO to hold decoding results + private class DecodedInfo { - Directory.CreateDirectory(baseFolder); + public string FilePath { get; set; } + public string CodeType { get; set; } + public string CodeText { get; set; } } - // -------------------------------------------------------------- - // Sample data representing Swiss Post Parcel barcode values - // -------------------------------------------------------------- - var sampleData = new List - { - "1234567890123456", - "9876543210987654", - "5555555555555555" - }; - - // -------------------------------------------------------------- - // Generate PNG barcode images for each sample value (if not already present) - // -------------------------------------------------------------- - foreach (var codeText in sampleData) + /// + /// Entry point. Generates sample barcodes, decodes them, and creates an Excel report. + /// + /// Command‑line arguments (not used). + static void Main(string[] args) { - string filePath = Path.Combine(baseFolder, $"SwissPost_{codeText}.png"); - if (File.Exists(filePath)) - continue; - - // Resolve EncodeTypes.SwissPostParcel via reflection (API may not expose it directly) - var encodeField = typeof(EncodeTypes).GetField("SwissPostParcel"); - if (encodeField == null) + // Create a unique temporary folder for the sample files + string tempFolder = Path.Combine(Path.GetTempPath(), "BatchSwissPost_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempFolder); + + // ----------------------------------------------------------------- + // Generate a few sample Swiss Post Parcel barcode images + // ----------------------------------------------------------------- + List barcodeFiles = new List(); + for (int i = 0; i < 5; i++) { - Console.WriteLine("EncodeTypes does not contain SwissPostParcel. Skipping generation."); - continue; - } - BaseEncodeType encodeType = (BaseEncodeType)encodeField.GetValue(null); + string filePath = Path.Combine(tempFolder, $"SwissPostParcel_{i}.png"); + string codeText = $"12345678{i}"; // simple varying code text - using (BarcodeGenerator generator = new BarcodeGenerator(encodeType, codeText)) - { - // Save the generated barcode as a PNG file - generator.Save(filePath, BarCodeImageFormat.Png); - } - } + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, codeText)) + { + // Optional: adjust barcode appearance if needed + // generator.Parameters.Barcode.XDimension.Point = 2f; - // -------------------------------------------------------------- - // Prepare a collection to store decoding results - // -------------------------------------------------------------- - var results = new List(); + // Save directly to PNG file + generator.Save(filePath, BarCodeImageFormat.Png); + } - // -------------------------------------------------------------- - // Scan the folder for PNG files and decode each using SwissPostParcel symbology - // -------------------------------------------------------------- - var imageFiles = Directory.GetFiles(baseFolder, "*.png"); - foreach (var imageFile in imageFiles) - { - if (!File.Exists(imageFile)) - continue; + barcodeFiles.Add(filePath); + } - BaseDecodeType decodeType = DecodeType.SwissPostParcel; - using (BarCodeReader reader = new BarCodeReader(imageFile, decodeType)) + // ----------------------------------------------------------------- + // Decode the generated barcodes + // ----------------------------------------------------------------- + List decodedResults = new List(); + foreach (string file in barcodeFiles) { - foreach (var result in reader.ReadBarCodes()) + if (!File.Exists(file)) + { + Console.WriteLine($"File not found, skipping: {file}"); + continue; + } + + try { - results.Add(new DecodeResult + using (BarCodeReader reader = new BarCodeReader(file, DecodeType.SwissPostParcel)) { - FileName = Path.GetFileName(imageFile), - CodeText = result.CodeText ?? string.Empty, - Symbology = result.CodeTypeName, - Confidence = result.Confidence.ToString() - }); + foreach (var result in reader.ReadBarCodes()) + { + decodedResults.Add(new DecodedInfo + { + FilePath = file, + CodeType = result.CodeTypeName, + CodeText = result.CodeText + }); + } + } + } + catch (ArgumentException ex) + { + // Handles "Image loading failed" or other argument issues + Console.WriteLine($"Failed to read '{file}': {ex.Message}"); } } - } - - // -------------------------------------------------------------- - // Create an Excel workbook and populate it with the decoding data - // -------------------------------------------------------------- - using (Workbook workbook = new Workbook()) - { - Worksheet sheet = workbook.Worksheets[0]; - - // Header row - sheet.Cells[0, 0].PutValue("File Name"); - sheet.Cells[0, 1].PutValue("Code Text"); - sheet.Cells[0, 2].PutValue("Symbology"); - sheet.Cells[0, 3].PutValue("Confidence"); - // Data rows - for (int i = 0; i < results.Count; i++) + // ----------------------------------------------------------------- + // Create an Excel report with the decoding results + // ----------------------------------------------------------------- + string reportPath = Path.Combine(tempFolder, "SwissPostParcelReport.xlsx"); + using (Workbook workbook = new Workbook()) { - var r = results[i]; - int row = i + 1; - sheet.Cells[row, 0].PutValue(r.FileName); - sheet.Cells[row, 1].PutValue(r.CodeText); - sheet.Cells[row, 2].PutValue(r.Symbology); - sheet.Cells[row, 3].PutValue(r.Confidence); + Worksheet sheet = workbook.Worksheets[0]; + // Header row + sheet.Cells[0, 0].PutValue("File"); + sheet.Cells[0, 1].PutValue("Barcode Type"); + sheet.Cells[0, 2].PutValue("Code Text"); + + int row = 1; + foreach (var info in decodedResults) + { + sheet.Cells[row, 0].PutValue(info.FilePath); + sheet.Cells[row, 1].PutValue(info.CodeType); + sheet.Cells[row, 2].PutValue(info.CodeText); + row++; + } + + workbook.Save(reportPath, SaveFormat.Xlsx); } - // Save the workbook to the specified path - workbook.Save(reportPath, SaveFormat.Xlsx); + Console.WriteLine($"Batch decoding completed. Report saved to: {reportPath}"); } - - Console.WriteLine($"Decoding completed. Report saved to: {reportPath}"); - } - - // Simple DTO to hold decoding information - private class DecodeResult - { - public string FileName { get; set; } - public string CodeText { get; set; } - public string Symbology { get; set; } - public string Confidence { get; set; } } } \ No newline at end of file diff --git a/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-international-barcodes-from-network-share-and-handle-checksum-mismatches.cs b/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-international-barcodes-from-network-share-and-handle-checksum-mismatches.cs index a6e8d43..b4c23fb 100644 --- a/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-international-barcodes-from-network-share-and-handle-checksum-mismatches.cs +++ b/postal-barcode-types/perform-batch-decoding-of-swiss-post-parcel-international-barcodes-from-network-share-and-handle-checksum-mismatches.cs @@ -1,112 +1,119 @@ // Title: Batch decode Swiss Post Parcel barcodes with checksum validation -// Description: Demonstrates how to read multiple Swiss Post Parcel barcodes from a folder (simulating a network share), validate checksums, and report mismatches. -// Category-Description: This example belongs to the barcode recognition and generation category of Aspose.BarCode for .NET. It showcases using BarCodeReader for batch decoding, configuring checksum validation, and using BarcodeGenerator to create sample barcodes. Developers working with bulk barcode processing, validation, and integration with file systems commonly use these APIs. +// Description: Demonstrates generating Swiss Post Parcel barcode images, storing them in a temporary network‑share‑like folder, and batch decoding them while detecting checksum mismatches. +// 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 batch decoding, and checksum validation settings. Developers working with postal barcode automation, bulk image processing, or quality‑control scenarios can use these APIs to validate barcode data and handle errors efficiently. // Prompt: Perform batch decoding of Swiss Post Parcel international barcodes from a network share and handle checksum mismatches. -// Tags: swisspostparcel, batch decoding, checksum validation, barcodereader, barcodegenerator, console output +// Tags: swisspostparcel, barcode generation, barcode recognition, checksum validation, batch processing, aspnet.barcode, aspose.barcode using System; using System.IO; +using System.Collections.Generic; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Example program that batch‑processes Swiss Post Parcel barcodes from a folder, -/// validates their checksums, and outputs the results to the console. +/// Entry point for the batch Swiss Post Parcel barcode generation and decoding example. /// class Program { /// - /// Entry point. Scans a folder for PNG images, reads Swiss Post Parcel barcodes, - /// validates checksums, and reports successful reads or mismatches. + /// Generates sample Swiss Post Parcel barcodes, saves them to a temporary folder, + /// then reads them back in a batch, reporting success or checksum mismatches. /// static void Main() { - // Define the folder that simulates a network share. - // For the purpose of this self‑contained example we use a local folder. - string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + // Create a unique temporary folder to simulate a network share + string tempFolder = Path.Combine(Path.GetTempPath(), "BatchSwissPost_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempFolder); - // Ensure the folder exists. - if (!Directory.Exists(folderPath)) + // Sample Swiss Post Parcel barcode texts (some with intentional checksum errors) + var barcodeTexts = new List { - Directory.CreateDirectory(folderPath); + "1234567890123", // assume valid + "9876543210987", // assume valid + "1111111111111" // assume invalid checksum + }; + + // Generate barcode images and collect file paths + var generatedFiles = new List(); + foreach (var text in barcodeTexts) + { + string filePath = Path.Combine(tempFolder, $"SwissPost_{text}.png"); + using (var generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, text)) + { + // Example of setting a barcode property (optional) + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Save(filePath, BarCodeImageFormat.Png); + } + generatedFiles.Add(filePath); } - // Seed a few sample Swiss Post Parcel barcodes if the folder is empty. - SeedSampleBarcodes(folderPath); + Console.WriteLine($"Generated {generatedFiles.Count} barcode images in: {tempFolder}"); + Console.WriteLine(); - // Retrieve all PNG image files in the folder. - string[] imageFiles = Directory.GetFiles(folderPath, "*.png"); - foreach (string imageFile in imageFiles) + // Batch decode the generated images + foreach (var file in generatedFiles) { - // Verify the file exists before processing. - if (!File.Exists(imageFile)) + if (!File.Exists(file)) { - Console.WriteLine($"File not found: {imageFile}"); + Console.WriteLine($"File not found, skipping: {file}"); continue; } - // Create a reader configured for Swiss Post Parcel barcodes. - using (BarCodeReader reader = new BarCodeReader(imageFile, DecodeType.SwissPostParcel)) + try { - // Enable checksum validation. - reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; - - // Disallow recognition of barcodes with incorrect checksums. - reader.QualitySettings.AllowIncorrectBarcodes = false; - - // Read all barcodes from the image. - BarCodeResult[] results = reader.ReadBarCodes(); - - if (results.Length == 0) + using (var reader = new BarCodeReader(file, DecodeType.SwissPostParcel)) { - Console.WriteLine($"No barcode detected in file: {Path.GetFileName(imageFile)}"); - continue; - } + // Enable checksum validation + reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; + // Allow reading even if checksum is wrong (so we can detect mismatch) + reader.QualitySettings.AllowIncorrectBarcodes = true; - // Process each detected barcode. - foreach (BarCodeResult result in results) - { - // If CodeText is null or empty, the checksum likely failed. - if (string.IsNullOrEmpty(result.CodeText)) + var results = reader.ReadBarCodes(); + if (results.Length == 0) { - Console.WriteLine($"Checksum mismatch in file: {Path.GetFileName(imageFile)}"); + Console.WriteLine($"No barcode detected in file: {Path.GetFileName(file)}"); + continue; } - else + + foreach (var result in results) { - Console.WriteLine($"File: {Path.GetFileName(imageFile)} | Type: {result.CodeTypeName} | Text: {result.CodeText}"); + // If CodeText is null or empty, treat it as a checksum mismatch + if (string.IsNullOrEmpty(result.CodeText)) + { + Console.WriteLine($"[Checksum Mismatch] File: {Path.GetFileName(file)}"); + } + else + { + Console.WriteLine($"[Success] File: {Path.GetFileName(file)}"); + Console.WriteLine($" Type : {result.CodeTypeName}"); + Console.WriteLine($" CodeText: {result.CodeText}"); + } } } } - } - } + catch (ArgumentException ex) when (ex.Message.Contains("Image loading failed")) + { + Console.WriteLine($"Unable to load image (skipped): {Path.GetFileName(file)}"); + } + catch (Exception ex) + { + Console.WriteLine($"Unexpected error processing {Path.GetFileName(file)}: {ex.Message}"); + } - // Generates a few sample Swiss Post Parcel barcodes if none exist. - private static void SeedSampleBarcodes(string folderPath) - { - // Check if there are already PNG files. - if (Directory.GetFiles(folderPath, "*.png").Length > 0) - return; + Console.WriteLine(); + } - // Sample data for Swiss Post Parcel barcodes. - string[] sampleTexts = new[] + // Cleanup: delete temporary folder and its contents + try { - "1234567890123456", // Example valid code (replace with real format as needed) - "9876543210987654", - "5555555555555555" - }; - - // Create a barcode image for each sample text. - for (int i = 0; i < sampleTexts.Length; i++) + Directory.Delete(tempFolder, true); + Console.WriteLine("Temporary files cleaned up."); + } + catch (Exception ex) { - string filePath = Path.Combine(folderPath, $"Sample{i + 1}.png"); - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.SwissPostParcel, sampleTexts[i])) - { - // Optional: adjust barcode appearance. - generator.Parameters.Barcode.XDimension.Point = 2f; - generator.Save(filePath, BarCodeImageFormat.Png); - } + Console.WriteLine($"Failed to delete temporary folder: {ex.Message}"); } } } \ No newline at end of file