diff --git a/one-dimensional-barcode-types/adjust-barcode-text-font-to-arial-size-12-pt-and-center-text-beneath-bars.cs b/one-dimensional-barcode-types/adjust-barcode-text-font-to-arial-size-12-pt-and-center-text-beneath-bars.cs index 0a9425f..1abdbec 100644 --- a/one-dimensional-barcode-types/adjust-barcode-text-font-to-arial-size-12-pt-and-center-text-beneath-bars.cs +++ b/one-dimensional-barcode-types/adjust-barcode-text-font-to-arial-size-12-pt-and-center-text-beneath-bars.cs @@ -1,39 +1,38 @@ -// Title: Adjust barcode text font and alignment -// Description: Demonstrates how to set the barcode's human‑readable text to Arial 12 pt and center it beneath the bars. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to customize CodeTextParameters such as font, size, alignment, and location. It uses the BarcodeGenerator class together with EncodeTypes and CodeTextParameters to produce barcodes with tailored human‑readable text. Developers often need to modify these settings to match branding guidelines or improve readability in printed materials. +// Title: Generate Code128 barcode with centered Arial text +// Description: Demonstrates creating a Code128 barcode, placing human‑readable text below the bars, centering it, and applying an Arial‑like 12 pt font. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator, EncodeTypes, and CodeTextParameters to produce barcodes with customized human‑readable text. Typical use cases include product labeling, inventory tracking, and shipping documents where readable text must accompany the barcode. Developers often need to adjust text position, alignment, and font styling to meet branding or regulatory requirements. // Prompt: Adjust barcode text font to Arial, size 12 pt, and center the text beneath the bars. -// Tags: barcode, code128, font, alignment, textlocation, generation, aspnet, aspose.barcode +// Tags: code128, barcode generation, text formatting, png output, aspose.barcode, font settings -using System; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Demonstrates adjusting barcode text font to Arial 12 pt and centering it below the bars. +/// Example program that creates a Code128 barcode with centered, Arial‑style text placed below the bars. /// class Program { /// - /// Generates a Code128 barcode with customized text appearance and saves it as PNG. + /// Entry point that configures barcode parameters and saves the image as PNG. /// static void Main() { - // Initialize a barcode generator for Code128 with the sample value "1234567890" - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Initialize a BarcodeGenerator for Code128 with the sample value "123456" + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) { - // Configure the human‑readable text font: Arial, 12 pt - generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Arial"; - generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 12f; + // Position the human‑readable text below the barcode bars + generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below; - // Align the text to the center and position it below the barcode bars + // Align the text to the center of the barcode generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center; - generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below; + + // Set the font to Helvetica (Arial equivalent) with a size of 12 points + generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Helvetica"; + generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 12f; // Save the generated barcode image to a PNG file generator.Save("barcode.png"); } - - // Inform the user that the barcode has been created - Console.WriteLine("Barcode generated: barcode.png"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/align-barcode-text-to-center-and-enable-automatic-scaling-to-fit-within-narrow-barcode-width.cs b/one-dimensional-barcode-types/align-barcode-text-to-center-and-enable-automatic-scaling-to-fit-within-narrow-barcode-width.cs index 60fa854..c8e34be 100644 --- a/one-dimensional-barcode-types/align-barcode-text-to-center-and-enable-automatic-scaling-to-fit-within-narrow-barcode-width.cs +++ b/one-dimensional-barcode-types/align-barcode-text-to-center-and-enable-automatic-scaling-to-fit-within-narrow-barcode-width.cs @@ -1,47 +1,42 @@ -// Title: Center-aligned barcode text with automatic scaling -// Description: Demonstrates how to center the human‑readable text of a Code128 barcode and enable automatic scaling to fit a narrow image width. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and related parameter classes to customize barcode appearance. Typical scenarios include creating compact barcodes for limited‑space labels while preserving readability. Developers often need to adjust text alignment, font sizing, and image dimensions to meet layout constraints. +// Title: Center barcode text and enable auto scaling for narrow width +// Description: Demonstrates how to center the human‑readable text of a Code128 barcode and automatically scale the image to fit a specified narrow width. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and barcode parameters such as CodeTextParameters.Alignment and AutoSizeMode. Developers often need to adjust text alignment and automatically resize barcodes for tight layout constraints in documents, labels, or web pages. The snippet shows typical steps for configuring alignment, scaling mode, and image dimensions before saving the barcode image. // Prompt: Align barcode text to center and enable automatic scaling to fit within narrow barcode width. -// Tags: code128, text alignment, auto scaling, png, aspose.barcode, barcode generation +// Tags: code128, barcode, text alignment, autoscaling, image size, aspnet, aspose.barcode, generation, png -using System; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; /// -/// Generates a Code128 barcode with centered human‑readable text and automatic scaling -/// to fit a narrow image width, then saves it as a PNG file. +/// Generates a Code128 barcode with centered human‑readable text and +/// automatically scales the image to fit a narrow width. /// class Program { /// - /// Entry point of the example. Creates a barcode, configures text alignment and scaling, - /// and writes the result to "barcode.png". + /// Entry point of the example. Configures barcode parameters, + /// applies text alignment and auto‑scaling, then saves the image. /// static void Main() { - // Initialize a barcode generator for the Code128 symbology. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) + // Initialize a barcode generator for Code128 with sample text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Set the data that will be encoded in the barcode. - generator.CodeText = "1234567890"; + // Center the human‑readable text beneath the barcode + generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center; - // Configure automatic scaling (interpolation) so the barcode adapts to the image size. + // Enable automatic scaling to fit a narrow width using interpolation generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - // Define a narrow image width (150 points) and a suitable height (50 points). + // Set the desired image width (points); adjust as needed for layout constraints generator.Parameters.ImageWidth.Point = 150f; - generator.Parameters.ImageHeight.Point = 50f; - // Center‑align the human‑readable text beneath the barcode. - generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center; - - // Enable automatic font sizing so the text scales proportionally with the barcode. - generator.Parameters.Barcode.CodeTextParameters.FontMode = FontMode.Auto; + // Set the desired image height (points); optional—omit to preserve aspect ratio + generator.Parameters.ImageHeight.Point = 50f; - // Save the generated barcode image to a PNG file. - generator.Save("barcode.png"); + // Save the generated barcode image; format inferred from file extension + generator.Save("centered_scaled.png"); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/align-barcode-text-to-center-enable-automatic-scaling-and-generate-image-suitable-for-narrow-receipt-printing.cs b/one-dimensional-barcode-types/align-barcode-text-to-center-enable-automatic-scaling-and-generate-image-suitable-for-narrow-receipt-printing.cs index ef32259..1bcbc0a 100644 --- a/one-dimensional-barcode-types/align-barcode-text-to-center-enable-automatic-scaling-and-generate-image-suitable-for-narrow-receipt-printing.cs +++ b/one-dimensional-barcode-types/align-barcode-text-to-center-enable-automatic-scaling-and-generate-image-suitable-for-narrow-receipt-printing.cs @@ -1,56 +1,63 @@ -// Title: Center-aligned Code128 barcode with auto scaling for receipt printing -// Description: Generates a Code128 barcode with centered human‑readable text, automatic scaling, and a narrow image suitable for receipt printers. -// Category-Description: This example demonstrates Aspose.BarCode generation features such as setting image dimensions, resolution, text alignment, and auto‑scaling. It uses the BarcodeGenerator, EncodeTypes, and related parameter classes to create barcodes for point‑of‑sale scenarios where narrow, high‑resolution images are required. Developers often need to customize size, DPI, and text appearance for receipt or label printing. +// Title: Center-aligned Code128 barcode with auto-scaling for receipt printing +// Description: Demonstrates how to generate a narrow receipt‑friendly Code128 barcode, centering the human‑readable text and enabling automatic scaling to fit a specific image width. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating use of BarcodeGenerator, EncodeTypes, and image formatting classes. Typical use cases include creating barcodes for point‑of‑sale receipts, tickets, or labels where space is limited. Developers often need to control text alignment, scaling mode, and output dimensions to produce clear, printable barcodes. // Prompt: Align barcode text to center, enable automatic scaling, and generate image suitable for narrow receipt printing. -// Tags: code128, barcode, auto-scaling, receipt, png, aspose.barcode, generation +// Tags: code128, alignment, autoscaling, png, barcodegenerator, aspose.barcode, aspose.drawing using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Demonstrates how to generate a narrow, center‑aligned Code128 barcode with automatic scaling, -/// suitable for receipt printers. +/// Generates a Code128 barcode image that is centered, auto‑scaled, and sized for narrow receipt printers. /// class Program { /// - /// Entry point of the example. Creates a barcode, configures scaling and alignment, - /// and saves the result as a PNG image. + /// Entry point of the example. Creates the barcode, configures alignment and scaling, and saves it as a PNG file. /// static void Main() { - // Text to be encoded in the barcode. + // Define the barcode content and output file name const string codeText = "1234567890"; + const string outputPath = "receipt_barcode.png"; - // Initialize the barcode generator for Code128 symbology. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // Ensure the output directory exists (creates it if missing) + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(outputDir)) { - // Enable automatic scaling (interpolation) to fit the target image size. - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; + Directory.CreateDirectory(outputDir); + } - // Define a narrow receipt width and modest height (points). - generator.Parameters.ImageWidth.Point = 200f; // Width in points. - generator.Parameters.ImageHeight.Point = 50f; // Height in points. + // Initialize the barcode generator with Code128 symbology + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + { + // Center the human‑readable text beneath the barcode + generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center; + generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below; - // Set the printer resolution typical for receipt printers (203 DPI). - generator.Parameters.Resolution = 203f; + // Enable automatic scaling (interpolation) to fit the target width + generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - // Center‑align the human‑readable text beneath the barcode. - generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center; + // Set the desired image width for a typical receipt printer (≈2.78 in) + generator.Parameters.ImageWidth.Point = 200f; + // Height is auto‑calculated based on content and scaling mode - // Ensure the text font scales automatically with the barcode size. - generator.Parameters.Barcode.CodeTextParameters.FontMode = FontMode.Auto; + // Use a small X‑dimension so the barcode fits within the narrow width + generator.Parameters.Barcode.XDimension.Point = 1f; - // Set barcode bar color to black and background to white. + // Define barcode and background colors (black on white) generator.Parameters.Barcode.BarColor = Color.Black; generator.Parameters.BackColor = Color.White; - // Save the generated barcode image to a PNG file. - const string outputPath = "receipt_barcode.png"; - generator.Save(outputPath); - Console.WriteLine($"Barcode saved to {outputPath}"); + // Save the generated barcode as a PNG image + generator.Save(outputPath, BarCodeImageFormat.Png); } + + // Inform the user where the image was saved + Console.WriteLine($"Barcode image saved to: {Path.GetFullPath(outputPath)}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/align-barcode-text-to-left-enable-automatic-scaling-and-generate-image-suitable-for-narrow-column-layout.cs b/one-dimensional-barcode-types/align-barcode-text-to-left-enable-automatic-scaling-and-generate-image-suitable-for-narrow-column-layout.cs index a20a03d..85ead16 100644 --- a/one-dimensional-barcode-types/align-barcode-text-to-left-enable-automatic-scaling-and-generate-image-suitable-for-narrow-column-layout.cs +++ b/one-dimensional-barcode-types/align-barcode-text-to-left-enable-automatic-scaling-and-generate-image-suitable-for-narrow-column-layout.cs @@ -1,8 +1,8 @@ -// Title: Align Code128 barcode text left with auto‑scaling for narrow column layout -// Description: Demonstrates how to left‑align human‑readable text, enable automatic scaling, and set image size for a narrow column using Aspose.BarCode. -// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and Parameters classes to customize barcode appearance. Typical scenarios include creating compact barcodes for reports, invoices, or mobile screens where space is limited. Developers often need to control text alignment, scaling mode, and image dimensions to fit specific layout constraints. +// Title: Align barcode text left with auto scaling for narrow column +// Description: Demonstrates how to left‑align the human‑readable text of a Code128 barcode, enable automatic scaling, and set image dimensions for a narrow column layout. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and barcode parameters such as CodeTextParameters, AutoSizeMode, and image size settings. Typical use cases include creating compact barcodes for reports, invoices, or mobile screens where space is limited. Developers often need to control text alignment and scaling to fit barcodes into constrained layouts. // Prompt: Align barcode text to left, enable automatic scaling, and generate image suitable for narrow column layout. -// Tags: code128, alignment, autoscaling, png, barcodegenerator, parameters, aspose.barcode, imagegeneration +// Tags: code128, barcode, text-alignment, autoscaling, narrow-layout, png, aspose.barcode, generation using System; using Aspose.BarCode; @@ -10,36 +10,34 @@ using Aspose.Drawing; /// -/// Generates a Code128 barcode with left‑aligned text, automatic scaling, and a compact image size. +/// Generates a Code128 barcode with left‑aligned text, automatic scaling, and a narrow image size. /// class Program { /// - /// Entry point that creates and saves the barcode image. + /// Entry point that creates, configures, and saves the barcode image. /// static void Main() { - // Initialize a barcode generator for Code128 with the sample value. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Initialize a barcode generator for Code128 with sample data + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789")) { - // Enable automatic scaling using interpolation to fit the specified dimensions. - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - - // Define image size (points) suitable for a narrow column layout. - generator.Parameters.ImageWidth.Point = 150f; - generator.Parameters.ImageHeight.Point = 50f; - - // Align the human‑readable text to the left side of the barcode. + // Set human‑readable text alignment to the left side of the barcode generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Left; - // Optional: adjust the module (X) dimension for clearer rendering at small sizes. - generator.Parameters.Barcode.XDimension.Point = 2f; + // Enable automatic scaling using interpolation to fit a narrow column + generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - // Save the generated barcode as a PNG file. - generator.Save("barcode.png"); - } + // Define a narrow image width and a suitable height (points) + generator.Parameters.ImageWidth.Point = 150f; // narrow width + generator.Parameters.ImageHeight.Point = 50f; // appropriate height - // Inform the user that the image has been created. - Console.WriteLine("Barcode image generated: barcode.png"); + // Generate the barcode image as a bitmap + using (Aspose.Drawing.Bitmap image = generator.GenerateBarCodeImage()) + { + // Save the generated image as a PNG file + generator.Save("barcode.png"); + } + } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/align-barcode-text-to-right-enable-automatic-scaling-and-generate-image-for-narrow-label-printing.cs b/one-dimensional-barcode-types/align-barcode-text-to-right-enable-automatic-scaling-and-generate-image-for-narrow-label-printing.cs index 109d010..aad2ce3 100644 --- a/one-dimensional-barcode-types/align-barcode-text-to-right-enable-automatic-scaling-and-generate-image-for-narrow-label-printing.cs +++ b/one-dimensional-barcode-types/align-barcode-text-to-right-enable-automatic-scaling-and-generate-image-for-narrow-label-printing.cs @@ -1,51 +1,48 @@ -// Title: Align barcode text to right and generate narrow label image -// Description: Demonstrates how to right‑align human‑readable text, enable automatic scaling, and create a PNG image sized for narrow label printing. -// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, AutoSizeMode, and TextAlignment to produce high‑resolution barcodes for label printers. Developers often need to customize barcode dimensions, scaling, and text alignment for various printing scenarios, such as narrow labels, receipts, or product tags. The snippet shows typical API calls for setting image size, resolution, colors, and saving the result. +// Title: Generate right-aligned Code128 barcode with auto scaling for narrow label printing +// Description: Demonstrates how to create a Code128 barcode, align its human‑readable text to the right, enable automatic scaling, and output a PNG image sized for narrow label printing. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and various Parameters such as AutoSizeMode, image dimensions, XDimension, and CodeTextParameters. Typical use cases include creating compact barcodes for small labels, receipts, or product tags where precise alignment and scaling are required. Developers often need to adjust image size, resolution, and text alignment to meet printing specifications. // Prompt: Align barcode text to right, enable automatic scaling, and generate image for narrow label printing. -// Tags: code128, text-alignment, autoscaling, png, image-generation, aspnet, aspose.barcode +// Tags: code128, barcode generation, auto scaling, text alignment, narrow label, png, aspose.barcode, csharp using System; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; +using Aspose.Drawing; // Required for BarCodeImageFormat enum /// -/// Demonstrates aligning barcode text to the right, enabling automatic scaling, -/// and generating a PNG image suitable for narrow label printing using Aspose.BarCode. +/// Example program that generates a right‑aligned Code128 barcode with automatic scaling, +/// sized for a narrow label and saved as a PNG image. /// class Program { /// - /// Entry point of the example. Creates a Code128 barcode, configures scaling, - /// size, resolution, text alignment, colors, and saves the image. + /// Entry point. Creates the barcode, configures scaling, alignment, and image size, + /// then saves the result to a file. /// static void Main() { - // Initialize a barcode generator for Code128 symbology with sample text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Initialize a BarcodeGenerator for Code128 with the desired code text. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) { - // Enable automatic scaling using interpolation mode. + // Enable automatic scaling using interpolation mode to keep the barcode readable + // when the image size changes. generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - // Set the target image dimensions for a narrow label (150pt width x 50pt height). - generator.Parameters.ImageWidth.Point = 150f; - generator.Parameters.ImageHeight.Point = 50f; + // Set the target image dimensions (in points) suitable for a narrow label. + generator.Parameters.ImageWidth.Point = 150f; // Label width + generator.Parameters.ImageHeight.Point = 50f; // Label height - // Increase resolution to 300 DPI for better print quality. - generator.Parameters.Resolution = 300f; + // Reduce the module (X) dimension to keep the barcode compact on the small label. + generator.Parameters.Barcode.XDimension.Point = 0.5f; // Align the human‑readable text to the right side of the barcode. generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Right; - // Optional: define bar and background colors (black on white). - generator.Parameters.Barcode.BarColor = Color.Black; - generator.Parameters.BackColor = Color.White; + // Increase the resolution to 300 DPI for higher print quality on narrow labels. + generator.Parameters.Resolution = 300f; - // Save the generated barcode image as a PNG file. + // Save the generated barcode as a PNG image. generator.Save("narrow_label.png"); } - - // Output a simple confirmation message. - Console.WriteLine("Barcode image 'narrow_label.png' generated successfully."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/align-barcode-text-to-right-positioning-human-readable-characters-at-far-right-of-image.cs b/one-dimensional-barcode-types/align-barcode-text-to-right-positioning-human-readable-characters-at-far-right-of-image.cs index 7d89bfc..31182f9 100644 --- a/one-dimensional-barcode-types/align-barcode-text-to-right-positioning-human-readable-characters-at-far-right-of-image.cs +++ b/one-dimensional-barcode-types/align-barcode-text-to-right-positioning-human-readable-characters-at-far-right-of-image.cs @@ -1,38 +1,37 @@ -// Title: Align barcode text to the right -// Description: Demonstrates how to position the human‑readable text of a barcode at the far right edge of the generated image using Aspose.BarCode. -// Category-Description: This example belongs to the Aspose.BarCode text formatting category, showing how to control the alignment of human‑readable characters via the CodeTextParameters API. Typical use cases include customizing barcode labels for printing where text placement matters, such as aligning numbers to the right margin. Developers often need to adjust TextAlignment, Font, and other visual properties to meet layout requirements. +// Title: Right-Aligned Human-Readable Text in a Barcode Image +// Description: Demonstrates how to generate a Code128 barcode with the human‑readable text positioned at the far right below the bars. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to customize human‑readable text placement using the BarcodeGenerator, EncodeTypes, CodeLocation, and TextAlignment classes. Typical use cases include creating barcodes for labels, receipts, or packaging where the readable text must be aligned to a specific side of the image. Developers often need to adjust text location and alignment to meet branding or layout requirements. // Prompt: Align barcode text to the right, positioning human‑readable characters at the far right of the image. -// Tags: code128, text-alignment, png, barcodegenerator, codetextparameters +// Tags: barcode, code128, text-alignment, right-align, image, aspose.barcode, generation -using System; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; +using Aspose.Drawing; // Required for Aspose.Drawing.Bitmap if needed /// -/// Generates a Code128 barcode with its human‑readable text aligned to the right side of the image. +/// Generates a Code128 barcode with right‑aligned human‑readable text placed below the bars. /// class Program { /// - /// Entry point of the example. Creates a barcode, sets right alignment for the text, and saves the image. + /// Entry point of the example. Creates the barcode, configures text alignment, and saves the image. /// static void Main() { - // Initialize a barcode generator for Code128 with the sample value "1234567890" - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Initialize a barcode generator for the Code128 symbology. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128)) { - // Set the human‑readable text alignment to the far right of the barcode image - generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Right; + // Set the data to be encoded in the barcode. + generator.CodeText = "123ABC"; - // Define the output file name (PNG format) - string outputFile = "right_aligned.png"; + // Make the human‑readable text visible and position it below the barcode. + generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below; - // Save the generated barcode image to the specified file - generator.Save(outputFile); + // Align the human‑readable text to the far right side of the image. + generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Right; - // Inform the user where the image was saved - Console.WriteLine($"Barcode image saved to: {outputFile}"); + // Save the generated barcode as a PNG image. + generator.Save("right_aligned.png"); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/apply-blue-foreground-color-and-light-gray-background-color-to-improve-printed-barcode-contrast.cs b/one-dimensional-barcode-types/apply-blue-foreground-color-and-light-gray-background-color-to-improve-printed-barcode-contrast.cs index 9623e67..ae35065 100644 --- a/one-dimensional-barcode-types/apply-blue-foreground-color-and-light-gray-background-color-to-improve-printed-barcode-contrast.cs +++ b/one-dimensional-barcode-types/apply-blue-foreground-color-and-light-gray-background-color-to-improve-printed-barcode-contrast.cs @@ -1,8 +1,8 @@ -// Title: Apply custom foreground and background colors to a Code128 barcode -// Description: Demonstrates how to set a blue foreground and light‑gray background for a Code128 barcode using Aspose.BarCode, improving visual contrast for printed labels. -// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating color customization with BarcodeGenerator and its Parameters properties. Developers often need to adjust barcode colors to match branding or enhance readability on various media. The snippet shows typical usage of EncodeTypes, BarCodeImageFormat, and color settings for printable barcode images. +// Title: Apply custom foreground and background colors to a barcode image +// Description: Demonstrates how to set a blue foreground color and a light‑gray background color for a Code128 barcode using Aspose.BarCode, then save it as a PNG file. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to customize barcode appearance with color properties. It uses the BarcodeGenerator class and its Parameters to modify BarColor and BackColor, a common requirement when improving print contrast or matching branding guidelines. Developers often need to adjust these settings for various output formats such as PNG, JPEG, or PDF. // Prompt: Apply blue foreground color and light‑gray background color to improve printed barcode contrast. -// Tags: code128, color, png, barcodegenerator, aspose.barcode +// Tags: barcode, color, foreground, background, code128, png, aspose.barcode, generation using System; using Aspose.BarCode; @@ -10,32 +10,32 @@ using Aspose.Drawing; /// -/// Demonstrates applying custom foreground and background colors to a barcode image. +/// Generates a Code128 barcode with custom foreground and background colors and saves it as a PNG image. /// class Program { /// - /// Generates a Code128 barcode with blue bars on a light‑gray background and saves it as PNG. + /// Entry point of the example. Creates the barcode, applies color settings, and writes the image to disk. /// static void Main() { - // Define the output file path for the generated barcode image + // Define the output file path for the generated barcode image. string outputPath = "barcode.png"; - // Initialize a BarcodeGenerator for Code128 with the sample text "1234567890" + // Initialize a BarcodeGenerator for Code128 with the sample text "1234567890". using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Set the barcode (foreground) color to blue for better contrast + // Set the barcode (foreground) color to blue to enhance visual contrast. generator.Parameters.Barcode.BarColor = Color.Blue; - // Set the image background color to light gray + // Set the image background color to light gray for better readability on print. generator.Parameters.BackColor = Color.LightGray; - // Save the generated barcode as a PNG file at the specified path + // Save the configured barcode as a PNG file at the specified location. generator.Save(outputPath, BarCodeImageFormat.Png); } - // Inform the user that the barcode has been saved - Console.WriteLine($"Barcode saved to {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/one-dimensional-barcode-types/apply-custom-background-color-named-lightcoral-to-match-ui-theme-requirements.cs b/one-dimensional-barcode-types/apply-custom-background-color-named-lightcoral-to-match-ui-theme-requirements.cs index 856a098..267627e 100644 --- a/one-dimensional-barcode-types/apply-custom-background-color-named-lightcoral-to-match-ui-theme-requirements.cs +++ b/one-dimensional-barcode-types/apply-custom-background-color-named-lightcoral-to-match-ui-theme-requirements.cs @@ -1,8 +1,8 @@ -// Title: Apply LightCoral Background to Barcode Image -// Description: Demonstrates setting a custom background color for a generated barcode and saving it as PNG. -// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to customize visual appearance using BarcodeGenerator and its Parameters. Typical use cases include branding, UI theming, and improving readability by adjusting background and bar colors. Developers often need to modify colors, sizes, and formats when integrating barcodes into applications. +// Title: Apply LightCoral background to a Code128 barcode image +// Description: Demonstrates how to set a custom LightCoral background color for a Code128 barcode and save it as a PNG file. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and Parameters to customize barcode appearance. Typical use cases include branding, UI theming, and visual consistency across applications. Developers often need to adjust colors, sizes, and formats when integrating barcodes into user interfaces or printed materials. // Prompt: Apply a custom background color named “LightCoral” to match UI theme requirements. -// Tags: barcode symbology, image generation, png output, background color, aspose.barcode, aspose.drawing +// Tags: barcode symbology, background color, png, aspose.barcode, aspose.drawing using System; using Aspose.BarCode; @@ -10,32 +10,32 @@ using Aspose.Drawing; /// -/// Generates a Code128 barcode with a LightCoral background and saves it as a PNG file. +/// Generates a Code128 barcode with a LightCoral background and saves it as a PNG image. /// class Program { /// - /// Entry point of the example. Creates a barcode, applies custom colors, and writes the image to disk. + /// Entry point of the example. Creates the barcode, applies the custom background, and writes the file. /// static void Main() { - // Initialize the barcode generator with Code128 symbology and sample data. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) - { - // Set the background color to LightCoral to match the UI theme. - generator.Parameters.BackColor = Color.LightCoral; - - // Set the bar (foreground) color to Black for good contrast. - generator.Parameters.Barcode.BarColor = Color.Black; + // Define the output file path for the generated barcode image. + string outputPath = "barcode.png"; - // Define the output file path for the PNG image. - string outputPath = "barcode_lightcoral.png"; + // Initialize a BarcodeGenerator for the Code128 symbology. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) + { + // Set the text that the barcode will encode. + generator.CodeText = "123ABC"; - // Save the generated barcode image to the specified file. - generator.Save(outputPath); + // Apply a custom LightCoral background color (RGB 240,128,128, fully opaque). + generator.Parameters.BackColor = Color.FromArgb(255, 240, 128, 128); - // Inform the user where the file was saved. - Console.WriteLine($"Barcode saved to {outputPath}"); + // Save the generated barcode as a PNG file to the specified path. + generator.Save(outputPath, BarCodeImageFormat.Png); } + + // Inform the user where the barcode image has been saved. + Console.WriteLine($"Barcode saved to {outputPath}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/apply-custom-background-color-named-mistyrose-to-create-soft-pastel-appearance-for-barcode.cs b/one-dimensional-barcode-types/apply-custom-background-color-named-mistyrose-to-create-soft-pastel-appearance-for-barcode.cs index 5e2e273..9955745 100644 --- a/one-dimensional-barcode-types/apply-custom-background-color-named-mistyrose-to-create-soft-pastel-appearance-for-barcode.cs +++ b/one-dimensional-barcode-types/apply-custom-background-color-named-mistyrose-to-create-soft-pastel-appearance-for-barcode.cs @@ -1,8 +1,8 @@ -// Title: Apply MistyRose Background to a Code128 Barcode -// Description: Demonstrates setting a custom MistyRose background color for a Code128 barcode and saving it as a PNG image. -// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to customize barcode appearance using the BarcodeGenerator class. Typical use cases include branding, UI integration, and print-ready barcode creation where visual styling such as background colors is required. Developers often need to adjust colors, fonts, and image formats to match design guidelines. +// Title: Generate a Code128 barcode with a MistyRose background +// Description: Demonstrates how to set a custom pastel background color for a barcode image using Aspose.BarCode and save it as PNG. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and color parameters. Developers often need to customize barcode appearance for branding or UI integration, adjusting background and foreground colors before exporting to common image formats. // Prompt: Apply a custom background color named “MistyRose” to create a soft pastel appearance for the barcode. -// Tags: barcode symbology, background color, png output, aspose.barcode, generation +// Tags: barcode symbology, background color, png output, aspose.barcode, code128, generation using System; using Aspose.BarCode; @@ -10,29 +10,32 @@ using Aspose.Drawing; /// -/// Generates a Code128 barcode with a MistyRose background and saves it as a PNG file. +/// Demonstrates generating a Code128 barcode with a MistyRose background and saving it as a PNG file. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Creates a barcode, applies colors, and saves the image. /// static void Main() { - // Initialize the barcode generator for Code128 symbology - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128)) - { - // Define the text to be encoded in the barcode - generator.CodeText = "Sample123"; + // Define the output file path for the generated barcode image + const string outputPath = "barcode_mistyrose.png"; - // Set the background color to MistyRose for a soft pastel look + // Initialize a BarcodeGenerator for Code128 symbology with sample text + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + { + // Set a soft pastel background color named "MistyRose" generator.Parameters.BackColor = Color.MistyRose; - // Save the generated barcode image as a PNG file - generator.Save("barcode.png"); + // Optionally, set the barcode (foreground) color to a contrasting dark shade + generator.Parameters.Barcode.BarColor = Color.Black; + + // Save the barcode image to the specified file in PNG format + generator.Save(outputPath, BarCodeImageFormat.Png); } - // Inform the user that the barcode has been generated - Console.WriteLine("Barcode generated with MistyRose background."); + // Inform the user where the barcode image has been saved + Console.WriteLine($"Barcode saved to '{outputPath}'."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/apply-custom-background-color-to-itf-barcodes-before-rendering-export-jpeg.cs b/one-dimensional-barcode-types/apply-custom-background-color-to-itf-barcodes-before-rendering-export-jpeg.cs index ddae110..bd876a9 100644 --- a/one-dimensional-barcode-types/apply-custom-background-color-to-itf-barcodes-before-rendering-export-jpeg.cs +++ b/one-dimensional-barcode-types/apply-custom-background-color-to-itf-barcodes-before-rendering-export-jpeg.cs @@ -1,35 +1,44 @@ -// Title: Apply custom background color to ITF14 barcode and export as JPEG -// Description: Demonstrates setting a custom background color for an ITF14 barcode before rendering and saving it as a JPEG image. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to customize visual properties such as background and bar colors using the BarcodeGenerator class. Typical use cases include branding, UI integration, and printing where specific color schemes are required. Developers often need to adjust colors, sizes, and output formats for various barcode symbologies. -// Prompt: Apply custom background color to ITF barcodes before rendering, export JPEG. -// Tags: barcode, itf14, background color, jpeg, aspose.barcode, generation +// Title: Apply custom background color to ITF‑14 barcode and export as JPEG +// Description: Demonstrates how to set a custom background color for an ITF‑14 barcode using Aspose.BarCode, then render and save it as a JPEG image. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes. Typical use cases include customizing barcode appearance for branding or printing requirements, where developers need to modify colors and export to common image formats. +/// Prompt: Apply custom background color to ITF barcodes before rendering, export JPEG. +/// Tags: itf, background-color, jpeg, aspose.barcode, aspose.drawing using System; +using System.IO; using Aspose.BarCode.Generation; -using Aspose.BarCode; using Aspose.Drawing; /// -/// Demonstrates applying a custom background color to an ITF14 barcode and saving it as a JPEG image. +/// Demonstrates applying a custom background color to an ITF‑14 barcode and saving it as a JPEG image. /// class Program { /// - /// Entry point of the example. Generates the barcode, sets visual parameters, and saves the image. + /// Entry point of the example. Generates the barcode, customizes colors, and writes the image to disk. /// static void Main() { - // Create an ITF14 barcode generator with sample numeric data - using (var generator = new BarcodeGenerator(EncodeTypes.ITF14, "123456789012")) + // Define the output file name and path + string outputPath = "itf_barcode.jpg"; + + // Sample 14‑digit code for the ITF‑14 barcode + string codeText = "12345678901231"; + + // Initialize the barcode generator with ITF‑14 symbology and the sample code + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.ITF14, codeText)) { - // Set a custom background color (light gray) + // Set a custom background color for the entire image generator.Parameters.BackColor = Color.LightGray; - // Optionally customize bar color (default is black) - // generator.Parameters.Barcode.BarColor = Color.Black; + // Optionally set the bar (foreground) color + generator.Parameters.Barcode.BarColor = Color.Black; - // Save the barcode as a JPEG image file - generator.Save("itf_barcode.jpg"); + // Render and save the barcode as a JPEG image + generator.Save(outputPath, BarCodeImageFormat.Jpeg); } + + // Inform the user where the file was saved + Console.WriteLine($"ITF barcode saved to {Path.GetFullPath(outputPath)}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/apply-custom-background-color-using-argb-value-255-255-255-0-to-create-semi-transparent-effect.cs b/one-dimensional-barcode-types/apply-custom-background-color-using-argb-value-255-255-255-0-to-create-semi-transparent-effect.cs index a4e97b1..2dd44ab 100644 --- a/one-dimensional-barcode-types/apply-custom-background-color-using-argb-value-255-255-255-0-to-create-semi-transparent-effect.cs +++ b/one-dimensional-barcode-types/apply-custom-background-color-using-argb-value-255-255-255-0-to-create-semi-transparent-effect.cs @@ -1,37 +1,34 @@ -// Title: Apply Semi‑Transparent Background Color to Barcode -// Description: Demonstrates setting a custom ARGB background color on a barcode image to achieve a semi‑transparent effect and saving it as PNG. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to customize visual appearance of generated barcodes using the BarcodeGenerator class. It shows configuring rendering parameters such as background color, a common requirement when integrating barcodes into UI designs or reports. Developers often need to adjust colors, sizes, and formats to match branding or layout constraints. +// Title: Apply semi‑transparent background color to QR code barcode +// Description: Demonstrates how to set a custom ARGB background color on a QR code using Aspose.BarCode and save it as a PNG image. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and drawing parameters to customize barcode appearance. Typical use cases include branding, UI overlays, and visual emphasis where developers need to modify background colors, transparency, or other visual properties before exporting the barcode. // Prompt: Apply a custom background color using ARGB value (255,255,255,0) to create a semi‑transparent effect. -// Tags: code128, background-color, png, barcodelibrary, generation +// Tags: qr code, background color, png, aspose.barcode, aspose.drawing using System; using Aspose.BarCode.Generation; using Aspose.Drawing; /// -/// Generates a Code128 barcode with a semi‑transparent background and saves it as a PNG file. +/// Demonstrates applying a semi‑transparent background color to a QR code and saving it as a PNG file. /// class Program { /// - /// Entry point of the example. Creates a barcode, applies a custom background color, and writes the image to disk. + /// Entry point of the example. Generates a QR code with a custom ARGB background and writes the image to disk. /// static void Main() { - // Initialize the barcode generator with Code128 symbology and sample data - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Initialize a QR code generator with the desired text. + using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Sample Text")) { - // Apply a semi‑transparent background color using ARGB (255, 255, 255, 0) + // Set the background color to semi‑transparent white (ARGB 255,255,255,0). generator.Parameters.BackColor = Color.FromArgb(255, 255, 255, 0); - // Define the output file path for the PNG image - string outputPath = "barcode.png"; - - // Save the generated barcode image to the specified file - generator.Save(outputPath); - - // Inform the user where the barcode image was saved - Console.WriteLine($"Barcode saved to {outputPath}"); + // Export the barcode as a PNG image file. + generator.Save("barcode.png"); } + + // Inform the user that the file has been created. + Console.WriteLine("Barcode image saved to barcode.png"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/apply-custom-foreground-color-to-code-16k-barcodes-verify-accessibility-contrast-compliance.cs b/one-dimensional-barcode-types/apply-custom-foreground-color-to-code-16k-barcodes-verify-accessibility-contrast-compliance.cs index b5d3238..02500ab 100644 --- a/one-dimensional-barcode-types/apply-custom-foreground-color-to-code-16k-barcodes-verify-accessibility-contrast-compliance.cs +++ b/one-dimensional-barcode-types/apply-custom-foreground-color-to-code-16k-barcodes-verify-accessibility-contrast-compliance.cs @@ -1,8 +1,8 @@ -// Title: Apply custom foreground color to Code 16K barcode and verify contrast -// Description: Demonstrates setting a dark blue bar color on a Code 16K barcode, checking WCAG contrast against a white background, and saving the image. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to customize barcode appearance using BarcodeGenerator, set bar and background colors, adjust image size, and evaluate accessibility contrast. Developers creating branded or accessible barcodes often need to modify colors while ensuring compliance with WCAG guidelines. +// Title: Apply custom foreground and background colors to a Code 16K barcode +// Description: Demonstrates setting custom bar and background colors for a Code 16K barcode and checks WCAG contrast compliance. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to customize visual appearance using BarcodeGenerator, EncodeTypes, and color properties. Typical use cases include branding, accessibility compliance, and UI integration where developers need to ensure sufficient contrast between barcode foreground and background colors. // Prompt: Apply custom foreground color to Code 16K barcodes, verify accessibility contrast compliance. -// Tags: barcode, code16k, color, contrast, accessibility, aspnet, aspose.barcode, generation +// Tags: barcode, code16k, color, contrast, accessibility, wcag, aspose.barcode, generation, png using System; using Aspose.BarCode; @@ -10,59 +10,34 @@ using Aspose.Drawing; /// -/// Generates a Code 16K barcode with a custom foreground color, -/// evaluates its contrast against the background for accessibility, -/// and saves the resulting image. +/// Demonstrates applying custom foreground and background colors to a Code 16K barcode +/// and verifying WCAG contrast compliance. /// class Program { - /// - /// Entry point of the example. Sets up colors, checks contrast, - /// configures the barcode generator, and saves the image. - /// - static void Main() + // Calculates the relative luminance of a color according to WCAG. + static double GetLuminance(Color color) { - // Sample codetext for Code 16K - const string codeText = "1234567890123456"; - - // Define custom foreground (bar) color and background color - Color barColor = Color.FromArgb(0, 0, 139); // Dark blue - Color backColor = Color.White; - - // Verify contrast ratio (WCAG AA minimum 4.5:1 for normal text) - double contrast = GetContrastRatio(barColor, backColor); - Console.WriteLine($"Contrast ratio between bar color and background: {contrast:F2}:1"); - if (contrast >= 4.5) - Console.WriteLine("Contrast OK."); - else - Console.WriteLine("Warning: Contrast may not meet accessibility guidelines."); - - // Generate the barcode with the specified colors - using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, codeText)) - { - // Apply custom colors - generator.Parameters.Barcode.BarColor = barColor; - generator.Parameters.BackColor = backColor; + // Convert sRGB components (0‑255) to linear values (0‑1) + double RsRGB = color.R / 255.0; + double GsRGB = color.G / 255.0; + double BsRGB = color.B / 255.0; - // Optional: set image size via interpolation mode - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; + double R = RsRGB <= 0.03928 ? RsRGB / 12.92 : Math.Pow((RsRGB + 0.055) / 1.055, 2.4); + double G = GsRGB <= 0.03928 ? GsRGB / 12.92 : Math.Pow((GsRGB + 0.055) / 1.055, 2.4); + double B = BsRGB <= 0.03928 ? BsRGB / 12.92 : Math.Pow((BsRGB + 0.055) / 1.055, 2.4); - // Save the barcode image - const string outputPath = "code16k.png"; - generator.Save(outputPath); - Console.WriteLine($"Barcode saved to {outputPath}"); - } + // Relative luminance formula + return 0.2126 * R + 0.7152 * G + 0.0722 * B; } - // Calculates the WCAG contrast ratio between two colors - static double GetContrastRatio(Color c1, Color c2) + // Returns the contrast ratio between two colors. + static double GetContrastRatio(Color fore, Color back) { - double L1 = GetRelativeLuminance(c1); - double L2 = GetRelativeLuminance(c2); + double L1 = GetLuminance(fore); + double L2 = GetLuminance(back); // Ensure L1 is the lighter luminance - if (L1 < L2) + if (L2 > L1) { double temp = L1; L1 = L2; @@ -71,17 +46,34 @@ static double GetContrastRatio(Color c1, Color c2) return (L1 + 0.05) / (L2 + 0.05); } - // Computes the relative luminance of a color per WCAG definition - static double GetRelativeLuminance(Color color) + /// + /// Entry point. Calculates contrast ratio, outputs result, generates barcode with custom colors. + /// + static void Main() { - double RsRGB = color.R / 255.0; - double GsRGB = color.G / 255.0; - double BsRGB = color.B / 255.0; + // Define custom colors (example: dark blue foreground on light yellow background) + Color foreground = Color.FromArgb(0, 0, 139); // DarkBlue + Color background = Color.FromArgb(255, 255, 224); // LightYellow - double R = RsRGB <= 0.03928 ? RsRGB / 12.92 : Math.Pow((RsRGB + 0.055) / 1.055, 2.4); - double G = GsRGB <= 0.03928 ? GsRGB / 12.92 : Math.Pow((GsRGB + 0.055) / 1.055, 2.4); - double B = BsRGB <= 0.03928 ? BsRGB / 12.92 : Math.Pow((BsRGB + 0.055) / 1.055, 2.4); + // Verify accessibility contrast (WCAG AA requires >= 4.5 for normal text) + double contrast = GetContrastRatio(foreground, background); + Console.WriteLine($"Contrast ratio: {contrast:F2}:1"); + if (contrast >= 4.5) + Console.WriteLine("Contrast meets WCAG AA requirements."); + else + Console.WriteLine("Contrast does NOT meet WCAG AA requirements."); - return 0.2126 * R + 0.7152 * G + 0.0722 * B; + // Create a Code 16K barcode with custom colors + using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, "1234567890123456")) + { + // Apply colors + generator.Parameters.Barcode.BarColor = foreground; // foreground (bars) + generator.Parameters.BackColor = background; // background + + // Save the barcode image as PNG + generator.Save("code16k.png"); + } + + // Program ends normally } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/apply-custom-foreground-color-using-hexadecimal-value-ff6600-to-match-corporate-branding.cs b/one-dimensional-barcode-types/apply-custom-foreground-color-using-hexadecimal-value-ff6600-to-match-corporate-branding.cs index 178793c..a34cccf 100644 --- a/one-dimensional-barcode-types/apply-custom-foreground-color-using-hexadecimal-value-ff6600-to-match-corporate-branding.cs +++ b/one-dimensional-barcode-types/apply-custom-foreground-color-using-hexadecimal-value-ff6600-to-match-corporate-branding.cs @@ -1,62 +1,39 @@ -// Title: Apply custom foreground color to a Code128 barcode -// Description: Demonstrates setting a barcode's foreground color using a hexadecimal value to match corporate branding. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to customize barcode appearance with the BarcodeGenerator class. Typical use cases include branding, visual consistency, and UI integration where developers need to apply specific colors to generated barcodes. +// Title: Apply custom foreground color to barcode using hexadecimal value +// Description: Demonstrates how to set a barcode's foreground color to a specific hex value (#FF6600) using Aspose.BarCode and save it as a PNG image. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to customize barcode appearance with color settings. It uses the BarcodeGenerator class and its Parameters.Barcode.BarColor property to apply branding colors. Developers often need to match corporate visual identity when generating barcodes for packaging, labels, or documents, and this snippet shows the typical steps for setting colors and exporting the image. // Prompt: Apply custom foreground color using hexadecimal value #FF6600 to match corporate branding. -// Tags: barcode symbology, color customization, code128, png output, aspose.barcode generation +// Tags: barcode, color, hex, code128, generation, png, aspose.barcode, aspose.drawing using System; -using System.Globalization; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; /// -/// Generates a Code128 barcode with a custom foreground color defined by a hexadecimal value. +/// Demonstrates setting a custom foreground color for a barcode and saving it as PNG. /// class Program { /// - /// Entry point of the example. Creates a barcode, applies a custom color, and saves it as a PNG file. + /// Entry point. Generates a Code128 barcode with a corporate orange color and writes the file path. /// static void Main() { - // Define the output file path for the generated barcode image. - string outputPath = "custom_color_barcode.png"; + // Define the output file path for the generated barcode image + string outputPath = "barcode.png"; - // Initialize the barcode generator for the Code128 symbology. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) + // Initialize a BarcodeGenerator for Code128 symbology with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - // Set the text that will be encoded into the barcode. - generator.CodeText = "Sample123"; + // Set the barcode's foreground (bar) color to the corporate orange #FF6600 (RGB 255,102,0) + generator.Parameters.Barcode.BarColor = Color.FromArgb(255, 102, 0); - // Convert the hexadecimal color string to an ARGB integer and apply it as the barcode's foreground color. - generator.Parameters.Barcode.BarColor = Color.FromArgb(ParseHexColor("#FF6600")); - - // Save the generated barcode image to the specified file path. - generator.Save(outputPath); + // 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 saved to {outputPath}"); - } - - /// - /// Parses a hex color string (e.g., "#FF6600") to an ARGB integer. - /// If the alpha component is omitted, it defaults to fully opaque (FF). - /// - /// Hexadecimal color string, optionally prefixed with '#'. - /// Integer representing the ARGB color. - static int ParseHexColor(string hex) - { - // Remove the leading '#' if present. - if (hex.StartsWith("#")) - hex = hex.Substring(1); - - // If only RGB components are provided, prepend 'FF' for full opacity. - if (hex.Length == 6) - hex = "FF" + hex; - - // Parse the hexadecimal string to an integer using invariant culture. - return int.Parse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture); + // Output the full path of the saved barcode image for verification + Console.WriteLine($"Barcode saved to {Path.GetFullPath(outputPath)}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/apply-custom-foreground-color-using-hsl-values-to-achieve-specific-branding-shade.cs b/one-dimensional-barcode-types/apply-custom-foreground-color-using-hsl-values-to-achieve-specific-branding-shade.cs index ef7b295..8477d8d 100644 --- a/one-dimensional-barcode-types/apply-custom-foreground-color-using-hsl-values-to-achieve-specific-branding-shade.cs +++ b/one-dimensional-barcode-types/apply-custom-foreground-color-using-hsl-values-to-achieve-specific-branding-shade.cs @@ -1,15 +1,16 @@ -// Title: Apply custom foreground color using HSL values for branding -// Description: Demonstrates converting HSL color values to Aspose.Drawing.Color and applying the result as the barcode foreground (bar) color. -// Category-Description: This example belongs to the Aspose.BarCode color customization category, showing how to use BarcodeGenerator and its Parameters.Barcode.BarColor property to match corporate branding. Developers often need to adjust bar and background colors for brand consistency, and this snippet illustrates the typical workflow using Aspose.BarCode and Aspose.Drawing APIs. +// Title: Apply Custom HSL Foreground Color to a Code128 Barcode +// Description: Demonstrates how to convert HSL values to an Aspose.Drawing.Color and apply it as the foreground bar color of a Code128 barcode, then save the image as PNG. +// Category-Description: This example belongs to the barcode appearance customization category of Aspose.BarCode. It shows how to use the BarcodeGenerator class together with the Parameters.Barcode.BarColor property to modify bar colors, and how to set background colors. Developers often need to match corporate branding by applying specific colors using standard color models such as HSL. // Prompt: Apply a custom foreground color using HSL values to achieve a specific branding shade. -// Tags: code128, color, png, barcodegenerator, aspose.barcode, aspose.drawing +// Tags: code128, color, png, barcodegenerator, parameters using System; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; /// -/// Demonstrates applying a custom foreground color to a barcode using HSL values. +/// Demonstrates applying a custom foreground color defined by HSL values to a barcode. /// class Program { @@ -20,38 +21,57 @@ class Program /// Saturation component (0‑1). /// Lightness component (0‑1). /// Corresponding Color instance. - static Color HslToColor(float hue, float saturation, float lightness) + static Color ColorFromHsl(float hue, float saturation, float lightness) { // Normalize hue to the range [0,360) hue = hue % 360f; if (hue < 0) hue += 360f; - // Compute chroma, intermediate value, and second largest component float c = (1f - Math.Abs(2f * lightness - 1f)) * saturation; float hPrime = hue / 60f; float x = c * (1f - Math.Abs(hPrime % 2f - 1f)); - // Determine temporary RGB values based on hue sector - float r1 = 0f, g1 = 0f, b1 = 0f; - if (0f <= hPrime && hPrime < 1f) { r1 = c; g1 = x; b1 = 0f; } - else if (1f <= hPrime && hPrime < 2f){ r1 = x; g1 = c; b1 = 0f; } - else if (2f <= hPrime && hPrime < 3f){ r1 = 0f; g1 = c; b1 = x; } - else if (3f <= hPrime && hPrime < 4f){ r1 = 0f; g1 = x; b1 = c; } - else if (4f <= hPrime && hPrime < 5f){ r1 = x; g1 = 0f; b1 = c; } - else if (5f <= hPrime && hPrime < 6f){ r1 = c; g1 = 0f; b1 = x; } + float r1 = 0, g1 = 0, b1 = 0; + if (0 <= hPrime && hPrime < 1) + { + r1 = c; g1 = x; b1 = 0; + } + else if (1 <= hPrime && hPrime < 2) + { + r1 = x; g1 = c; b1 = 0; + } + else if (2 <= hPrime && hPrime < 3) + { + r1 = 0; g1 = c; b1 = x; + } + else if (3 <= hPrime && hPrime < 4) + { + r1 = 0; g1 = x; b1 = c; + } + else if (4 <= hPrime && hPrime < 5) + { + r1 = x; g1 = 0; b1 = c; + } + else if (5 <= hPrime && hPrime < 6) + { + r1 = c; g1 = 0; b1 = x; + } - // Add match value to shift RGB into correct lightness float m = lightness - c / 2f; int r = (int)Math.Round((r1 + m) * 255f); int g = (int)Math.Round((g1 + m) * 255f); int b = (int)Math.Round((b1 + m) * 255f); - // Return the final color + // Clamp RGB values to valid byte range + r = Math.Clamp(r, 0, 255); + g = Math.Clamp(g, 0, 255); + b = Math.Clamp(b, 0, 255); + return Color.FromArgb(r, g, b); } /// - /// Entry point. Generates a Code128 barcode with a branding color derived from HSL values and saves it as PNG. + /// Generates a Code128 barcode with a custom HSL foreground color and saves it as a PNG file. /// static void Main() { @@ -60,19 +80,23 @@ static void Main() float saturation = 0.75f; // 0..1 float lightness = 0.40f; // 0..1 - // Convert HSL to a Color object usable by Aspose.Drawing - Color brandingColor = HslToColor(hue, saturation, lightness); + // Convert HSL to a Color object usable by Aspose.BarCode + Color brandingColor = ColorFromHsl(hue, saturation, lightness); - // Initialize barcode generator for Code128 with sample text - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Brand123")) + // Initialize a Code128 barcode generator with sample text + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "BRAND123")) { // Apply the custom foreground (bar) color generator.Parameters.Barcode.BarColor = brandingColor; - // Define output file path and save as PNG - string outputPath = "branding_barcode.png"; - generator.Save(outputPath); - Console.WriteLine($"Barcode saved to {outputPath}"); + // Optional: set a white background for contrast + generator.Parameters.BackColor = Color.White; + + // Define output path and save the barcode image as PNG + string outputPath = "custom_color_barcode.png"; + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"Barcode saved to {outputPath} with custom color (HSL {hue}, {saturation}, {lightness})."); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/apply-custom-foreground-color-using-rgb-128-0-128-to-produce-purple-barcode-for-branding-purposes.cs b/one-dimensional-barcode-types/apply-custom-foreground-color-using-rgb-128-0-128-to-produce-purple-barcode-for-branding-purposes.cs index 3771004..b751a1a 100644 --- a/one-dimensional-barcode-types/apply-custom-foreground-color-using-rgb-128-0-128-to-produce-purple-barcode-for-branding-purposes.cs +++ b/one-dimensional-barcode-types/apply-custom-foreground-color-using-rgb-128-0-128-to-produce-purple-barcode-for-branding-purposes.cs @@ -1,8 +1,8 @@ -// Title: Generate a Purple Code128 Barcode -// Description: Demonstrates how to set a custom foreground color for a barcode using Aspose.BarCode and save it as a PNG image. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to customize barcode appearance with the BarcodeGenerator API. It covers setting bar colors, selecting symbology, and exporting to common image formats. Developers often need to brand barcodes or match corporate colors, making use of classes like BarcodeGenerator, EncodeTypes, BarCodeImageFormat, and System.Drawing.Color. +// Title: Generate a purple Code128 barcode using Aspose.BarCode +// Description: Demonstrates how to set a custom foreground color (RGB 128,0,128) for a barcode image, useful for branding. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and color parameters to customize barcode appearance. Typical use cases include creating branded barcodes for product packaging, marketing materials, or internal tracking where brand colors are required. Developers often need to adjust bar and background colors, select symbology, and export to common image formats. // Prompt: Apply a custom foreground color using RGB (128,0,128) to produce a purple barcode for branding purposes. -// Tags: code128, color, png, barcodegenerator, parameters +// Tags: code128, barcode generation, color customization, png output, aspose.barcode, aspose.drawing using System; using Aspose.BarCode; @@ -10,26 +10,30 @@ using Aspose.Drawing; /// -/// Example program that creates a Code128 barcode with a custom purple foreground color -/// and saves it as a PNG file. +/// Demonstrates generating a purple Code128 barcode and saving it as a PNG file. /// class Program { /// - /// Entry point of the application. - /// Generates the barcode, applies the color, saves the image, and writes the output path to the console. + /// Entry point. Creates a BarcodeGenerator, sets custom colors, and saves the image. /// static void Main() { // Define the output file path for the generated barcode image string outputPath = "purple_barcode.png"; - // Initialize the barcode generator with Code128 symbology and sample data - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Initialize the barcode generator with Code128 symbology + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128)) { - // Set the foreground (bar) color to purple using RGB values (128, 0, 128) + // Set the text that will be encoded into the barcode + generator.CodeText = "Brand123"; + + // Apply a custom purple color (RGB 128,0,128) to the barcode bars generator.Parameters.Barcode.BarColor = Color.FromArgb(128, 0, 128); + // Ensure the background remains white (default is white, but set explicitly for clarity) + generator.Parameters.BackColor = Color.White; + // Save the generated barcode as a PNG image to the specified path generator.Save(outputPath, BarCodeImageFormat.Png); } diff --git a/one-dimensional-barcode-types/apply-gradient-background-using-two-colors-to-create-visually-appealing-barcode.cs b/one-dimensional-barcode-types/apply-gradient-background-using-two-colors-to-create-visually-appealing-barcode.cs index a9d7e96..9c10418 100644 --- a/one-dimensional-barcode-types/apply-gradient-background-using-two-colors-to-create-visually-appealing-barcode.cs +++ b/one-dimensional-barcode-types/apply-gradient-background-using-two-colors-to-create-visually-appealing-barcode.cs @@ -1,74 +1,73 @@ -// Title: Gradient Background Barcode Example -// Description: Demonstrates applying a vertical gradient background to a Code128 barcode and saving it as a PNG image. -// Category-Description: This example belongs to the Aspose.BarCode image generation category, showcasing how to customize barcode appearance using Aspose.BarCode.Generation.BarcodeGenerator and Aspose.Drawing graphics. Typical use cases include branding, UI design, and creating visually appealing barcodes for marketing materials. Developers often need to modify background colors, apply gradients, or overlay images while preserving barcode readability. +// Title: Apply a gradient background to a Code128 barcode image +// Description: Demonstrates generating a Code128 barcode and overlaying it on a vertical gradient background, then saving as PNG. +// Category-Description: This example belongs to the Aspose.BarCode image manipulation category, showcasing how to combine barcode generation (BarcodeGenerator) with custom graphics (Bitmap, Graphics) to create visually enhanced barcodes. Typical use cases include branding, marketing materials, and UI elements where a plain barcode needs a styled background. Developers often need to render barcodes onto custom canvases, apply gradients, and export to common image formats. // Prompt: Apply a gradient background using two colors to create a visually appealing barcode. -// Tags: barcode symbology, gradient background, png output, barcodegenerator, graphics +// Tags: code128, gradient-background, png, barcodelibrary, bitmap, graphics using System; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Generates a Code128 barcode with a vertical gradient background and saves it as a PNG file. +/// Generates a Code128 barcode and places it on a vertical gradient background. /// class Program { /// - /// Entry point. Creates the barcode, applies gradient, and writes the image to disk. + /// Entry point of the example. Creates the barcode, draws a gradient, composites the images, and saves the result. /// static void Main() { - // Output file path - const string outputPath = "gradient_barcode.png"; + // Define barcode parameters + const string codeText = "Gradient123"; + var encodeType = EncodeTypes.Code128; - // Create a barcode generator for Code128 with sample text - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Create a barcode generator with the specified symbology and text + using (var generator = new BarcodeGenerator(encodeType, codeText)) { - // Set barcode bar color - generator.Parameters.Barcode.BarColor = Color.Black; - // Make the generator background transparent so we can apply our own gradient - generator.Parameters.BackColor = Color.Transparent; - - // Generate the barcode image - using (Bitmap barcodeBmp = generator.GenerateBarCodeImage()) + // Generate the barcode image as a bitmap + using (var barcodeImage = generator.GenerateBarCodeImage()) { - // Create a new bitmap to hold the gradient background plus the barcode - using (Bitmap finalBmp = new Bitmap(barcodeBmp.Width, barcodeBmp.Height)) - { - using (Graphics graphics = Graphics.FromImage(finalBmp)) - { - // Define two colors for the gradient (top to bottom) - Color topColor = Color.LightBlue; - Color bottomColor = Color.LightCoral; + int width = barcodeImage.Width; + int height = barcodeImage.Height; - int height = finalBmp.Height; - int width = finalBmp.Width; + // Create a new bitmap that will hold the gradient background + using (var gradientBitmap = new Bitmap(width, height)) + { + // Define start and end colors for the vertical gradient + var startColor = Color.LightBlue; + var endColor = Color.LightGreen; - // Draw a simple vertical gradient by interpolating each scan line + // Obtain a Graphics object to draw on the gradient bitmap + using (var graphics = Graphics.FromImage(gradientBitmap)) + { + // Fill the bitmap line by line to create a smooth vertical gradient for (int y = 0; y < height; y++) { float ratio = (float)y / (height - 1); - int r = (int)(topColor.R + (bottomColor.R - topColor.R) * ratio); - int g = (int)(topColor.G + (bottomColor.G - topColor.G) * ratio); - int b = (int)(topColor.B + (bottomColor.B - topColor.B) * ratio); - Color lineColor = Color.FromArgb(r, g, b); - using (Pen pen = new Pen(lineColor)) + int r = (int)(startColor.R + (endColor.R - startColor.R) * ratio); + int g = (int)(startColor.G + (endColor.G - startColor.G) * ratio); + int b = (int)(startColor.B + (endColor.B - startColor.B) * ratio); + var lineColor = Color.FromArgb(r, g, b); + var rect = new Rectangle(0, y, width, 1); + using (var brush = new SolidBrush(lineColor)) { - graphics.DrawLine(pen, 0, y, width, y); + graphics.FillRectangle(brush, rect); } } - // Draw the barcode on top of the gradient background - graphics.DrawImage(barcodeBmp, 0, 0, barcodeBmp.Width, barcodeBmp.Height); + // Draw the generated barcode on top of the gradient background + graphics.DrawImage(barcodeImage, 0, 0); } - // Save the final image as PNG - finalBmp.Save(outputPath, ImageFormat.Png); + // Save the composited image to a PNG file + const string outputPath = "gradient_barcode.png"; + gradientBitmap.Save(outputPath, ImageFormat.Png); + Console.WriteLine($"Barcode with gradient background saved to: {outputPath}"); } } } - - Console.WriteLine($"Barcode with gradient background saved to: {outputPath}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/batch-generate-barcodes-from-database-query-using-each-record-s-identifier-as-codetext-and-saving-as-jpeg.cs b/one-dimensional-barcode-types/batch-generate-barcodes-from-database-query-using-each-record-s-identifier-as-codetext-and-saving-as-jpeg.cs index 83b0b88..12d1845 100644 --- a/one-dimensional-barcode-types/batch-generate-barcodes-from-database-query-using-each-record-s-identifier-as-codetext-and-saving-as-jpeg.cs +++ b/one-dimensional-barcode-types/batch-generate-barcodes-from-database-query-using-each-record-s-identifier-as-codetext-and-saving-as-jpeg.cs @@ -1,31 +1,49 @@ -// Title: Batch barcode generation from identifiers -// Description: Demonstrates generating Code128 barcodes for a list of identifiers and saving each as a JPEG image. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator with EncodeTypes to create barcodes in bulk. Typical use cases include exporting product IDs, inventory numbers, or any database‑driven identifiers to image files for printing or digital distribution. Developers often need to loop through data sources, set barcode properties, and save images in common formats. +// Title: Batch generate Code128 barcodes from identifiers and save as JPEG files +// Description: Demonstrates how to generate a series of Code128 barcodes using Aspose.BarCode, assigning each record's identifier as the CodeText and storing the images as JPEG files. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating batch creation of barcodes from a data source. It showcases the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes to produce images suitable for printing, labeling, or digital distribution. Developers often need to generate many barcodes programmatically—for inventory, shipping, or ticketing—by iterating over database records or other collections. // Prompt: Batch generate barcodes from a database query, using each record’s identifier as CodeText and saving as JPEG. -// Tags: barcode symbology, batch generation, jpeg output, aspose.barcode, generation +// Tags: barcode symbology, batch generation, jpeg output, aspose.barcode, code128, csharp using System; -using System.Collections.Generic; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing.Imaging; /// -/// Demonstrates batch generation of Code128 barcodes from a collection of identifiers -/// and saves each barcode as a JPEG image in a designated output folder. +/// Demonstrates batch barcode generation using Aspose.BarCode. /// class Program { /// - /// Entry point of the example. Generates barcodes for sample identifiers and writes them to disk. + /// Entry point. Generates barcodes for a set of identifiers and saves them as JPEG images. /// static void Main() { - // In a real scenario the identifiers would be read from a database. - // For this runnable example we use a hard‑coded list of sample identifiers. - // Replace the following block with actual DB access code when the required - // data provider packages are available. - List identifiers = new List + // Define the output folder for generated barcode images + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(outputFolder)) + { + // Create the folder if it does not already exist + Directory.CreateDirectory(outputFolder); + } + + // ----------------------------------------------------------------- + // NOTE: In a real scenario you would retrieve identifiers from a + // database using ADO.NET, Entity Framework, Dapper, etc. + // Example (pseudo‑code): + // using (var connection = new SqlConnection(connectionString)) + // { + // connection.Open(); + // var ids = connection.Query("SELECT Identifier FROM MyTable"); + // foreach (var id in ids) { GenerateBarcode(id, outputFolder); } + // } + // The required database packages are not available in the snippet runner, + // so we substitute with a local sample collection. + // ----------------------------------------------------------------- + + // Sample identifiers to simulate database records + string[] sampleIds = new string[] { "ID001", "ID002", @@ -34,39 +52,32 @@ static void Main() "ID005" }; - // Define the output directory for generated barcode images. - string outputFolder = "Barcodes"; - - // Ensure the output directory exists; create it if it does not. - if (!Directory.Exists(outputFolder)) + // Generate a barcode for each identifier + foreach (string id in sampleIds) { - Directory.CreateDirectory(outputFolder); + GenerateBarcode(id, outputFolder); } - // Iterate over each identifier and generate a corresponding barcode. - foreach (string id in identifiers) - { - // Create a barcode generator for Code128 (adjust symbology as needed). - using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) - { - // Set the text to be encoded in the barcode. - generator.CodeText = id; - - // Optional: set foreground and background colors. - // generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; - // generator.Parameters.BackColor = Aspose.Drawing.Color.White; - - // Build the full file path for the JPEG image. - string filePath = Path.Combine(outputFolder, $"barcode_{id}.jpeg"); + Console.WriteLine("Barcode generation completed."); + } - // Save the generated barcode as a JPEG file. - generator.Save(filePath, BarCodeImageFormat.Jpeg); + /// + /// Generates a Code128 barcode image for the specified text and saves it as a JPEG file. + /// + /// The text to encode in the barcode (e.g., a database identifier). + /// The folder where the JPEG image will be saved. + static void GenerateBarcode(string codeText, string outputFolder) + { + // Build the full file path for the JPEG image + string filePath = Path.Combine(outputFolder, $"{codeText}.jpg"); - // Log the successful generation to the console. - Console.WriteLine($"Generated barcode for '{id}' -> {filePath}"); - } + // Create a BarcodeGenerator for Code128 symbology with the given code text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + { + // Save the barcode image as JPEG + generator.Save(filePath, BarCodeImageFormat.Jpeg); } - // End of program. + Console.WriteLine($"Saved barcode for '{codeText}' to '{filePath}'."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/batch-generate-barcodes-from-excel-spreadsheet-using-each-row-s-value-as-codetext-and-exporting-png-files.cs b/one-dimensional-barcode-types/batch-generate-barcodes-from-excel-spreadsheet-using-each-row-s-value-as-codetext-and-exporting-png-files.cs index 3cd6a74..3a8c9d6 100644 --- a/one-dimensional-barcode-types/batch-generate-barcodes-from-excel-spreadsheet-using-each-row-s-value-as-codetext-and-exporting-png-files.cs +++ b/one-dimensional-barcode-types/batch-generate-barcodes-from-excel-spreadsheet-using-each-row-s-value-as-codetext-and-exporting-png-files.cs @@ -1,105 +1,96 @@ // Title: Batch barcode generation from Excel rows -// Description: Demonstrates reading code texts from an Excel (or CSV) file and generating PNG barcode images for each row. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator with EncodeTypes, AutoSizeMode, and image format settings. Typical use cases include bulk barcode creation from data sources such as spreadsheets for inventory, shipping, or labeling. Developers often need to read data, loop through entries, and export barcodes in common image formats. +// Description: Demonstrates reading an Excel file, extracting each row's first column as barcode text, and generating PNG barcode images using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode for .NET batch processing category, illustrating how to combine Aspose.Cells and Aspose.BarCode APIs to automate barcode creation from tabular data. It shows loading a workbook, iterating over used rows, configuring a BarcodeGenerator (e.g., Code128), and saving images. Developers often need to generate large numbers of barcodes from databases or spreadsheets for inventory, shipping, or labeling workflows. // Prompt: Batch generate barcodes from an Excel spreadsheet, using each row’s value as CodeText and exporting PNG files. -// Tags: barcode, code128, batch, excel, csv, png, generation, aspose.barcode, autosizemode +// Tags: barcode, batch, excel, code128, png, aspose.cells, aspose.barcode, generation using System; -using System.Collections.Generic; using System.IO; +using Aspose.Cells; +using Aspose.Cells.Drawing; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; /// -/// Example program that reads code texts from an Excel/CSV file and generates PNG barcodes -/// using Aspose.BarCode. Each row's first column becomes the CodeText for a Code128 barcode. +/// Demonstrates batch generation of Code128 barcodes from an Excel file, saving each as a PNG image. /// class Program { /// - /// Entry point. Creates an output folder, loads code texts, and generates a PNG barcode for each entry. + /// Entry point. Reads an Excel file, creates output folder, generates barcodes for each non‑empty cell in the first column, and saves them as PNG files. /// static void Main() { - // Input Excel (or CSV) file path – adjust as needed. - string inputPath = "input.xlsx"; + // Define input Excel path and output folder for barcode images + string excelPath = "input.xlsx"; + string outputFolder = "Barcodes"; - // Output directory for generated PNG files. - string outputDir = "Barcodes"; - if (!Directory.Exists(outputDir)) + // Ensure the output directory exists + if (!Directory.Exists(outputFolder)) { - Directory.CreateDirectory(outputDir); + Directory.CreateDirectory(outputFolder); } - // Load code texts from the spreadsheet (or fallback sample data). - List codeTexts = LoadCodeTexts(inputPath); - - // Generate a barcode image for each code text. - int index = 1; - foreach (string text in codeTexts) + // If the Excel file does not exist, create a sample workbook with example data + if (!File.Exists(excelPath)) { - // Create a barcode generator for Code128 symbology. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, text)) - { - // Use interpolation auto‑size mode for automatic image dimensions. - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; + CreateSampleExcel(excelPath); + } - // Optional: set image resolution (dots per inch). - generator.Parameters.Resolution = 300f; + // Load the workbook from the specified Excel file + Workbook workbook = new Workbook(excelPath); + Worksheet sheet = workbook.Worksheets[0]; - // Optional: set foreground (barcode) and background colors. - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; - generator.Parameters.BackColor = Aspose.Drawing.Color.White; + // Determine the last row that contains data + int maxRow = sheet.Cells.MaxDataRow; - // Build output file name (e.g., barcode_001.png). - string fileName = Path.Combine(outputDir, $"barcode_{index:D3}.png"); + // Iterate through each row up to the last used row + for (int row = 0; row <= maxRow; row++) + { + // Read the first column value of the current row as the barcode text + string codeText = sheet.Cells[row, 0].StringValue?.Trim(); - // Save the barcode as PNG. - generator.Save(fileName, BarCodeImageFormat.Png); + // Skip rows where the cell is empty or contains only whitespace + if (string.IsNullOrEmpty(codeText)) + { + continue; } - Console.WriteLine($"Generated barcode {index}: {text}"); - index++; + // Create a barcode generator configured for Code128 symbology + using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) + { + generator.CodeText = codeText; + + // Build the output file name (e.g., ABC001.png) and full path + string fileName = $"{codeText}.png"; + string outputPath = Path.Combine(outputFolder, fileName); + + // Save the generated barcode image as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode for '{codeText}' -> {outputPath}"); + } } Console.WriteLine("Barcode generation completed."); } - // Loads code texts from a CSV file (simple fallback for Excel) or returns a sample list. - private static List LoadCodeTexts(string path) + // Helper method to create a sample Excel file with a few rows of data + private static void CreateSampleExcel(string path) { - var list = new List(); + var wb = new Workbook(); + var ws = wb.Worksheets[0]; - // If a CSV file exists, read each line's first column as a code text. - if (File.Exists(path) && Path.GetExtension(path).Equals(".csv", StringComparison.OrdinalIgnoreCase)) - { - foreach (string line in File.ReadLines(path)) - { - if (string.IsNullOrWhiteSpace(line)) - continue; - - // Split by comma and take the first column. - string[] parts = line.Split(','); - if (parts.Length > 0) - { - list.Add(parts[0].Trim()); - } - - // Limit to a safe sample size (max 5 items). - if (list.Count >= 5) - break; - } - } - else + // Sample barcode values to populate the first column + string[] sampleCodes = { "ABC001", "ABC002", "ABC003", "ABC004", "ABC005" }; + + for (int i = 0; i < sampleCodes.Length; i++) { - // File not found or not CSV – use a predefined sample set (max 5 items). - for (int i = 1; i <= 5; i++) - { - list.Add($"Sample{i:D3}"); - } + ws.Cells[i, 0].PutValue(sampleCodes[i]); } - return list; + // Save the workbook as an XLSX file + wb.Save(path, SaveFormat.Xlsx); + Console.WriteLine($"Sample Excel file created at '{path}'."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/batch-generate-barcodes-from-json-array-using-each-element-as-codetext-and-saving-each-as-jpeg.cs b/one-dimensional-barcode-types/batch-generate-barcodes-from-json-array-using-each-element-as-codetext-and-saving-each-as-jpeg.cs index 79735e7..5d9f22f 100644 --- a/one-dimensional-barcode-types/batch-generate-barcodes-from-json-array-using-each-element-as-codetext-and-saving-each-as-jpeg.cs +++ b/one-dimensional-barcode-types/batch-generate-barcodes-from-json-array-using-each-element-as-codetext-and-saving-each-as-jpeg.cs @@ -1,54 +1,58 @@ -// Title: Batch Barcode Generation from JSON to JPEG -// Description: Demonstrates how to read a JSON array of strings, generate a Code128 barcode for each entry, and save the images as JPEG files. -// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator with EncodeTypes to create 1D barcodes. Typical use cases include batch processing of identifiers from data sources such as JSON, CSV, or databases, and exporting them as image files for printing or digital distribution. Developers often need to automate barcode creation in bulk, customize formats, and manage output directories. +// Title: Batch barcode generation from JSON array +// Description: Demonstrates how to deserialize a JSON array of strings and generate a separate Code128 barcode image for each entry, saving them as JPEG files. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating bulk barcode creation using the BarcodeGenerator class. It shows typical use cases such as processing data-driven lists, exporting barcodes for inventory or labeling, and handling file output. Developers working with batch barcode generation often need to parse input data (e.g., JSON, CSV) and produce image files in formats like JPEG, PNG, or BMP. // Prompt: Batch generate barcodes from a JSON array, using each element as CodeText and saving each as JPEG. -// Tags: barcode symbology, batch generation, jpeg, aspose.barcode, json +// Tags: barcode generation, json, batch processing, code128, jpeg, aspose.barcode, csharp using System; -using System.Collections.Generic; using System.IO; using System.Text.Json; -using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.BarCode; /// -/// Provides an example of batch barcode generation from a JSON array and saves each barcode as a JPEG image. +/// Example program that reads a JSON array of strings, creates a Code128 barcode for each string, +/// and saves the barcodes as JPEG images in an output folder. /// class Program { /// - /// Entry point of the application. Reads a JSON array, generates Code128 barcodes, and writes JPEG files. + /// Entry point of the application. Performs JSON deserialization, barcode generation, and file saving. /// static void Main() { - // Sample JSON array containing the code texts for the barcodes. - string json = "[\"12345\",\"ABCDEF\",\"Hello World\",\"9876543210\",\"SampleCode\"]"; + // Sample JSON array containing code texts + string json = @"[ ""ABC123"", ""XYZ789"", ""HELLO"", ""WORLD"", ""CODE5"" ]"; - // Deserialize the JSON array into a list of strings. - List codeTexts = JsonSerializer.Deserialize>(json) ?? new List(); + // Deserialize the JSON array into a string[] + string[] codeTexts = JsonSerializer.Deserialize(json); - // Ensure the output directory exists. - string outputDir = "Barcodes"; - if (!Directory.Exists(outputDir)) - { - Directory.CreateDirectory(outputDir); - } + // Ensure the output folder exists (creates it if missing) + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Choose a barcode symbology (e.g., Code128) + BaseEncodeType barcodeType = EncodeTypes.Code128; - // Generate a barcode for each code text and save it as a JPEG file. - for (int i = 0; i < codeTexts.Count; i++) + // Iterate over each code text and generate a corresponding JPEG barcode + for (int i = 0; i < codeTexts.Length; i++) { - string code = codeTexts[i]; - string filePath = Path.Combine(outputDir, $"barcode_{i + 1}.jpeg"); + string text = codeTexts[i]; + string fileName = $"barcode_{i + 1}.jpg"; + string filePath = Path.Combine(outputFolder, fileName); - // Use Code128 as a generic 1D barcode type. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, code)) + // Create a BarcodeGenerator for the selected symbology + using (var generator = new BarcodeGenerator(barcodeType)) { - // Save the barcode image in JPEG format. + // Assign the text to be encoded + generator.CodeText = text; + + // Save the barcode directly as a JPEG image generator.Save(filePath, BarCodeImageFormat.Jpeg); } } - // Indicate successful completion. - Console.WriteLine($"Generated {codeTexts.Count} barcode images in '{outputDir}' directory."); + // Indicate completion (no waiting for user input) + Console.WriteLine($"Generated {codeTexts.Length} barcode images in '{outputFolder}'."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/batch-generate-barcodes-from-list-of-urls-using-each-url-as-codetext-and-saving-as-png-files.cs b/one-dimensional-barcode-types/batch-generate-barcodes-from-list-of-urls-using-each-url-as-codetext-and-saving-as-png-files.cs index 0d1b49b..ab6127e 100644 --- a/one-dimensional-barcode-types/batch-generate-barcodes-from-list-of-urls-using-each-url-as-codetext-and-saving-as-png-files.cs +++ b/one-dimensional-barcode-types/batch-generate-barcodes-from-list-of-urls-using-each-url-as-codetext-and-saving-as-png-files.cs @@ -1,27 +1,28 @@ -// Title: Batch generate Code128 barcodes from URLs -// Description: Demonstrates how to create PNG barcode images for a collection of URLs, using each URL as the CodeText. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating batch processing with the BarcodeGenerator class. It shows typical use cases such as encoding multiple data items (e.g., URLs) into Code128 barcodes and saving them as image files, a common requirement for inventory, tracking, or QR code generation workflows. +// Title: Batch QR Code Generation from URL List +// Description: Demonstrates how to generate QR code barcodes for a collection of URLs and save each as a PNG file. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing bulk creation of barcodes using the BarcodeGenerator class with EncodeTypes.QR. Typical scenarios include encoding URLs for marketing materials, inventory tracking, or mobile scanning applications. Developers often need to iterate over data sets, configure code text, and export images in common formats such as PNG. // Prompt: Batch generate barcodes from a list of URLs, using each URL as CodeText and saving as PNG files. -// Tags: code128, batch-generation, png, barcodegenerator, aspose.barcode +// Tags: qr-code, barcode-generation, batch-processing, png, aspose.barcode, csharp using System; using System.Collections.Generic; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Demonstrates batch generation of Code128 barcodes from a list of URLs -/// and saves each barcode as a PNG image file. +/// Generates QR code barcodes for a predefined list of URLs and saves each barcode as a PNG file. /// class Program { /// - /// Entry point of the example. Iterates over a predefined list of URLs, - /// creates a Code128 barcode for each, and writes the image to disk. + /// Entry point of the application. Iterates through a list of URLs, creates a QR code for each, + /// and writes the resulting image to the file system. /// static void Main() { - // Define a sample collection of URLs to be encoded as barcodes. + // Define a sample collection of URLs to be encoded as QR codes. List urls = new List { "https://example.com/page1", @@ -31,25 +32,41 @@ static void Main() "https://example.com/page5" }; + // Determine the output directory relative to the current working folder. + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + + // Ensure the output directory exists; create it if it does not. + if (!Directory.Exists(outputFolder)) + { + Directory.CreateDirectory(outputFolder); + } + int index = 1; // Counter used to generate unique file names. // Process each URL in the list. foreach (string url in urls) { - // Initialise a BarcodeGenerator for Code128 symbology with the current URL as the CodeText. - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, url)) + // Initialize a QR code generator for the current URL. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR)) { - // Construct the output file name (e.g., barcode_1.png, barcode_2.png, ...). - string fileName = $"barcode_{index}.png"; + // Assign the URL as the code text to be encoded. + generator.CodeText = url; + + // Construct a safe file name using the index counter. + string safeFileName = $"barcode_{index}.png"; + string filePath = Path.Combine(outputFolder, safeFileName); - // Save the generated barcode image in PNG format. - generator.Save(fileName); + // Save the generated QR code as a PNG image. + generator.Save(filePath, BarCodeImageFormat.Png); - // Inform the user about the successful generation. - Console.WriteLine($"Generated barcode for URL '{url}' -> {fileName}"); + // Log the successful creation of the barcode file. + Console.WriteLine($"Saved barcode for '{url}' to '{filePath}'"); } - index++; // Increment the file name counter. + index++; // Increment the file name counter for the next barcode. } + + // Indicate that the batch processing has finished. + Console.WriteLine("Barcode generation completed."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/batch-generate-codabar-barcodes-from-csv-file-applying-alternating-start-symbols-for-visual-variety.cs b/one-dimensional-barcode-types/batch-generate-codabar-barcodes-from-csv-file-applying-alternating-start-symbols-for-visual-variety.cs index 0786008..d9ee550 100644 --- a/one-dimensional-barcode-types/batch-generate-codabar-barcodes-from-csv-file-applying-alternating-start-symbols-for-visual-variety.cs +++ b/one-dimensional-barcode-types/batch-generate-codabar-barcodes-from-csv-file-applying-alternating-start-symbols-for-visual-variety.cs @@ -1,61 +1,53 @@ -// Title: Batch Codabar Barcode Generation from CSV -// Description: Demonstrates reading a CSV file and generating Codabar barcode images, alternating start/stop symbols for visual variety. -// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use EncodeTypes, BarcodeGenerator, and CodabarSymbol classes to create barcodes in bulk. Typical use cases include batch processing of inventory codes, ticket numbers, or any data set stored in CSV format where developers need to automate image creation for downstream systems. +// Title: Batch generate Codabar barcodes from CSV with alternating start symbols +// Description: Demonstrates how to read values from a CSV file and create a series of Codabar barcode images, alternating the start/stop symbols for visual variety. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, showcasing the use of BarcodeGenerator, EncodeTypes, and CodabarSymbol classes. It illustrates typical batch processing scenarios such as reading data sources, configuring symbology options, and exporting PNG images—common tasks for developers integrating barcode creation into automated workflows. // Prompt: Batch generate Codabar barcodes from a CSV file, applying alternating start symbols for visual variety. -// Tags: codabar, barcode, batch, csv, image, generation, aspose.barcode +// Tags: codabar, barcode, csv, batch, generation, aspose.barcode, png using System; using System.IO; -using System.Collections.Generic; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Generates Codabar barcodes from a CSV file, alternating start/stop symbols for each image. +/// Demonstrates batch generation of Codabar barcodes from a CSV file with alternating start/stop symbols. /// class Program { /// - /// Entry point of the example. Reads input data, creates barcodes, and saves them as PNG files. + /// Entry point of the example. Reads data, creates barcodes, and saves them as PNG files. /// static void Main() { - // Path to the CSV file containing the data to encode. - const string csvPath = "input.csv"; + // Define the path to the CSV file containing barcode data. + string csvPath = "data.csv"; - // If the CSV does not exist, create a sample file with placeholder data. + // Create a sample CSV file with test data if it does not already exist. if (!File.Exists(csvPath)) { - var sampleData = new List + string[] sampleData = new string[] { "12345", "67890", - "24680", - "13579", - "112233" + "ABCDEF", + "98765", + "XYZ" }; File.WriteAllLines(csvPath, sampleData); - Console.WriteLine($"Sample CSV created at '{csvPath}'."); } - // Load all lines from the CSV and filter out empty entries. + // Read all lines from the CSV and collect non‑empty, trimmed values. string[] lines = File.ReadAllLines(csvPath); - var codes = new List(); - foreach (var line in lines) + var values = new System.Collections.Generic.List(); + foreach (string line in lines) { - var trimmed = line.Trim(); + string trimmed = line.Trim(); if (!string.IsNullOrEmpty(trimmed)) - codes.Add(trimmed); + values.Add(trimmed); } - // Abort if no valid data was found. - if (codes.Count == 0) - { - Console.WriteLine("No data found in CSV."); - return; - } - - // Define a rotating set of start/stop symbols for visual variety. + // Define a sequence of Codabar start/stop symbols to alternate between. CodabarSymbol[] symbols = new CodabarSymbol[] { CodabarSymbol.A, @@ -64,27 +56,29 @@ static void Main() CodabarSymbol.D }; - // Iterate over each code and generate the corresponding barcode image. - for (int i = 0; i < codes.Count; i++) + // Ensure the output directory for barcode images exists. + string outputDir = "Barcodes"; + if (!Directory.Exists(outputDir)) { - string codeText = codes[i]; - CodabarSymbol startStop = symbols[i % symbols.Length]; + Directory.CreateDirectory(outputDir); + } - // Initialize the generator with Codabar symbology and the current code text. - using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, codeText)) - { - // Apply the alternating start and stop symbols. - generator.Parameters.Barcode.Codabar.StartSymbol = startStop; - generator.Parameters.Barcode.Codabar.StopSymbol = startStop; + // Generate a barcode image for each value, applying the alternating symbol. + for (int i = 0; i < values.Count; i++) + { + string codeText = values[i]; + CodabarSymbol symbol = symbols[i % symbols.Length]; - // Set a modest image size (points) for the output PNG. - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Codabar, codeText)) + { + // Apply the selected start and stop symbols to the Codabar barcode. + generator.Parameters.Barcode.Codabar.StartSymbol = symbol; + generator.Parameters.Barcode.Codabar.StopSymbol = symbol; - // Save the generated barcode to a file. - string outputFile = $"barcode_{i + 1}.png"; - generator.Save(outputFile); - Console.WriteLine($"Generated '{outputFile}' with start/stop symbol '{startStop}'."); + // Save the generated barcode as a PNG file. + string fileName = Path.Combine(outputDir, $"barcode_{i + 1}.png"); + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for \"{codeText}\" with symbol {symbol} to {fileName}"); } } diff --git a/one-dimensional-barcode-types/batch-generate-codabar-barcodes-using-data-from-sql-query-saving-each-as-jpeg-file-with-identifier-name.cs b/one-dimensional-barcode-types/batch-generate-codabar-barcodes-using-data-from-sql-query-saving-each-as-jpeg-file-with-identifier-name.cs index bc51305..381491a 100644 --- a/one-dimensional-barcode-types/batch-generate-codabar-barcodes-using-data-from-sql-query-saving-each-as-jpeg-file-with-identifier-name.cs +++ b/one-dimensional-barcode-types/batch-generate-codabar-barcodes-using-data-from-sql-query-saving-each-as-jpeg-file-with-identifier-name.cs @@ -1,67 +1,80 @@ -// Title: Batch generate Codabar barcodes from SQL data -// Description: Demonstrates generating Codabar barcodes for each record retrieved from a SQL query and saving them as JPEG files named with the record identifier. -// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use the BarcodeGenerator class with EncodeTypes.Codabar to create barcodes in bulk. Typical use cases include batch processing of database records to produce printable barcode images. Developers often need to customize appearance, choose output formats, and automate file naming—this snippet illustrates those common steps. +// Title: Batch generate Codabar barcodes from data and save as JPEG files +// Description: Demonstrates how to create Codabar barcodes for multiple records and store each image as a JPEG file using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category. It shows how to use the BarcodeGenerator class with EncodeTypes.Codabar to produce barcodes in bulk, configure image format, and save them to disk. Typical use cases include generating product labels, inventory tags, or any batch barcode creation where data originates from a database query. // Prompt: Batch generate Codabar barcodes using data from a SQL query, saving each as a JPEG file with identifier name. -// Tags: codabar, barcode generation, batch processing, jpeg, aspose.barcode, aspose.drawing, sql +// Tags: codabar, barcode generation, batch, sql, jpeg, aspose.barcode, image export using System; using System.Collections.Generic; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; /// -/// Demonstrates batch generation of Codabar barcodes from data (simulating a SQL query) and saving each as a JPEG file. +/// Demonstrates batch generation of Codabar barcodes from a data source and saving each as a JPEG file. /// class Program { /// - /// Entry point of the example. Simulates fetching data from a database and generates barcodes for each record. + /// Entry point that creates an output folder, retrieves sample data (replace with SQL query), generates Codabar barcodes, and saves them as JPEG images. /// static void Main() { - // ------------------------------------------------------------ - // Simulated data representing rows fetched from a SQL query. - // Replace this block with actual database access code as needed. - // ------------------------------------------------------------ - var sampleData = new List<(int Id, string Code)> - { - (1, "A12345B"), - (2, "C67890D"), - (3, "E11223F"), - (4, "G44556H"), - (5, "I78901J") - }; + // Define the folder where barcode images will be stored. + string outputFolder = "Barcodes"; - // Iterate over each record and generate a Codabar barcode. - foreach (var (id, code) in sampleData) + // Ensure the output directory exists. + if (!Directory.Exists(outputFolder)) { - GenerateCodabar(id, code); + Directory.CreateDirectory(outputFolder); } - } - /// - /// Generates a Codabar barcode image for the specified identifier and code text, then saves it as a JPEG file. - /// - /// Unique identifier used for naming the output file. - /// The text to encode in the Codabar barcode. Must be a valid Codabar string. - static void GenerateCodabar(int identifier, string codeText) - { - // Construct the output file name using the identifier. - string fileName = $"Barcode_{identifier}.jpeg"; + // ------------------------------------------------------------ + // In a real scenario you would fetch data from a SQL database, + // e.g. using System.Data.SqlClient and executing a query that + // returns an identifier and the Codabar code text. + // The following code is a placeholder that simulates such data. + // ------------------------------------------------------------ + List<(string Id, string CodeText)> records = GetSampleData(); - // Create a BarcodeGenerator for Codabar with the provided code text. - using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, codeText)) + // Iterate over each record and generate a barcode image. + foreach (var record in records) { - // Optional: customize barcode appearance. - generator.Parameters.Barcode.BarColor = Color.Black; // Set barcode bars to black. - generator.Parameters.BackColor = Color.White; // Set background to white. + try + { + // Initialize a Codabar barcode generator with the current code text. + using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, record.CodeText)) + { + // Optional: set start/stop symbols if required. + // generator.Parameters.Barcode.Codabar.StartSymbol = CodabarSymbol.A; + // generator.Parameters.Barcode.Codabar.StopSymbol = CodabarSymbol.A; - // Save the generated barcode as a JPEG image. - generator.Save(fileName, BarCodeImageFormat.Jpeg); + // Build the full file path using the record identifier. + string filePath = Path.Combine(outputFolder, $"{record.Id}.jpg"); + + // Save the generated barcode as a JPEG image. + generator.Save(filePath, BarCodeImageFormat.Jpeg); + Console.WriteLine($"Saved barcode for '{record.Id}' to '{filePath}'."); + } + } + catch (Exception ex) + { + // Log any errors that occur during barcode generation. + Console.WriteLine($"Failed to generate barcode for '{record.Id}': {ex.Message}"); + } } + } - // Inform the user that the barcode has been generated. - Console.WriteLine($"Generated Codabar barcode for ID {identifier} -> {fileName}"); + // Sample data generator – replace with actual SQL query results. + static List<(string Id, string CodeText)> GetSampleData() + { + return new List<(string, string)> + { + ("Item001", "A123456A"), + ("Item002", "B987654B"), + ("Item003", "C555555C"), + ("Item004", "D111111D"), + ("Item005", "E222222E") + }; } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/batch-generate-code-16k-barcodes-for-product-id-list-storing-each-as-bmp-file.cs b/one-dimensional-barcode-types/batch-generate-code-16k-barcodes-for-product-id-list-storing-each-as-bmp-file.cs index eec0587..e5c2e35 100644 --- a/one-dimensional-barcode-types/batch-generate-code-16k-barcodes-for-product-id-list-storing-each-as-bmp-file.cs +++ b/one-dimensional-barcode-types/batch-generate-code-16k-barcodes-for-product-id-list-storing-each-as-bmp-file.cs @@ -1,28 +1,28 @@ -// Title: Batch generate Code 16K barcodes and save as BMP files -// Description: Demonstrates creating Code 16K barcodes for a collection of product IDs and storing each barcode as an individual BMP image. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class with EncodeTypes.Code16K for batch processing. Typical use cases include inventory labeling, product tracking, and bulk barcode creation where developers need to automate image output in a specific format. +// Title: Batch generation of Code 16K barcodes to BMP files +// Description: Demonstrates how to generate Code 16K barcodes for a list of product IDs and save each barcode as a BMP image file. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of EncodeTypes, BarcodeGenerator, and BarCodeImageFormat classes. Typical scenarios include bulk creation of product barcodes for inventory systems, packaging, or point‑of‑sale applications. Developers often need to automate barcode creation for multiple items and store them in common image formats such as BMP. // Prompt: Batch generate Code 16K barcodes for product ID list, storing each as BMP file. -// Tags: code16k, barcode, generation, bmp, batch, aspose.barcode +// Tags: code16k, barcode, generation, bmp, aspose.barcode using System; -using System.Collections.Generic; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Provides an entry point for generating a set of Code 16K barcodes from a list of product identifiers -/// and saving each barcode as a BMP image file. +/// Provides an example that creates Code 16K barcodes for a collection of product identifiers +/// and stores each barcode as a BMP image file. /// class Program { /// - /// Generates Code 16K barcodes for predefined product IDs and writes each image to the "Barcodes" folder. + /// Entry point that iterates over product IDs, generates corresponding Code 16K barcodes, + /// and saves them as BMP files in a dedicated output folder. /// static void Main() { - // Define a sample collection of product identifiers. - List productIds = new List + // Define a sample list of product IDs to encode. + string[] productIds = new[] { "PROD001", "PROD002", @@ -31,36 +31,31 @@ static void Main() "PROD005" }; - // Determine the output directory relative to the current working directory. + // Determine the output directory for BMP files (creates "Barcodes" folder in the current directory). string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); - - // Ensure the output directory exists; create it if it does not. if (!Directory.Exists(outputDir)) { Directory.CreateDirectory(outputDir); } - // Iterate over each product ID and generate a corresponding barcode. + // Process each product ID. foreach (string id in productIds) { - // Initialize a barcode generator for the Code 16K symbology. - using (var generator = new BarcodeGenerator(EncodeTypes.Code16K)) + // Initialize a BarcodeGenerator for the Code16K symbology. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code16K)) { - // Assign the product ID as the text to encode in the barcode. + // Assign the product ID as the text to encode. generator.CodeText = id; - // Optional: adjust the aspect ratio if required (default is 1.0). - // generator.Parameters.Barcode.Code16K.AspectRatio = 1.0f; - - // Construct the full file path for the BMP output. - string filePath = Path.Combine(outputDir, $"Product_{id}.bmp"); + // Optional: configure Code16K‑specific parameters. + generator.Parameters.Barcode.Code16K.AspectRatio = 1.0f; // Height/Width ratio. + generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = 10; // Left quiet zone coefficient. + generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = 1; // Right quiet zone coefficient. - // Save the generated barcode image in BMP format. - generator.Save(filePath); + // Build the full file path and save the barcode as a BMP image. + string filePath = Path.Combine(outputDir, $"{id}.bmp"); + generator.Save(filePath, BarCodeImageFormat.Bmp); } } - - // Notify the user that the batch operation has completed. - Console.WriteLine("Barcode generation completed."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/batch-generate-itf-barcodes-for-inventory-list-applying-individual-frame-thickness-save-zip-archive.cs b/one-dimensional-barcode-types/batch-generate-itf-barcodes-for-inventory-list-applying-individual-frame-thickness-save-zip-archive.cs index 2c6a0fb..13cf0c3 100644 --- a/one-dimensional-barcode-types/batch-generate-itf-barcodes-for-inventory-list-applying-individual-frame-thickness-save-zip-archive.cs +++ b/one-dimensional-barcode-types/batch-generate-itf-barcodes-for-inventory-list-applying-individual-frame-thickness-save-zip-archive.cs @@ -1,8 +1,8 @@ -// Title: Batch ITF14 Barcode Generation with Custom Frame Thickness -// Description: Demonstrates how to generate ITF14 barcodes for a list of inventory items, each with its own frame thickness, and package the images into a ZIP file. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on the BarcodeGenerator class and ITF14 symbology. It shows typical use cases such as creating product barcodes with customized borders, saving images in PNG format, and archiving results. Developers working on inventory management, packaging, or bulk barcode creation can use this pattern to automate barcode production. +// Title: Batch generation of ITF14 barcodes with custom frame thickness and ZIP packaging +// Description: Demonstrates how to generate multiple ITF14 barcodes, each with its own frame border thickness, and bundle the resulting PNG images into a ZIP archive. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and barcode parameter settings such as ITF border configuration. Typical scenarios include creating inventory labels, batch processing of barcodes, and exporting them for distribution. Developers often need to customize visual properties per barcode and archive the output for downstream systems. // Prompt: Batch generate ITF barcodes for inventory list, applying individual frame thickness, save ZIP archive. -// Tags: itf14, barcode, generation, png, zip, aspose.barcode, inventory, frame-thickness +// Tags: itf14, barcode, batch generation, frame thickness, zip archive, aspose.barcode, png, inventory using System; using System.Collections.Generic; @@ -12,73 +12,101 @@ using Aspose.BarCode.Generation; using Aspose.Drawing; -/// -/// Provides an example that batch‑generates ITF14 barcodes with per‑item frame thickness -/// and stores the resulting PNG images in a ZIP archive. -/// -class Program +namespace BarcodeBatch { /// - /// Entry point of the example. Generates barcodes, saves them as PNG files, - /// and creates a ZIP archive containing all images. + /// Generates a set of ITF14 barcodes with individual frame thickness settings and packages them into a ZIP file. /// - static void Main() + class Program { - // Define a sample inventory list. - // Each tuple holds the barcode text and the desired frame thickness (points). - var inventory = new List<(string CodeText, float FrameThickness)> + /// + /// Entry point of the example. Creates barcode images, applies per‑item border thickness, and archives the results. + /// + static void Main() { - ("12345678901231", 5f), - ("98765432109876", 8f), - ("55555555555555", 12f), - ("11111111111111", 3f), - ("22222222222222", 10f) - }; + // Define sample inventory items, each with a 14‑digit code and a specific frame thickness. + var items = new List + { + new InventoryItem { Code = "12345678901231", FrameThickness = 5f }, + new InventoryItem { Code = "98765432109876", FrameThickness = 8f }, + new InventoryItem { Code = "11111111111111", FrameThickness = 10f }, + new InventoryItem { Code = "22222222222222", FrameThickness = 12f }, + new InventoryItem { Code = "33333333333333", FrameThickness = 15f } + }; - // Prepare an output folder for the generated PNG files. - string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); - if (!Directory.Exists(outputDir)) - { - Directory.CreateDirectory(outputDir); - } + // Ensure the output directory exists. + string outputDir = "Barcodes"; + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } - // Iterate through the inventory and generate a barcode image for each item. - foreach (var item in inventory) - { - string fileName = $"{item.CodeText}.png"; - string filePath = Path.Combine(outputDir, fileName); + var generatedFiles = new List(); - // Use BarcodeGenerator with ITF14 symbology. - using (var generator = new BarcodeGenerator(EncodeTypes.ITF14)) + // Iterate over each inventory item and generate its barcode. + foreach (var item in items) { - // Set the text to encode. - generator.CodeText = item.CodeText; + // ITF14 requires exactly 14 numeric characters; skip invalid entries. + if (string.IsNullOrEmpty(item.Code) || item.Code.Length != 14) + { + Console.WriteLine($"Skipping invalid code '{item.Code}'. ITF14 requires 14 digits."); + continue; + } + + // Create a barcode generator for the ITF14 symbology. + using (var generator = new BarcodeGenerator(EncodeTypes.ITF14, item.Code)) + { + // Apply a frame border and set its thickness according to the current item. + generator.Parameters.Barcode.ITF.BorderType = ITF14BorderType.Frame; + generator.Parameters.Barcode.ITF.BorderThickness.Point = item.FrameThickness; - // Apply the specific frame thickness and set the border type to Frame. - generator.Parameters.Barcode.ITF.BorderThickness.Point = item.FrameThickness; - generator.Parameters.Barcode.ITF.BorderType = ITF14BorderType.Frame; + // Suppress exceptions for minor code‑text issues (e.g., leading zeros). + generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; - // Save the generated barcode as a PNG image. - generator.Save(filePath); + // Save the barcode as a PNG file. + string filePath = Path.Combine(outputDir, $"{item.Code}.png"); + generator.Save(filePath, BarCodeImageFormat.Png); + generatedFiles.Add(filePath); + } } - } - // Create a ZIP archive that contains all generated PNG files. - string zipPath = Path.Combine(Directory.GetCurrentDirectory(), "ITFBarcodes.zip"); - if (File.Exists(zipPath)) - { - File.Delete(zipPath); - } + // Create a ZIP archive that contains all generated barcode images. + string zipPath = "Barcodes.zip"; + if (File.Exists(zipPath)) + { + File.Delete(zipPath); + } - using (var zip = ZipFile.Open(zipPath, ZipArchiveMode.Create)) - { - foreach (var file in Directory.GetFiles(outputDir, "*.png")) + using (var zipStream = new FileStream(zipPath, FileMode.Create)) + using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Create)) { - zip.CreateEntryFromFile(file, Path.GetFileName(file)); + foreach (var file in generatedFiles) + { + if (File.Exists(file)) + { + // Add each PNG file to the archive using its file name. + archive.CreateEntryFromFile(file, Path.GetFileName(file)); + } + } } + + Console.WriteLine($"Generated {generatedFiles.Count} barcodes and saved to '{zipPath}'."); } - // Optional: clean up the temporary image files. - // Directory.Delete(outputDir, true); + /// + /// Simple data holder for inventory items used in the barcode generation loop. + /// + class InventoryItem + { + /// + /// The 14‑digit code to encode as an ITF14 barcode. + /// + public string Code { get; set; } + + /// + /// Desired frame border thickness (in points) for the barcode image. + /// + public float FrameThickness { get; set; } + } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/batch-import-xml-configurations-apply-each-to-generate-barcode-and-store-images-in-timestamped-folder.cs b/one-dimensional-barcode-types/batch-import-xml-configurations-apply-each-to-generate-barcode-and-store-images-in-timestamped-folder.cs index 077fd43..ab15624 100644 --- a/one-dimensional-barcode-types/batch-import-xml-configurations-apply-each-to-generate-barcode-and-store-images-in-timestamped-folder.cs +++ b/one-dimensional-barcode-types/batch-import-xml-configurations-apply-each-to-generate-barcode-and-store-images-in-timestamped-folder.cs @@ -1,67 +1,71 @@ -// Title: Batch generate barcodes from XML configurations -// Description: Demonstrates importing multiple barcode settings from XML files, generating corresponding PNG images, and saving them to a timestamped folder. -// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator.ImportFromXml and BarcodeGenerator.Save to process batch configurations. Developers often need to automate barcode creation from predefined XML templates for inventory, shipping, or labeling workflows. The snippet illustrates folder handling, timestamped output, and error reporting for large‑scale barcode generation. +// Title: Batch generate barcodes from XML configuration files +// Description: Demonstrates how to import barcode settings from multiple XML files, generate corresponding barcode images, and save them to a timestamped folder. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of BarcodeGenerator.ImportFromXml to load configuration, and BarcodeGenerator.Save to export images. Typical scenarios include bulk barcode creation from predefined settings, automated report generation, and integration pipelines where barcode specifications are maintained as XML. Developers often need to batch‑process configurations, manage output locations, and handle errors gracefully. // Prompt: Batch import XML configurations, apply each to generate a barcode, and store images in a timestamped folder. -// Tags: barcode symbology, batch import, png, barcodegenerator +// Tags: barcode generation, batch processing, xml configuration, png, aspose.barcode, barcodegenerator using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeRecognition; /// -/// Generates barcode images by importing settings from XML files located in a predefined folder. +/// Provides a console application that reads barcode generation settings from XML files, +/// creates corresponding barcode images, and saves them into a timestamped output directory. /// class Program { /// - /// Entry point of the application. Scans the input directory for XML configurations, - /// creates barcodes, and saves them as PNG files in a timestamped output folder. + /// Entry point of the application. Executes the batch barcode generation workflow. /// static void Main() { - // Define the folder that contains XML barcode configuration files. - string inputFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "BarcodesXml"); + // Define the folder that contains XML configuration files for barcode generation. + string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "BarCodeConfigs"); if (!Directory.Exists(inputFolder)) { - // Ensure the input folder exists to avoid runtime errors. - Directory.CreateDirectory(inputFolder); + Console.WriteLine($"Input folder not found: {inputFolder}"); + return; } - // Define a timestamped output folder for the generated barcode images. + // Create a unique output folder using the current timestamp to avoid name collisions. string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); - string outputFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "BarcodesOutput", timestamp); + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), $"BarCodeImages_{timestamp}"); Directory.CreateDirectory(outputFolder); - // Retrieve all XML files from the input folder. + // Retrieve all XML files from the input directory. string[] xmlFiles = Directory.GetFiles(inputFolder, "*.xml"); if (xmlFiles.Length == 0) { - Console.WriteLine("No XML configuration files found in: " + inputFolder); + Console.WriteLine("No XML configuration files found."); return; } - // Process each XML configuration file. + // Process each XML configuration file individually. foreach (string xmlPath in xmlFiles) { try { - // Import barcode settings from the XML file. + // Load generator settings from the XML file. using (BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(xmlPath)) { - // Build the output image file name (same as XML file name, but with .png extension). - string outputFileName = Path.GetFileNameWithoutExtension(xmlPath) + ".png"; - string outputPath = Path.Combine(outputFolder, outputFileName); + // Build the output image path using the XML file name (without extension). + string fileNameWithoutExt = Path.GetFileNameWithoutExtension(xmlPath); + string imagePath = Path.Combine(outputFolder, $"{fileNameWithoutExt}.png"); - // Save the generated barcode image to the output folder. - generator.Save(outputPath); - Console.WriteLine($"Generated barcode saved to: {outputPath}"); + // Save the generated barcode as a PNG image. + generator.Save(imagePath, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode saved to: {imagePath}"); } } catch (Exception ex) { - // Log any errors encountered while processing the current XML file. + // Log any errors that occur while processing a specific XML file. Console.WriteLine($"Failed to process '{xmlPath}': {ex.Message}"); } } + + Console.WriteLine("Batch barcode generation completed."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/batch-process-directory-of-xml-configuration-files-generating-corresponding-barcode-images-and-logging-any-errors-encoun.cs b/one-dimensional-barcode-types/batch-process-directory-of-xml-configuration-files-generating-corresponding-barcode-images-and-logging-any-errors-encoun.cs index 2865758..d20aa8a 100644 --- a/one-dimensional-barcode-types/batch-process-directory-of-xml-configuration-files-generating-corresponding-barcode-images-and-logging-any-errors-encoun.cs +++ b/one-dimensional-barcode-types/batch-process-directory-of-xml-configuration-files-generating-corresponding-barcode-images-and-logging-any-errors-encoun.cs @@ -1,8 +1,8 @@ -// Title: Batch generate barcodes from XML configurations -// Description: Demonstrates how to read barcode settings from XML files, generate images, and handle errors. -// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of BarcodeGenerator.ImportFromXml to create barcodes from configuration files. Typical use cases include bulk barcode creation for inventory, shipping, or labeling systems where settings are stored in XML. Developers often need to process multiple files, manage output directories, and log processing issues. +// Title: Batch barcode generation from XML configuration files +// Description: Demonstrates how to read barcode settings from XML files, generate PNG images, and log errors. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of BarcodeGenerator.ImportFromXml and ExportToXml for batch processing. Developers often need to automate barcode creation from configuration files, handling multiple symbologies and output formats while capturing processing errors. The snippet illustrates folder handling, image saving, and simple logging, useful for CI pipelines or bulk operations. // Prompt: Batch process a directory of XML configuration files, generating corresponding barcode images and logging any errors encountered. -// Tags: barcode generation, xml configuration, batch processing, png output, aspose.barcode +// Tags: barcode generation, xml configuration, batch processing, error logging, png output, aspose.barcode using System; using System.IO; @@ -10,75 +10,76 @@ using Aspose.BarCode.Generation; /// -/// Provides a console application that batch‑processes XML barcode configuration files, -/// generates PNG images for each configuration, and logs any errors encountered during the process. +/// Demonstrates batch processing of XML barcode configuration files to generate PNG images. /// class Program { /// - /// Entry point of the application. - /// Accepts optional command‑line arguments for input and output directories, - /// processes up to a safety‑capped number of XML files, and creates corresponding barcode images. + /// Entry point. Scans a folder for XML files, creates barcodes per configuration, saves them, and logs any errors. /// - /// - /// args[0] – optional path to the input directory containing XML files (default: "BarcodesConfig"). - /// args[1] – optional path to the output directory for generated PNG images (default: "BarcodesOutput"). - /// - static void Main(string[] args) + static void Main() { - // Resolve input directory (first argument or default) - string inputDir = args.Length > 0 ? args[0] : "BarcodesConfig"; + // Input folder containing XML configuration files + string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "BarcodesXml"); + // Output folder for generated barcode images + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "BarcodesImages"); + // Log file for errors + string logFile = Path.Combine(outputFolder, "error.log"); - // Resolve output directory (second argument or default) - string outputDir = args.Length > 1 ? args[1] : "BarcodesOutput"; - - // Verify that the input directory exists - if (!Directory.Exists(inputDir)) + // Ensure input and output folders exist + if (!Directory.Exists(inputFolder)) { - Console.WriteLine($"Input directory does not exist: {inputDir}"); - return; + Directory.CreateDirectory(inputFolder); } - - // Ensure the output directory exists - if (!Directory.Exists(outputDir)) + if (!Directory.Exists(outputFolder)) { - Directory.CreateDirectory(outputDir); + Directory.CreateDirectory(outputFolder); } - // Retrieve all XML configuration files from the input directory - string[] xmlFiles = Directory.GetFiles(inputDir, "*.xml"); - - // Safety cap to avoid processing an unexpectedly large number of files - const int maxFiles = 5; - int processed = 0; - - // Iterate over each XML file until the safety cap is reached - foreach (string xmlPath in xmlFiles) + // Seed a sample XML if the input folder is empty (self‑contained example) + if (Directory.GetFiles(inputFolder, "*.xml").Length == 0) { - if (processed >= maxFiles) - break; + string sampleXmlPath = Path.Combine(inputFolder, "sample1.xml"); + using (var sampleGenerator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + { + // Export the generator settings to XML + sampleGenerator.ExportToXml(sampleXmlPath); + } + } + // Process each XML file in the input folder + foreach (string xmlFile in Directory.GetFiles(inputFolder, "*.xml")) + { try { - // Load barcode generator settings from the XML configuration - using (BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(xmlPath)) + // Load generator configuration from XML + using (var generator = BarcodeGenerator.ImportFromXml(xmlFile)) { - // Build the output image path (same base name, .png extension) - string fileNameWithoutExt = Path.GetFileNameWithoutExtension(xmlPath); - string outputPath = Path.Combine(outputDir, fileNameWithoutExt + ".png"); + // Determine output image path (same name, .png extension) + string outputImagePath = Path.Combine( + outputFolder, + Path.GetFileNameWithoutExtension(xmlFile) + ".png"); + + // Save the barcode image as PNG + generator.Save(outputImagePath, BarCodeImageFormat.Png); - // Save the generated barcode image to the output directory - generator.Save(outputPath); - Console.WriteLine($"Generated barcode: {outputPath}"); + Console.WriteLine($"Generated barcode: {outputImagePath}"); } } catch (Exception ex) { - // Log any errors that occur while processing the current XML file - Console.WriteLine($"Error processing '{xmlPath}': {ex.Message}"); + // Log error to console and file + string message = $"Error processing '{xmlFile}': {ex.Message}"; + Console.WriteLine(message); + try + { + File.AppendAllText(logFile, $"{DateTime.Now}: {message}{Environment.NewLine}"); + } + catch + { + // Swallow logging failures to avoid crashing the batch + } } - - processed++; } Console.WriteLine("Batch processing completed."); diff --git a/one-dimensional-barcode-types/batch-process-folder-of-xml-configuration-files-generating-barcode-for-each-and-saving-as-tiff-images.cs b/one-dimensional-barcode-types/batch-process-folder-of-xml-configuration-files-generating-barcode-for-each-and-saving-as-tiff-images.cs index 95e3507..ab6ae2a 100644 --- a/one-dimensional-barcode-types/batch-process-folder-of-xml-configuration-files-generating-barcode-for-each-and-saving-as-tiff-images.cs +++ b/one-dimensional-barcode-types/batch-process-folder-of-xml-configuration-files-generating-barcode-for-each-and-saving-as-tiff-images.cs @@ -1,73 +1,104 @@ -// Title: Generate barcodes from XML configs and save as TIFF images -// Description: This example reads up to five XML barcode configuration files from a folder, creates barcodes using Aspose.BarCode, and writes them as TIFF files. -// Category-Description: Demonstrates batch processing of barcode generation using Aspose.BarCode's BarcodeGenerator class. Typical use cases include automating barcode creation from configuration files for inventory, shipping, or labeling systems. Developers often need to import settings from XML, generate images, and store them in a designated output directory. +// Title: Batch generate barcodes from XML configurations and save as TIFF +// Description: The example reads XML files that specify barcode symbology and data, creates a barcode for each, and writes the result as a TIFF image. +// Category-Description: This sample belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator, EncodeTypes, and related parameter settings for bulk barcode creation. Typical use cases include processing configuration files, automating label production, or converting data definitions into visual barcodes. Developers often need to read external definitions, resolve symbology via reflection, and output high‑resolution images for printing or archival. // Prompt: Batch process a folder of XML configuration files, generating a barcode for each and saving as TIFF images. -// Tags: barcode generation, xml import, batch processing, tiff output, aspose.barcode +// Tags: barcode, symbology, batch processing, tiff, aspose.barcode, xml, generation using System; using System.IO; +using System.Xml; +using System.Reflection; using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Demonstrates batch processing of XML barcode configuration files to generate TIFF images. +/// Demonstrates batch processing of XML configuration files to generate barcodes and save them as TIFF images. /// class Program { /// - /// Entry point. Processes up to five XML files in the specified folder, creates barcodes, and saves them as TIFF files. + /// Entry point. Reads input and output folder paths, processes each XML file, and creates corresponding barcode images. /// - /// Optional first argument specifying the input folder path. + /// Optional command‑line arguments: [0] input folder, [1] output folder. static void Main(string[] args) { - // Determine input folder (first argument or default) + // Determine input folder containing XML configuration files string inputFolder = args.Length > 0 ? args[0] : "BarcodesConfig"; - // Verify that the input folder exists + // Determine output folder for generated TIFF images + string outputFolder = args.Length > 1 ? args[1] : "BarcodesOutput"; + + // Ensure the input folder exists; create it if missing if (!Directory.Exists(inputFolder)) { - Console.WriteLine($"Input folder does not exist: {inputFolder}"); - return; + Directory.CreateDirectory(inputFolder); + Console.WriteLine($"Created input folder: {Path.GetFullPath(inputFolder)}"); } - // Prepare output folder inside the input folder - string outputFolder = Path.Combine(inputFolder, "Output"); - Directory.CreateDirectory(outputFolder); - - // Retrieve all XML configuration files (limit to 5 for safety) - string[] xmlFiles = Directory.GetFiles(inputFolder, "*.xml"); - int maxFiles = Math.Min(xmlFiles.Length, 5); - - // Process each XML file - for (int i = 0; i < maxFiles; i++) + // Ensure the output folder exists; create it if missing + if (!Directory.Exists(outputFolder)) { - string xmlPath = xmlFiles[i]; + Directory.CreateDirectory(outputFolder); + Console.WriteLine($"Created output folder: {Path.GetFullPath(outputFolder)}"); + } - // Ensure the file still exists before processing - if (!File.Exists(xmlPath)) + // Iterate over each XML file in the input folder + foreach (string xmlPath in Directory.GetFiles(inputFolder, "*.xml")) + { + try { - Console.WriteLine($"File not found: {xmlPath}"); - continue; - } + // Load the XML configuration document + var doc = new XmlDocument(); + doc.Load(xmlPath); - // Load barcode settings from the XML file - using (BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(xmlPath)) - { - // Verify that the generator was created successfully - if (generator == null) + // Expected XML elements: and + XmlNode symNode = doc.SelectSingleNode("//Symbology"); + XmlNode textNode = doc.SelectSingleNode("//CodeText"); + + // Validate required elements are present + if (symNode == null || textNode == null) + { + Console.WriteLine($"Skipping '{xmlPath}': missing Symbology or CodeText element."); + continue; + } + + // Extract symbology name and code text, trimming whitespace + string symName = symNode.InnerText.Trim(); + string codeText = textNode.InnerText.Trim(); + + // Resolve symbology name to an EncodeTypes field using reflection + FieldInfo field = typeof(EncodeTypes).GetField(symName); + if (field == null) { - Console.WriteLine($"Failed to import XML: {xmlPath}"); + Console.WriteLine($"Unknown symbology '{symName}' in file '{xmlPath}'."); continue; } - // Build the output TIFF file name based on the XML file name - string fileNameWithoutExt = Path.GetFileNameWithoutExtension(xmlPath); - string tiffPath = Path.Combine(outputFolder, fileNameWithoutExt + ".tiff"); + // Cast the resolved field value to BaseEncodeType + BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null); + + // Create a barcode generator with the resolved type and code text + using (var generator = new BarcodeGenerator(encodeType, codeText)) + { + // Set a higher resolution for better quality TIFF output + generator.Parameters.Resolution = 300; + + // Build output file name (same as XML but with .tif extension) + string outputFileName = Path.GetFileNameWithoutExtension(xmlPath) + ".tif"; + string outputPath = Path.Combine(outputFolder, outputFileName); - // Save the generated barcode image as a TIFF file - generator.Save(tiffPath, BarCodeImageFormat.Tiff); - Console.WriteLine($"Generated barcode: {tiffPath}"); + // Save the generated barcode as a TIFF image + generator.Save(outputPath, BarCodeImageFormat.Tiff); + Console.WriteLine($"Generated barcode: {outputPath}"); + } + } + catch (Exception ex) + { + // Log any errors encountered while processing the current XML file + Console.WriteLine($"Error processing '{xmlPath}': {ex.Message}"); } } + + // Program completes without waiting for input } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/batch-process-list-of-identifiers-generate-codabar-barcodes-with-start-symbol-c-and-save-each-as-tiff-file.cs b/one-dimensional-barcode-types/batch-process-list-of-identifiers-generate-codabar-barcodes-with-start-symbol-c-and-save-each-as-tiff-file.cs index cffbc6e..7fd11cc 100644 --- a/one-dimensional-barcode-types/batch-process-list-of-identifiers-generate-codabar-barcodes-with-start-symbol-c-and-save-each-as-tiff-file.cs +++ b/one-dimensional-barcode-types/batch-process-list-of-identifiers-generate-codabar-barcodes-with-start-symbol-c-and-save-each-as-tiff-file.cs @@ -1,60 +1,70 @@ -// Title: Generate Codabar barcodes in batch and save as TIFF files -// Description: Demonstrates how to encode a list of identifiers into Codabar barcodes with start/stop symbol 'C' and store each image as a TIFF file. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and Codabar settings. Typical use cases include batch creation of inventory labels, shipping tags, or any scenario requiring multiple Codabar images. Developers often need to configure start/stop symbols, choose image formats, and manage output directories. +// Title: Generate Codabar Barcodes in Batch and Save as TIFF +// Description: This example demonstrates how to generate Codabar barcodes with a start/stop symbol of C for a list of identifiers and save each barcode as a TIFF image file. +// Category-Description: Learn how to perform batch barcode generation using Aspose.BarCode. The sample utilizes the BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes to create Codabar symbols, configure visual properties, and export images. Ideal for developers needing to automate barcode creation for inventory, shipping, or labeling workflows where multiple codes must be produced efficiently. // Prompt: Batch process a list of identifiers, generate Codabar barcodes with start symbol C, and save each as a TIFF file. -// Tags: barcode symbology, batch processing, tiff output, codabar, aspnet, aspose.barcode, barcode generation +// Tags: barcode, codabar, batch, tiff, generation, aspose.barcode, aspose.drawing, image, console using System; +using System.Collections.Generic; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Demonstrates batch generation of Codabar barcodes with start/stop symbol 'C' and saves them as TIFF images. +/// Demonstrates batch creation of Codabar barcodes with a start/stop symbol of 'C' and saves each as a TIFF file. /// class Program { /// - /// Entry point that creates barcodes for a predefined set of identifiers and writes them to the file system. + /// Entry point of the example. Generates barcodes for a predefined list of identifiers. /// static void Main() { - // Sample identifiers to encode as Codabar barcodes. - string[] identifiers = new string[] + // Define a sample list of identifiers to encode as Codabar barcodes. + List identifiers = new List { "12345", "67890", "ABCDEF", "987654321", - "CODE123" + "C12345" }; - // Ensure the output directory exists. - string outputDir = "Barcodes"; - if (!Directory.Exists(outputDir)) + // Specify the output folder where TIFF files will be stored. + string outputFolder = "Barcodes"; + if (!Directory.Exists(outputFolder)) { - Directory.CreateDirectory(outputDir); + // Create the folder if it does not already exist. + Directory.CreateDirectory(outputFolder); } - // Process each identifier and generate a corresponding barcode. + // Iterate over each identifier and generate a corresponding barcode. foreach (string id in identifiers) { - // Create a barcode generator for Codabar with the current identifier. - using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, id)) + // Initialize a Codabar barcode generator with the current identifier as the code text. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Codabar, id)) { - // Configure the Codabar start and stop symbols to 'C'. + // Configure the start and stop symbols to 'C'. generator.Parameters.Barcode.Codabar.StartSymbol = CodabarSymbol.C; generator.Parameters.Barcode.Codabar.StopSymbol = CodabarSymbol.C; - // Build the full file path for the TIFF output. - string filePath = Path.Combine(outputDir, $"{id}.tif"); + // Optional: set visual colors (black barcode on white background). + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + + // Build the full file path for the output TIFF image. + string fileName = Path.Combine(outputFolder, $"barcode_{id}.tiff"); // Save the generated barcode as a TIFF file. - generator.Save(filePath, BarCodeImageFormat.Tiff); + generator.Save(fileName, BarCodeImageFormat.Tiff); - // Inform the user that the file was saved. - Console.WriteLine($"Saved barcode for '{id}' to '{filePath}'."); + // Log the successful generation to the console. + Console.WriteLine($"Generated barcode for '{id}' -> {fileName}"); } } + + // Indicate that all barcodes have been processed. + Console.WriteLine("All barcodes have been generated."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/configure-barcode-resolution-to-300-dpi-and-save-generated-image-as-high-resolution-jpeg.cs b/one-dimensional-barcode-types/configure-barcode-resolution-to-300-dpi-and-save-generated-image-as-high-resolution-jpeg.cs index 3693e2c..8ae7cee 100644 --- a/one-dimensional-barcode-types/configure-barcode-resolution-to-300-dpi-and-save-generated-image-as-high-resolution-jpeg.cs +++ b/one-dimensional-barcode-types/configure-barcode-resolution-to-300-dpi-and-save-generated-image-as-high-resolution-jpeg.cs @@ -1,37 +1,46 @@ -// Title: Generate High-Resolution Barcode JPEG -// Description: This example creates a Code128 barcode, configures the image resolution to 300 DPI, and saves it as a high‑resolution JPEG file. -// Category-Description: Demonstrates Aspose.BarCode generation features, focusing on the BarcodeGenerator class to produce printable barcodes. Typical use cases include creating high‑quality barcode images for packaging, shipping labels, or marketing materials. Developers often need to adjust resolution and output format using the Parameters and Save methods. +// Title: Generate high‑resolution Code128 barcode and save as JPEG +// Description: Demonstrates configuring the barcode generator resolution to 300 DPI and exporting the result as a high‑quality JPEG image. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to adjust rendering parameters such as resolution. It uses the BarcodeGenerator class together with EncodeTypes and BarCodeImageFormat to create barcodes for common use cases like product labeling, inventory tracking, and document embedding. Developers often need to control DPI to meet print‑ready specifications or to ensure clarity on high‑resolution displays. // Prompt: Configure barcode resolution to 300 DPI and save the generated image as a high‑resolution JPEG. -// Tags: code128, resolution, jpeg, generation, aspose.barcode +// Tags: code128, resolution, jpeg, barcode, generation, aspose.barcode using System; +using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Example program that generates a Code128 barcode image with a resolution of 300 DPI -/// and saves it as a high‑resolution JPEG file. +/// Example program that creates a Code128 barcode, sets its resolution to 300 DPI, +/// and saves it as a high‑resolution JPEG image. /// class Program { /// - /// Entry point of the application. Generates the barcode and writes the output file. + /// Entry point of the application. /// static void Main() { - // Define the output file path for the generated barcode image - const string outputPath = "barcode_300dpi.jpg"; + // Define the output file path for the generated JPEG image. + string outputPath = "high_res_barcode.jpg"; - // Initialize the barcode generator with Code128 symbology and sample data - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Ensure the target directory exists; create it if necessary. + string directory = Path.GetDirectoryName(outputPath); + if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) { - // Configure the image resolution to 300 DPI for high‑quality output + Directory.CreateDirectory(directory); + } + + // Initialize a barcode generator for the Code128 symbology with sample data. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789")) + { + // Configure the rendering resolution to 300 DPI (float literal required). generator.Parameters.Resolution = 300f; - // Save the barcode as a JPEG image using the specified resolution + // Save the generated barcode as a high‑resolution JPEG image. generator.Save(outputPath, BarCodeImageFormat.Jpeg); } - // Inform the user where the barcode image has been saved - Console.WriteLine($"Barcode image saved to: {outputPath}"); + // Output the full path of the saved barcode image. + Console.WriteLine($"Barcode saved to: {Path.GetFullPath(outputPath)}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/configure-barcode-to-use-mod16-checksum-generate-image-and-programmatically-verify-checksum-matches-expected-mod16-value.cs b/one-dimensional-barcode-types/configure-barcode-to-use-mod16-checksum-generate-image-and-programmatically-verify-checksum-matches-expected-mod16-value.cs index 3294fc0..2474b3b 100644 --- a/one-dimensional-barcode-types/configure-barcode-to-use-mod16-checksum-generate-image-and-programmatically-verify-checksum-matches-expected-mod16-value.cs +++ b/one-dimensional-barcode-types/configure-barcode-to-use-mod16-checksum-generate-image-and-programmatically-verify-checksum-matches-expected-mod16-value.cs @@ -1,75 +1,73 @@ -// Title: Codabar barcode generation with Mod16 checksum and verification -// Description: Demonstrates configuring a Codabar barcode to use the Mod16 checksum, generating an image, and programmatically verifying the checksum during recognition. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, showcasing how to set checksum algorithms (e.g., Mod16) using BarcodeGenerator and validate them with BarCodeReader. Developers often need to ensure data integrity for 1D symbologies like Codabar, making checksum configuration and verification essential in inventory, logistics, and point‑of‑sale applications. +// Title: Codabar Barcode Generation with Mod16 Checksum and Verification +// Description: Demonstrates how to generate a Codabar barcode using the Mod16 checksum algorithm, save it as an image, and programmatically verify the checksum during recognition. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, illustrating the use of BarcodeGenerator for creating barcodes with specific checksum settings and BarCodeReader for decoding and validating them. Key API classes include BarcodeGenerator, BarCodeReader, and related parameter objects. Typical scenarios involve ensuring data integrity in logistics, inventory, and point‑of‑sale systems where checksum validation is required. Developers often need to configure checksum modes, render barcode images, and confirm checksum correctness programmatically. // Prompt: Configure barcode to use Mod16 checksum, generate image, and programmatically verify checksum matches expected Mod16 value. -// Tags: codabar, checksum, mod16, barcode generation, barcode recognition, aspose.barcode, png +// Tags: codabar, checksum, mod16, barcode generation, barcode recognition, image output, aspose.barcode, png 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 creates a Codabar barcode with a Mod16 checksum, -/// saves it as an image, and then reads the image to verify the checksum. +/// Generates a Codabar barcode with Mod16 checksum, saves it as a PNG image, +/// then reads the image back to verify that the checksum matches the expected value. /// class Program { /// - /// Entry point of the example. Generates the barcode, saves it, and validates the checksum. + /// Entry point of the example. Performs barcode creation, saving, and checksum verification. /// static void Main() { - // Define the full path for the output PNG image. - string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "codabar_mod16.png"); + // Define the output file path for the generated barcode image. + const string outputPath = "codabar.png"; - // Create a Codabar barcode generator with the sample data "123456". - using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, "123456")) + // Create a Codabar barcode generator with a sample code. + // Start/stop characters (A) are required for Codabar. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Codabar, "A123456A")) { - // Enable checksum generation for the barcode. + // Enable checksum generation and select the Mod16 algorithm. generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes; - - // Specify that the Mod16 algorithm should be used for the checksum. generator.Parameters.Barcode.Codabar.ChecksumMode = CodabarChecksumMode.Mod16; - // Save the generated barcode image to the specified path. - generator.Save(imagePath); - } + // Optional: display the checksum digit in the human‑readable text. + generator.Parameters.Barcode.ChecksumAlwaysShow = true; - // Verify that the barcode image file was successfully created. - if (!File.Exists(imagePath)) - { - Console.WriteLine("Failed to generate barcode image."); - return; + // Save the barcode image directly to a file (PNG format). + generator.Save(outputPath, BarCodeImageFormat.Png); } - // Initialize a barcode reader for the generated image, targeting Codabar symbology. - using (var reader = new BarCodeReader(imagePath, DecodeType.Codabar)) + // Read the generated barcode image and verify the checksum. + using (BarCodeReader reader = new BarCodeReader(outputPath, DecodeType.Codabar)) { - // Turn on checksum validation during the recognition process. + // Ensure checksum validation is performed during recognition. reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; - // Iterate through all detected barcodes (should be only one in this case). + // Iterate through all recognized barcode results (should be one in this case). foreach (BarCodeResult result in reader.ReadBarCodes()) { - // Retrieve the decoded value without the checksum and the checksum itself. - string valueWithoutChecksum = result.Extended.OneD.Value; - string checksum = result.Extended.OneD.CheckSum; + // The full CodeText includes the checksum digit added by the generator. + string fullCodeText = result.CodeText; - Console.WriteLine($"Decoded Value (without checksum): {valueWithoutChecksum}"); - Console.WriteLine($"Detected Checksum (Mod16): {checksum}"); + // Extract the checksum digit from the recognized CodeText (last character). + string extractedChecksum = fullCodeText.Substring(fullCodeText.Length - 1); - // Simple verification: ensure a checksum was detected for Mod16. - if (string.IsNullOrEmpty(checksum)) - { - Console.WriteLine("Checksum verification failed: checksum is missing."); - } - else - { - Console.WriteLine("Checksum verification succeeded."); - } + // Get the checksum reported by the recognition engine. + string reportedChecksum = result.Extended.OneD.CheckSum; + + // Verify that both checksum values match. + bool isChecksumMatch = string.Equals(extractedChecksum, reportedChecksum, StringComparison.Ordinal); + + Console.WriteLine($"Full CodeText: {fullCodeText}"); + Console.WriteLine($"Extracted Checksum (last char): {extractedChecksum}"); + Console.WriteLine($"Reported Checksum (Extended.OneD): {reportedChecksum}"); + Console.WriteLine($"Checksum verification result: {(isChecksumMatch ? "PASS" : "FAIL")}"); } } + + // Program ends normally. } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/configure-barcode-to-use-mod16-checksum-mode-and-validate-checksum-after-generation.cs b/one-dimensional-barcode-types/configure-barcode-to-use-mod16-checksum-mode-and-validate-checksum-after-generation.cs index 463e4e4..153bf28 100644 --- a/one-dimensional-barcode-types/configure-barcode-to-use-mod16-checksum-mode-and-validate-checksum-after-generation.cs +++ b/one-dimensional-barcode-types/configure-barcode-to-use-mod16-checksum-mode-and-validate-checksum-after-generation.cs @@ -1,8 +1,8 @@ -// Title: Codabar barcode generation with Mod16 checksum and validation -// Description: Demonstrates how to generate a Codabar barcode using Mod16 checksum mode and then read it back while validating the checksum. -// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating 1D barcodes with specific checksum settings and BarCodeReader for decoding and validating those barcodes. Developers working with inventory, shipping, or point‑of‑sale systems often need to configure checksum modes such as Mod16 for Codabar and ensure data integrity during scanning. +// Title: Codabar Barcode Generation with Mod16 Checksum and Validation +// Description: Demonstrates how to generate a Codabar barcode using the Mod16 checksum mode, embed the checksum in the human‑readable text, and then validate the checksum during recognition. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes, configuring checksum settings via the Parameters.Barcode properties, and employing BarCodeReader to decode and verify checksums. Developers working with one‑dimensional symbologies such as Codabar often need to ensure data integrity by generating and validating checksums, making this pattern essential for inventory, shipping, and point‑of‑sale applications. // Prompt: Configure barcode to use Mod16 checksum mode and validate the checksum after generation. -// Tags: codabar, checksum, mod16, barcode generation, barcode recognition, aspose.barcode +// Tags: codabar, checksum, mod16, barcode generation, barcode recognition, aspose.barcode, .net using System; using System.IO; @@ -12,49 +12,58 @@ /// /// Generates a Codabar barcode with Mod16 checksum, saves it as an image, -/// then reads the image back and validates the checksum using Aspose.BarCode. +/// and then reads the image back to validate the checksum. /// class Program { /// - /// Entry point of the example. Executes barcode creation, saving, and validation. + /// Entry point of the example. Creates a barcode, writes it to disk, + /// and verifies the checksum during recognition. /// static void Main() { - // Define the full path for the output PNG image - string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "codabar_mod16.png"); + // Define the output file path for the generated barcode image. + string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "codabar.png"); - // -------------------------------------------------------------------- - // Generate a Codabar barcode with Mod16 checksum enabled - // -------------------------------------------------------------------- - using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, "A123456B")) + // ------------------------------------------------------------ + // Barcode generation + // ------------------------------------------------------------ + // Create a Codabar barcode generator with sample data. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Codabar, "A123456A")) { - // Turn on checksum generation for the barcode + // Enable checksum generation for the barcode. generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes; - // Specify Mod16 checksum mode for Codabar symbology + // Set the checksum mode to Mod16 (recommended AIIM for Codabar). generator.Parameters.Barcode.Codabar.ChecksumMode = CodabarChecksumMode.Mod16; - // Save the generated barcode image to the specified path - generator.Save(outputPath); + // Optionally display the checksum in the human‑readable text. + generator.Parameters.Barcode.ChecksumAlwaysShow = true; + + // Save the generated barcode image to the specified path. + generator.Save(imagePath); } - // -------------------------------------------------------------------- - // Read the generated barcode image and validate its checksum - // -------------------------------------------------------------------- - using (var reader = new BarCodeReader(outputPath, DecodeType.Codabar)) + // ------------------------------------------------------------ + // Barcode recognition and checksum validation + // ------------------------------------------------------------ + // Initialize a reader for the saved image, specifying Codabar as the decode type. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.Codabar)) { - // Enable checksum validation during the recognition process + // Enable checksum validation during the reading process. reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; - // Iterate through all detected barcodes (should be only one in this case) + // Iterate through all detected barcodes in the image. foreach (BarCodeResult result in reader.ReadBarCodes()) { - // Output the decoded text - Console.WriteLine($"CodeText: {result.CodeText}"); - - // For 1D barcodes, the checksum value is available via Extended.OneD.CheckSum - Console.WriteLine($"Checksum: {result.Extended.OneD.CheckSum}"); + // Output the type of barcode detected. + Console.WriteLine("Detected Barcode Type: " + result.CodeTypeName); + // Output the full code text, including checksum if displayed. + Console.WriteLine("Code Text (including checksum if shown): " + result.CodeText); + // Output the extracted value without the checksum. + Console.WriteLine("Extracted Value (without checksum): " + result.Extended.OneD.Value); + // Output the extracted checksum value. + Console.WriteLine("Extracted Checksum: " + result.Extended.OneD.CheckSum); } } } diff --git a/one-dimensional-barcode-types/configure-barcode-to-use-transparent-background-for-overlay-on-existing-images.cs b/one-dimensional-barcode-types/configure-barcode-to-use-transparent-background-for-overlay-on-existing-images.cs index d3cadd7..de85a45 100644 --- a/one-dimensional-barcode-types/configure-barcode-to-use-transparent-background-for-overlay-on-existing-images.cs +++ b/one-dimensional-barcode-types/configure-barcode-to-use-transparent-background-for-overlay-on-existing-images.cs @@ -1,8 +1,8 @@ -// Title: Generate a Code128 barcode with transparent background and overlay on an image -// Description: Demonstrates how to create a Code128 barcode with a transparent background and draw it onto an existing image, saving the result as a PNG. -// Category-Description: This example belongs to the Aspose.BarCode image overlay category, illustrating the use of BarcodeGenerator, BarcodeParameters, and Aspose.Drawing to combine barcodes with background images. Typical scenarios include adding barcodes to product photos, documents, or UI elements without obscuring the underlying graphics. Developers often need to control barcode colors and transparency for seamless integration. +// Title: Overlay Barcode with Transparent Background on an Image +// Description: Demonstrates generating a Code128 barcode with a transparent background and drawing it onto an existing PNG image. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to create barcodes with custom visual properties and combine them with existing graphics using Aspose.Drawing. It highlights the use of BarcodeGenerator, setting Parameters.BackColor to transparent, and drawing the generated bitmap onto another image—common tasks for developers who need to embed barcodes into product photos, marketing materials, or UI overlays. // Prompt: Configure barcode to use a transparent background for overlay on existing images. -// Tags: code128, transparent background, png, barcodegenerator, aspose.barcode, aspose.drawing +// Tags: barcode, code128, transparent background, overlay, image, aspose.barcode, aspose.drawing, png, generation using System; using System.IO; @@ -11,61 +11,58 @@ using Aspose.Drawing.Imaging; /// -/// Demonstrates generating a Code128 barcode with a transparent background and overlaying it onto an existing image. +/// Example program that creates a Code128 barcode with a transparent background +/// and overlays it onto an existing image. /// class Program { /// - /// Entry point. Loads or creates a base image, generates a transparent barcode, draws it onto the base, and saves the result. + /// Entry point. Generates the barcode, draws it onto the background image, + /// and saves the combined result. /// static void Main() { - // Define file paths for the background image and the resulting combined image. - string inputPath = "input.png"; + // Paths for the background image and the resulting image + string backgroundPath = "background.png"; string outputPath = "output.png"; - // Load the existing background image; if it does not exist, create a simple white canvas. - Image baseImage; - if (File.Exists(inputPath)) + // Verify that the background image exists + if (!File.Exists(backgroundPath)) { - baseImage = Image.FromFile(inputPath); - } - else - { - // Create a white bitmap of size 400x200 as a placeholder background. - baseImage = new Bitmap(400, 200); - using (Graphics g = Graphics.FromImage(baseImage)) - { - g.Clear(Color.White); - } + Console.WriteLine("Background image not found: " + backgroundPath); + return; } - // Ensure the base image is disposed after processing. - using (baseImage) + // Load the background image + using (Bitmap background = (Bitmap)Image.FromFile(backgroundPath)) { - // Initialize a barcode generator for Code128 with sample data. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // Create a barcode generator for Code128 with sample text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) { - // Configure the barcode to have a transparent background. + // Set the barcode background to transparent so underlying image shows through generator.Parameters.BackColor = Color.Transparent; - // Optionally set the bar (foreground) color to black. + + // Optional: set the bar (foreground) color to black generator.Parameters.Barcode.BarColor = Color.Black; - // Generate the barcode as a bitmap. - using (Bitmap barcodeImage = generator.GenerateBarCodeImage()) + // Generate the barcode image as a bitmap + using (Bitmap barcode = generator.GenerateBarCodeImage()) { - // Draw the barcode onto the base image at coordinates (10,10). - using (Graphics graphics = Graphics.FromImage(baseImage)) + // Draw the barcode onto the background image at position (0,0) + using (Graphics graphics = Graphics.FromImage(background)) { - graphics.DrawImage(barcodeImage, new Point(10, 10)); + graphics.DrawImage(barcode, new Point(0, 0)); } } } - // Save the final image with the transparent barcode overlay as a PNG file. - baseImage.Save(outputPath, ImageFormat.Png); + // Save the combined image as PNG to preserve transparency + using (FileStream outStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) + { + background.Save(outStream, ImageFormat.Png); + } } - Console.WriteLine($"Combined image saved to {outputPath}"); + Console.WriteLine("Barcode overlay saved to " + outputPath); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/configure-barcode-to-use-transparent-background-then-embed-generated-png-into-html-email-body.cs b/one-dimensional-barcode-types/configure-barcode-to-use-transparent-background-then-embed-generated-png-into-html-email-body.cs index 7e8bed8..d6f4e70 100644 --- a/one-dimensional-barcode-types/configure-barcode-to-use-transparent-background-then-embed-generated-png-into-html-email-body.cs +++ b/one-dimensional-barcode-types/configure-barcode-to-use-transparent-background-then-embed-generated-png-into-html-email-body.cs @@ -1,25 +1,23 @@ -// Title: Generate Transparent Barcode PNG and Embed in HTML Email -// Description: Demonstrates creating a Code128 barcode with a transparent background, saving it as PNG, and embedding the image directly into an HTML email body using a data URI. -// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to customize barcode appearance (background, colors) and integrate the generated image into HTML content. It uses BarcodeGenerator, EncodeTypes, BarCodeImageFormat, and Aspose.Drawing classes. Developers often need to embed barcodes in emails or web pages without external image files, and this snippet shows the typical workflow. +// Title: Generate transparent barcode PNG and embed in HTML email +// Description: Demonstrates how to create a Code128 barcode with a transparent background, save it as a PNG, convert it to Base64, and embed it directly into an HTML email body. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to produce barcode images with custom visual properties. Typical scenarios include creating email-friendly barcode graphics, web embedding, or generating reports where a transparent background is required. Developers often need to customize colors, export formats, and embed images as data URIs for seamless integration. // Prompt: Configure barcode to use transparent background, then embed generated PNG into an HTML email body. -// Tags: code128, transparent background, png, html email, barcode generation, aspose.barcode, aspose.drawing +// Tags: code128, transparent background, png, html email, base64, aspose.barcode, barcode generation using System; using System.IO; -using System.Text; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// /// Example program that generates a Code128 barcode with a transparent background, -/// converts it to a Base64 PNG, and embeds it in an HTML email body. +/// encodes the image as Base64, and embeds it in an HTML email body. /// class Program { /// - /// Entry point of the example. Generates the barcode, encodes it, and writes the HTML. + /// Entry point of the application. /// static void Main() { @@ -29,25 +27,26 @@ static void Main() // Configure the barcode to have a transparent background generator.Parameters.BackColor = Color.Transparent; - // Optionally set the bar (foreground) color to black - generator.Parameters.Barcode.BarColor = Color.Black; - - // Save the generated barcode to a memory stream in PNG format - using (var ms = new MemoryStream()) + // Create a memory stream to hold the generated PNG image + using (var memoryStream = new MemoryStream()) { - generator.Save(ms, BarCodeImageFormat.Png); + // Save the barcode image to the memory stream in PNG format + generator.Save(memoryStream, BarCodeImageFormat.Png); - // Convert the PNG bytes to a Base64 string for embedding in HTML - string base64 = Convert.ToBase64String(ms.ToArray()); + // Convert the PNG bytes to a Base64 string for embedding + string base64Image = Convert.ToBase64String(memoryStream.ToArray()); - // Build a simple HTML email body that includes the barcode image via a data URI - string htmlBody = $"" + - $"

Generated Barcode

" + - $"\"Barcode\"/" + - $""; + // Build the HTML email body with the barcode embedded as a data URI + string htmlEmailBody = $@" + + +

Here is the generated barcode with a transparent background:

+ + +"; - // Output the HTML; in a real scenario this would be set as the email body - Console.WriteLine(htmlBody); + // Output the HTML content to the console (or further processing) + Console.WriteLine(htmlEmailBody); } } } diff --git a/one-dimensional-barcode-types/configure-code-16k-quiet-zones-to-match-printer-margin-requirements-generate-pdf-output.cs b/one-dimensional-barcode-types/configure-code-16k-quiet-zones-to-match-printer-margin-requirements-generate-pdf-output.cs index beb86ee..991afa5 100644 --- a/one-dimensional-barcode-types/configure-code-16k-quiet-zones-to-match-printer-margin-requirements-generate-pdf-output.cs +++ b/one-dimensional-barcode-types/configure-code-16k-quiet-zones-to-match-printer-margin-requirements-generate-pdf-output.cs @@ -1,41 +1,76 @@ -// Title: Configure Code 16K barcode quiet zones and generate PDF -// Description: Demonstrates setting custom quiet zone coefficients for a Code 16K barcode and saving it as a PDF, useful for matching printer margin requirements. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on symbology-specific parameter configuration. It showcases the BarcodeGenerator class, EncodeTypes enumeration, and barcode parameter objects to adjust quiet zones and module size. Developers often need to tailor barcode dimensions for printing workflows, ensuring proper margins and readability. +// Title: Generate Code 16K Barcode with Custom Quiet Zones and Export to PDF +// Description: Demonstrates how to configure quiet zone coefficients for a Code 16K barcode, render it as PNG, and embed the image into a PDF document using Aspose.BarCode and Aspose.Pdf. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to customize barcode parameters (quiet zones, colors, dimensions) and combine the output with Aspose.Pdf for document creation. Key API classes include BarcodeGenerator, EncodeTypes, BarCodeImageFormat, and Aspose.Pdf.Document. Typical use cases involve preparing barcodes that meet specific printer margin requirements and packaging them into PDF reports or labels. // Prompt: Configure Code 16K quiet zones to match printer margin requirements, generate PDF output. -// Tags: code16k, quiet zones, pdf output, barcode generation, aspose.barcode, symbology +// Tags: code16k, quiet zones, barcode generation, pdf output, aspose.barcode, aspose.pdf, c# using System; -using Aspose.BarCode; +using System.IO; using Aspose.BarCode.Generation; +using Aspose.BarCode.ComplexBarcode; +using Aspose.Pdf; /// -/// Generates a Code 16K barcode with custom quiet zones and saves it as a PDF. +/// Example program that creates a Code 16K barcode with custom quiet zones, +/// saves it as a PNG image, and embeds the image into a PDF document. /// class Program { /// - /// Entry point of the example. Configures quiet zones, module size, and creates the PDF file. + /// Entry point of the application. /// static void Main() { - // Sample Code16K barcode text (must meet Code16K requirements) - const string codeText = "12345678901234567890"; + // Define the output PDF file path. + string pdfPath = "Code16K.pdf"; - // Initialize the barcode generator for Code16K symbology - using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, codeText)) + // Create a Code16K barcode generator with a sample numeric value. + using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, "1234567890123456")) { - // Configure quiet zones (coefficients are multiples of XDimension) - // Adjust these values to match the printer's required margins. - generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = 20; // e.g., 20 * XDimension - generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = 5; // e.g., 5 * XDimension + // Set foreground (barcode) and background colors. + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; - // Optional: define module size (XDimension) for better control of overall size - generator.Parameters.Barcode.XDimension.Point = 2f; // 2 points per module + // Configure quiet zones to satisfy printer margin requirements. + // Minimum allowed values are 10 (left) and 1 (right); increase as needed. + generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = 12; + generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = 2; - // Save the barcode directly as a PDF file - generator.Save("code16k.pdf"); + // Optional: adjust the module size (X dimension) for better visibility. + generator.Parameters.Barcode.XDimension.Point = 2f; + + // Render the barcode 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. + + // Create a new PDF document and add a page. + using (var pdfDoc = new Document()) + { + var page = pdfDoc.Pages.Add(); + + // Create an image object that references the barcode stream. + var pdfImage = new Aspose.Pdf.Image + { + ImageStream = barcodeStream, + // Set the displayed size (values are in points). + FixWidth = 200.0, + FixHeight = 100.0, + // Center the image on the page. + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }; + + // Add the image to the page's paragraph collection. + page.Paragraphs.Add(pdfImage); + + // Save the PDF document to the specified file. + pdfDoc.Save(pdfPath); + } + } } - Console.WriteLine("Code16K barcode with custom quiet zones saved to code16k.pdf"); + Console.WriteLine($"PDF with Code16K barcode generated: {pdfPath}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/configure-databar-parameters-to-generate-stacked-barcodes-with-aspect-ratio-ten-disable-2d-component-for-testing.cs b/one-dimensional-barcode-types/configure-databar-parameters-to-generate-stacked-barcodes-with-aspect-ratio-ten-disable-2d-component-for-testing.cs index ea24f67..57f137f 100644 --- a/one-dimensional-barcode-types/configure-databar-parameters-to-generate-stacked-barcodes-with-aspect-ratio-ten-disable-2d-component-for-testing.cs +++ b/one-dimensional-barcode-types/configure-databar-parameters-to-generate-stacked-barcodes-with-aspect-ratio-ten-disable-2d-component-for-testing.cs @@ -1,37 +1,40 @@ -// Title: Generate GS1 DataBar Stacked barcode with custom aspect ratio -// Description: Demonstrates configuring DataBar parameters to create a stacked barcode with an aspect ratio of ten and disabling the 2D composite component. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on DataBar symbologies. It showcases the use of BarcodeGenerator, EncodeTypes, and DataBar parameters to customize appearance, a common need for developers generating retail or logistics barcodes where specific sizing and component settings are required. +// Title: Generate Stacked DataBar Barcode with Custom Aspect Ratio +// Description: Demonstrates how to configure Aspose.BarCode to create a stacked DataBar barcode, set its aspect ratio to ten, and disable the 2D composite component. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on DataBar symbologies. It shows usage of the BarcodeGenerator class with EncodeTypes.DatabarStacked, adjusting DataBar parameters such as AspectRatio and Is2DCompositeComponent. Developers commonly use these settings to meet specific size requirements or to test barcode components without the 2D composite part. // Prompt: Configure DataBar parameters to generate stacked barcodes with aspect ratio ten, disable 2D component for testing. -// Tags: databar, stacked, aspectratio, disable2d, png, aspose.barcode, generation +// Tags: databar, stacked, aspectratio, disable-2d-component, barcode-generation, aspose.barcode, csharp using System; using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Demonstrates configuring DataBar parameters to generate a stacked barcode with a custom aspect ratio and without a 2D composite component. +/// Demonstrates generating a stacked DataBar barcode with a custom aspect ratio and disabled 2D component using Aspose.BarCode. /// class Program { /// - /// Entry point of the example. Generates and saves a GS1 DataBar Stacked barcode image. + /// Entry point that creates the barcode, configures parameters, saves the image, and writes a confirmation message. /// static void Main() { - // Initialize a BarcodeGenerator for the GS1 DataBar Stacked symbology with sample data - using (var generator = new BarcodeGenerator(EncodeTypes.DatabarStacked, "(01)12345678901231")) + // Define a sample GTIN code text for DataBar (required format) + string codeText = "(01)01234567890123"; + + // Initialize a DataBar stacked barcode generator with the specified text + using (var generator = new BarcodeGenerator(EncodeTypes.DatabarStacked, codeText)) { - // Set the DataBar aspect ratio to 10 (height divided by width) + // Set the DataBar aspect ratio to 10 (height/width) generator.Parameters.Barcode.DataBar.AspectRatio = 10f; - // Disable the optional 2D composite component for testing purposes + // Disable the 2D composite component for testing purposes generator.Parameters.Barcode.DataBar.Is2DCompositeComponent = false; - // Save the generated barcode as a PNG image file + // Save the generated barcode image to a PNG file generator.Save("databar_stacked.png"); } - // Output a simple confirmation message + // Inform the user that the barcode was generated successfully Console.WriteLine("DataBar stacked barcode generated successfully."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/configure-itf-parameters-with-thick-frame-style-and-quiet-zone-coefficient-03-render-tiff.cs b/one-dimensional-barcode-types/configure-itf-parameters-with-thick-frame-style-and-quiet-zone-coefficient-03-render-tiff.cs index 198ec4e..ddcabc6 100644 --- a/one-dimensional-barcode-types/configure-itf-parameters-with-thick-frame-style-and-quiet-zone-coefficient-03-render-tiff.cs +++ b/one-dimensional-barcode-types/configure-itf-parameters-with-thick-frame-style-and-quiet-zone-coefficient-03-render-tiff.cs @@ -1,52 +1,63 @@ -// Title: Configure ITF14 barcode with thick frame and quiet zone coefficient, render as TIFF -// Description: Demonstrates setting ITF14 barcode parameters such as a thick frame border and handling quiet zone coefficient validation, then saving the result as a TIFF image. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to customize ITF14 symbology using the BarcodeGenerator class. Typical use cases include creating product packaging barcodes with specific border styles and quiet zone settings. Developers often need to adjust border thickness, frame style, and output image format for compliance and branding requirements. +// Title: Configure ITF14 barcode with thick frame border and quiet zone coefficient, save as TIFF +// Description: Demonstrates how to set a thick frame border and adjust the quiet zone coefficient for an ITF14 barcode, then render the result as a TIFF image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes. Typical use cases include customizing barcode appearance such as border style, thickness, and quiet zone settings before exporting to image formats. Developers often need to fine‑tune these parameters for compliance with printing standards and visual requirements. // Prompt: Configure ITF parameters with thick frame style and quiet zone coefficient 0.3, render TIFF. -// Tags: itf14, barcode, generation, tiff, aspose.barcode, aspose.drawing +// Tags: itf14, barcode, configuration, tiff, aspose.barcode, generation using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing.Imaging; +using Aspose.Drawing; /// -/// Demonstrates configuring ITF14 barcode parameters and saving as TIFF. +/// Demonstrates configuring ITF14 barcode parameters and saving as a TIFF image. /// class Program { /// - /// Entry point. Generates an ITF14 barcode with a thick frame border, validates quiet zone coefficient, and saves the image. + /// Entry point that creates, configures, and saves an ITF14 barcode. /// static void Main() { - // Sample ITF14 code text (13 digits, check digit will be added automatically) - const string codeText = "1234567890123"; + // Define the output file path (current directory + filename) + string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "itf.tiff"); - // Desired quiet zone coefficient (invalid per API constraints) - const float quietZoneCoef = 0.3f; - - // Validate quiet zone coefficient before applying - // The API requires a coefficient of at least 10; otherwise we abort. - if (quietZoneCoef < 10f) + // Initialize a barcode generator for ITF14 (requires exactly 14 digits) + using (var generator = new BarcodeGenerator(EncodeTypes.ITF14, "12345678901231")) { - Console.WriteLine($"Quiet zone coefficient {quietZoneCoef} is invalid. It must be >= 10."); - return; - } + // ------------------------------ + // Configure ITF-specific settings + // ------------------------------ - // Create the barcode generator for ITF14 - using (var generator = new BarcodeGenerator(EncodeTypes.ITF14, codeText)) - { - // Configure a thick frame border + // Set a thick frame border around the barcode generator.Parameters.Barcode.ITF.BorderType = ITF14BorderType.Frame; - generator.Parameters.Barcode.ITF.BorderThickness.Point = 5f; // thick border - - // If the coefficient were valid, it would be set like this: - // generator.Parameters.Barcode.ITF.QuietZoneCoef = (int)quietZoneCoef; - - // Save the barcode as a TIFF image - generator.Save("itf14.tiff"); + // Example thick border: 5 points + generator.Parameters.Barcode.ITF.BorderThickness.Point = 5f; + + // Attempt to set quiet zone coefficient to 0.3. + // The API expects an integer >= 10, so we handle an invalid value gracefully. + try + { + // 0.3 expressed as an integer multiplier (e.g., 3) will trigger an exception. + generator.Parameters.Barcode.ITF.QuietZoneCoef = 3; + } + catch (ArgumentException ex) + { + // Log the failure and fall back to the minimum allowed value. + Console.WriteLine($"QuietZoneCoef setting failed: {ex.Message}"); + generator.Parameters.Barcode.ITF.QuietZoneCoef = 10; + } + + // ------------------------------ + // Save the generated barcode + // ------------------------------ + + // Render the barcode as a TIFF image and write it to the output path + generator.Save(outputPath, BarCodeImageFormat.Tiff); } - Console.WriteLine("Barcode generated successfully."); + // Inform the user where the file was saved + Console.WriteLine($"Barcode saved to: {outputPath}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/create-barcode-enable-showcodetext-and-position-text-below-bars-with-custom-vertical-offset.cs b/one-dimensional-barcode-types/create-barcode-enable-showcodetext-and-position-text-below-bars-with-custom-vertical-offset.cs index 9e06c07..665f220 100644 --- a/one-dimensional-barcode-types/create-barcode-enable-showcodetext-and-position-text-below-bars-with-custom-vertical-offset.cs +++ b/one-dimensional-barcode-types/create-barcode-enable-showcodetext-and-position-text-below-bars-with-custom-vertical-offset.cs @@ -1,39 +1,33 @@ // Title: Generate Code128 barcode with custom text positioning -// Description: Demonstrates creating a Code128 barcode, enabling the human‑readable text, and moving the text below the bars with a custom vertical offset. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode appearance using the BarcodeGenerator class. It covers setting CodeTextParameters such as Location, Space, and Font to control the display of human‑readable text. Developers often need these settings when integrating barcodes into documents, labels, or UI elements where precise text placement is required. +// Description: Demonstrates creating a Code128 barcode, enabling human-readable text, and positioning the text below the bars with a custom vertical offset. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to configure CodeTextParameters such as location and spacing. It uses BarcodeGenerator, EncodeTypes, and CodeLocation classes to customize human-readable text placement, a common requirement when integrating barcodes into printed labels, invoices, or product packaging. // Prompt: Create a barcode, enable ShowCodeText, and position text below bars with custom vertical offset. -// Tags: code128, showcodetext, verticaloffset, png, barcodelibrary, generation, aspnet, csharp +// Tags: barcode, code128, showcodetext, textposition, verticaloffset, aspnet, aspose.barcode, imageoutput -using System; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; // For color handling if needed +using Aspose.Drawing; /// -/// Example program that generates a Code128 barcode, shows the human‑readable text, -/// and positions the text below the bars with a custom vertical offset. +/// Demonstrates generating a Code128 barcode with human‑readable text positioned below the bars and a custom vertical offset. /// class Program { /// - /// Entry point of the example. Creates the barcode, configures text display, - /// and saves the result as a PNG image. + /// Entry point of the example. Generates the barcode and saves it as a PNG file. /// static void Main() { - // Initialize the barcode generator with Code128 symbology and sample data. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // Initialize a BarcodeGenerator for Code128 with the specified code text. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Ensure the human‑readable text is displayed below the bars. + // Enable human‑readable text and set its location to appear below the barcode bars. generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below; - // Set a custom vertical offset (10 points) between the bars and the text. - generator.Parameters.Barcode.CodeTextParameters.Space.Point = 10f; + // Define a custom vertical space (offset) between the bars and the text. + generator.Parameters.Barcode.CodeTextParameters.Space.Point = 8f; // adjust offset as needed - // Optionally adjust the font size of the displayed text (12 points). - generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 12f; - - // Save the generated barcode image to a PNG file. + // Save the generated barcode image as PNG. generator.Save("barcode.png"); } } diff --git a/one-dimensional-barcode-types/create-barcode-set-forecolor-to-123456-and-verify-exact-color-appears-in-saved-image.cs b/one-dimensional-barcode-types/create-barcode-set-forecolor-to-123456-and-verify-exact-color-appears-in-saved-image.cs index f5784be..5166e6a 100644 --- a/one-dimensional-barcode-types/create-barcode-set-forecolor-to-123456-and-verify-exact-color-appears-in-saved-image.cs +++ b/one-dimensional-barcode-types/create-barcode-set-forecolor-to-123456-and-verify-exact-color-appears-in-saved-image.cs @@ -1,70 +1,69 @@ -// Title: Create Code128 barcode with custom foreground color and verify it -// Description: This example creates a Code128 barcode, sets its bar color to #123456, saves it as a PNG file, and checks that the exact color appears in the generated image. -// Category-Description: Demonstrates Aspose.BarCode generation and image verification techniques. It uses BarcodeGenerator, EncodeTypes, BarCodeImageFormat, and Aspose.Drawing classes to customize barcode appearance, save the image, and programmatically inspect pixel data. Ideal for developers needing to ensure visual fidelity of generated barcodes in automated pipelines. +// Title: Generate Code128 Barcode with Custom Foreground Color and Verify It +// Description: This example creates a Code128 barcode, sets its bar color to the hexadecimal value #123456, saves it as a PNG file, and then checks the saved image to confirm the exact color is present. +// Category-Description: Aspose.BarCode barcode generation examples demonstrating color customization. Shows how to use BarcodeGenerator, set BarColor via Parameters.Barcode, save to PNG, and read the image with Aspose.Drawing.Bitmap for verification. Useful for developers needing precise visual styling of barcodes in .NET applications. // Prompt: Create a barcode, set ForeColor to #123456, and verify the exact color appears in the saved image. -// Tags: code128, color, png, barcode, generation, verification, aspose.barcode, aspose.drawing +// Tags: barcode, code128, color, verification, png, aspose.barcode, aspose.drawing, c# using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Demonstrates creating a barcode with a custom foreground color and verifying the color in the saved image. +/// Demonstrates creating a Code128 barcode with a custom foreground color, +/// saving it to a PNG file, and verifying the color in the output image. /// class Program { /// - /// Entry point of the example. Generates a Code128 barcode, sets its bar color to #123456, saves it as PNG, - /// and scans the resulting image to confirm the exact color is present. + /// Entry point of the example. /// static void Main() { - // Define the output file path for the generated barcode image. - string outputPath = "barcode.png"; + const string outputPath = "barcode.png"; - // Create a BarcodeGenerator for Code128 symbology with sample text "Test123". - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123")) + // Initialize a barcode generator for Code128 symbology with sample text. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "12345")) { - // Set the foreground (bar) color to the custom hex value #123456. - generator.Parameters.Barcode.BarColor = Color.FromArgb(0x12, 0x34, 0x56); - // Set the background color to white to ensure good contrast. - generator.Parameters.BackColor = Color.White; + // Define the desired bar (foreground) color using its RGB components. + var barColor = Color.FromArgb(0x12, 0x34, 0x56); + // Apply the custom color to the barcode. + generator.Parameters.Barcode.BarColor = barColor; - // Save the barcode image in PNG format to the specified path. + // Save the generated barcode as a PNG image. generator.Save(outputPath, BarCodeImageFormat.Png); } - // Verify that the barcode image file was successfully created. + // Ensure the image file was created before attempting verification. if (!File.Exists(outputPath)) { Console.WriteLine("Failed to create the barcode image."); return; } - // Load the saved PNG image for pixel inspection. - using (var bitmap = (Bitmap)Image.FromFile(outputPath)) - { - bool colorFound = false; - // Define the target color to search for in the image. - Color targetColor = Color.FromArgb(0x12, 0x34, 0x56); + bool colorFound = false; + var expectedColor = Color.FromArgb(0x12, 0x34, 0x56); - // Scan the image pixels until the target color is found. + // Load the saved image and scan its pixels for the expected color. + using (var bitmap = new Bitmap(outputPath)) + { for (int y = 0; y < bitmap.Height && !colorFound; y++) { for (int x = 0; x < bitmap.Width && !colorFound; x++) { - // Compare the ARGB values of the current pixel and the target color. - if (bitmap.GetPixel(x, y).ToArgb() == targetColor.ToArgb()) + // Compare each pixel's ARGB value with the expected color. + if (bitmap.GetPixel(x, y).ToArgb() == expectedColor.ToArgb()) { colorFound = true; } } } - - // Output verification result. - Console.WriteLine(colorFound ? "Bar color verified." : "Bar color not found in the image."); } + + // Output the verification result. + Console.WriteLine(colorFound + ? "Bar color #123456 verified in the saved image." + : "Bar color #123456 not found in the saved image."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/create-barcode-set-forecolor-to-dark-red-and-verify-color-appears-correctly-in-saved-png.cs b/one-dimensional-barcode-types/create-barcode-set-forecolor-to-dark-red-and-verify-color-appears-correctly-in-saved-png.cs index a0aac35..9e8eb8b 100644 --- a/one-dimensional-barcode-types/create-barcode-set-forecolor-to-dark-red-and-verify-color-appears-correctly-in-saved-png.cs +++ b/one-dimensional-barcode-types/create-barcode-set-forecolor-to-dark-red-and-verify-color-appears-correctly-in-saved-png.cs @@ -1,8 +1,8 @@ -// Title: Generate Code128 barcode with dark red foreground and verify PNG output -// Description: Demonstrates creating a barcode, setting its foreground color to dark red, saving as PNG, and checking the color in the saved image. -// Category-Description: This example belongs to the Aspose.BarCode generation and image verification category. It shows how to use BarcodeGenerator, set barcode parameters such as BarColor, and work with Aspose.Drawing to inspect pixel data. Developers often need to customize barcode appearance and programmatically validate rendered images for quality assurance or automated testing. +// Title: Generate Code128 barcode with dark red bars and verify PNG output +// Description: This example creates a Code128 barcode, sets the bar color to dark red, saves it as a PNG file, and programmatically checks that the saved image contains the expected color. +// Category-Description: Demonstrates Aspose.BarCode generation features such as customizing barcode appearance (foreground color) and exporting to PNG. It uses BarcodeGenerator, EncodeTypes, BarCodeImageFormat, and Aspose.Drawing classes to create and verify the image. Ideal for developers needing to apply branding colors to barcodes and ensure visual correctness in automated pipelines. // Prompt: Create a barcode, set ForeColor to dark red, and verify color appears correctly in saved PNG. -// Tags: barcode, code128, forecolor, darkred, png, generation, verification, aspose.barcode, aspose.drawing +// Tags: barcode, code128, colormodification, png, aspose.barcode, generation, verification, csharp using System; using System.IO; @@ -11,54 +11,64 @@ using Aspose.Drawing; /// -/// Example program that generates a Code128 barcode with a dark red foreground, -/// saves it as a PNG file, and verifies that the saved image contains the expected color. +/// Demonstrates creating a barcode with a custom foreground color and verifying the saved image. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Generates a Code128 barcode, applies a dark red bar color, + /// saves it as PNG, and validates that the color appears in the output file. /// - /// Command‑line arguments (not used). - static void Main(string[] args) + static void Main() { - // Path where the barcode image will be saved + // Define the output file path for the generated barcode image. string outputPath = "barcode.png"; - // Create a barcode generator for Code128, set the code text and dark red bar color, then save as PNG - using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) + // Create a barcode generator for Code128 with sample text. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) { - generator.CodeText = "12345"; - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.DarkRed; - generator.Save(outputPath); + // Set the foreground (bars) color to dark red. + generator.Parameters.Barcode.BarColor = Color.FromArgb(139, 0, 0); // DarkRed + + // Save the barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); } - // Ensure the file was created before attempting verification + // Verify that the saved image file exists. if (!File.Exists(outputPath)) { Console.WriteLine("Failed to create barcode image."); return; } - // Scan the saved image pixel by pixel to find at least one dark red pixel - bool darkRedFound = false; - using (var bitmap = new Aspose.Drawing.Bitmap(outputPath)) + bool colorFound = false; + + // Load the saved PNG and scan its pixels to locate a dark red bar. + using (var bitmap = new Bitmap(outputPath)) { - for (int y = 0; y < bitmap.Height && !darkRedFound; y++) + // Iterate over each pixel until a matching color is found. + for (int y = 0; y < bitmap.Height && !colorFound; y++) { - for (int x = 0; x < bitmap.Width && !darkRedFound; x++) + for (int x = 0; x < bitmap.Width && !colorFound; x++) { - if (bitmap.GetPixel(x, y).ToArgb() == Aspose.Drawing.Color.DarkRed.ToArgb()) + Color pixel = bitmap.GetPixel(x, y); + + // Skip background pixels (assumed white). + if (pixel.ToArgb() != Color.White.ToArgb()) { - darkRedFound = true; + // Check if the pixel matches the expected dark red color. + if (pixel.ToArgb() == Color.FromArgb(139, 0, 0).ToArgb()) + { + colorFound = true; + } } } } } - // Output verification result - Console.WriteLine(darkRedFound - ? "Dark red color verified in barcode image." - : "Dark red color not found in barcode image."); + // Output the verification result. + Console.WriteLine(colorFound + ? "Color verification passed: dark red bars detected." + : "Color verification failed: dark red bars not detected."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/create-barcode-set-height-to-40-mm-and-ensure-bars-remain-within-image-bounds.cs b/one-dimensional-barcode-types/create-barcode-set-height-to-40-mm-and-ensure-bars-remain-within-image-bounds.cs index da07ec0..ac522c7 100644 --- a/one-dimensional-barcode-types/create-barcode-set-height-to-40-mm-and-ensure-bars-remain-within-image-bounds.cs +++ b/one-dimensional-barcode-types/create-barcode-set-height-to-40-mm-and-ensure-bars-remain-within-image-bounds.cs @@ -1,45 +1,55 @@ -// Title: Create Code128 barcode with specific bar height within image bounds -// Description: Demonstrates generating a Code128 barcode, setting the bar height to 40 mm, and configuring the image size so the bars stay inside the image. -// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to control barcode dimensions using the BarcodeGenerator and its Parameters properties. It shows disabling auto‑size, setting BarHeight, and adjusting ImageWidth/ImageHeight to keep the barcode within the canvas—common tasks when creating printable barcodes for labels, receipts, or packaging. +// Title: Generate a Code128 barcode with a specific height and bounded image +// Description: Demonstrates creating a Code128 barcode, setting its bar height to 40 mm, and configuring the image so the bars stay within the image bounds. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to use BarcodeGenerator, EncodeTypes, and Parameters to control barcode dimensions and image sizing. Typical use cases include generating printable barcodes with precise size requirements for labeling, inventory, and packaging applications. Developers often need to set bar height, image height, and disable auto‑sizing to ensure the barcode fits within a predefined layout. // Prompt: Create a barcode, set Height to 40 mm, and ensure bars remain within image bounds. -// Tags: code128, barheight, image-bounds, png, barcodegenerator, parameters, aspose.barcode +// Tags: code128, barcode generation, png output, barcodegenerator, parameters using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; /// -/// Generates a Code128 barcode image with a bar height of 40 mm, -/// ensuring the barcode fits within the defined image dimensions. +/// Example program that generates a Code128 barcode image with a fixed bar height +/// and ensures the barcode fits within the image bounds. /// class Program { /// - /// Entry point of the example. Creates the barcode, configures dimensions, - /// and saves the result as a PNG file. + /// Entry point of the application. Generates the barcode and saves it as a PNG file. /// static void Main() { - // Initialize a BarcodeGenerator for Code128 with sample data. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // Define the output file path for the generated barcode image + string outputPath = "barcode.png"; + + // Resolve the full directory path and ensure it exists + string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(directory)) { - // Disable automatic sizing so the explicit BarHeight is applied. - generator.Parameters.AutoSizeMode = AutoSizeMode.None; + Directory.CreateDirectory(directory); + } - // Set the height of the barcode bars to 40 millimeters. - generator.Parameters.Barcode.BarHeight.Millimeters = 40f; + // Initialize a BarcodeGenerator for the Code128 symbology + using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) + { + // Set the text that will be encoded into the barcode + generator.CodeText = "1234567890"; - // Define image dimensions large enough to contain the bars and required padding. - generator.Parameters.ImageWidth.Millimeters = 100f; - generator.Parameters.ImageHeight.Millimeters = 50f; + // Specify the bar height in points (40 mm ≈ 40 points for this example) + generator.Parameters.Barcode.BarHeight.Point = 40f; - // Optional: set background to white and bars to black (default colors). - generator.Parameters.BackColor = Color.White; - generator.Parameters.Barcode.BarColor = Color.Black; + // Set the image height to a value that comfortably contains the bars + generator.Parameters.ImageHeight.Point = 50f; - // Save the generated barcode as a PNG file. - generator.Save("barcode.png"); + // Disable automatic sizing so the explicit dimensions are used + generator.Parameters.AutoSizeMode = AutoSizeMode.None; + + // Save the generated barcode as a PNG image to the specified path + generator.Save(outputPath, BarCodeImageFormat.Png); } + + // Inform the user where the barcode image has been saved + Console.WriteLine($"Barcode saved to: {Path.GetFullPath(outputPath)}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/create-barcode-set-showcodetext-to-false-and-verify-that-no-human-readable-text-appears.cs b/one-dimensional-barcode-types/create-barcode-set-showcodetext-to-false-and-verify-that-no-human-readable-text-appears.cs index 64d4d21..d84d2e4 100644 --- a/one-dimensional-barcode-types/create-barcode-set-showcodetext-to-false-and-verify-that-no-human-readable-text-appears.cs +++ b/one-dimensional-barcode-types/create-barcode-set-showcodetext-to-false-and-verify-that-no-human-readable-text-appears.cs @@ -1,68 +1,45 @@ -// Title: Generate Code128 barcode without human‑readable text -// Description: This example creates a Code128 barcode, disables the human‑readable code text, and saves it as a PNG image. -// Category-Description: Demonstrates Aspose.BarCode generation and recognition APIs. It shows how to configure BarcodeGenerator to hide the code text (using CodeLocation.None) and how to verify the setting with BarCodeReader. Typical for developers needing clean barcode images for packaging, labeling, or UI without accompanying text. +// Title: Hide human‑readable text in a Code128 barcode +// Description: Demonstrates how to generate a Code128 barcode with Aspose.BarCode, disable the visible code text, and confirm the setting. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and CodeTextParameters to control human‑readable text visibility. Developers often need to create barcodes without displaying the encoded value for aesthetic or security reasons; this snippet shows the typical API calls for that scenario. // Prompt: Create a barcode, set ShowCodeText to false, and verify that no human‑readable text appears. -// Tags: code128, hide text, png, barcodegenerator, barcodereader, generation, recognition +// Tags: barcode, code128, hide text, codetextparameters, aspose.barcode, generation, png using System; +using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; // Required for Aspose.Drawing.Bitmap if needed /// -/// Example program that generates a Code128 barcode without human‑readable text, -/// saves it to a PNG file, and verifies the configuration using a barcode reader. +/// Example program that generates a Code128 barcode with hidden human‑readable text. /// -class Program +public class Program { /// - /// Entry point of the example. Performs barcode generation, saving, and verification. + /// Entry point. Generates the barcode, hides the code text, saves the image, and verifies the setting. /// - static void Main() + /// Command‑line arguments (not used). + public static void Main(string[] args) { - // Output file path and the data to encode - const string outputPath = "barcode.png"; - const string codeText = "1234567890"; - - // ------------------------------------------------------------ - // 1. Generate a Code128 barcode and hide the human‑readable text - // ------------------------------------------------------------ + // Initialize a barcode generator for Code128 symbology using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) { - // Set the data to encode - generator.CodeText = codeText; + // Set the value to encode + generator.CodeText = "123456"; - // Hide the code text (human‑readable) by setting its location to None + // Hide the human‑readable text by setting its location to None generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.None; - // Save the barcode image as PNG - generator.Save(outputPath); - } - - // ------------------------------------------------------------ - // 2. Verify that the barcode was generated without human‑readable text - // (the setting above ensures the text is not rendered) - // ------------------------------------------------------------ - using (var reader = new BarCodeReader(outputPath, DecodeType.Code128)) - { - foreach (var result in reader.ReadBarCodes()) - { - // Output the decoded text; the absence of visual text does not affect decoding - Console.WriteLine($"Detected CodeText: {result.CodeText}"); - } - } + // Save the generated barcode as a PNG file + generator.Save("barcode.png"); - // ------------------------------------------------------------ - // 3. Additional check: confirm the generator's setting was applied - // ------------------------------------------------------------ - using (var generatorCheck = new BarcodeGenerator(EncodeTypes.Code128)) - { - if (generatorCheck.Parameters.Barcode.CodeTextParameters.Location == CodeLocation.None) + // Verify that the code text location is set to None (i.e., hidden) + if (generator.Parameters.Barcode.CodeTextParameters.Location == CodeLocation.None) { - Console.WriteLine("Human‑readable text is disabled (CodeLocation.None)."); + Console.WriteLine("Human‑readable text is hidden."); } else { - Console.WriteLine("Human‑readable text is enabled."); + Console.WriteLine("Human‑readable text is visible."); } } } diff --git a/one-dimensional-barcode-types/create-barcode-with-custom-background-color-f0f0f0-light-gray-and-save-as-bmp-file.cs b/one-dimensional-barcode-types/create-barcode-with-custom-background-color-f0f0f0-light-gray-and-save-as-bmp-file.cs index b297708..10bb5bc 100644 --- a/one-dimensional-barcode-types/create-barcode-with-custom-background-color-f0f0f0-light-gray-and-save-as-bmp-file.cs +++ b/one-dimensional-barcode-types/create-barcode-with-custom-background-color-f0f0f0-light-gray-and-save-as-bmp-file.cs @@ -1,6 +1,6 @@ -// Title: Create Code128 barcode with custom background color and save as BMP -// Description: Demonstrates how to generate a Code128 barcode with a light gray background and save it as a BMP image using Aspose.BarCode. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, showcasing the use of BarcodeGenerator, EncodeTypes, and drawing parameters to customize appearance. Typical use cases include creating branded barcodes with specific background colors for print or digital media. Developers often need to adjust visual properties like background and foreground colors before exporting to various image formats. +// Title: Generate a Code128 barcode with a custom light‑gray background and save as BMP +// Description: Demonstrates how to create a Code128 barcode, apply a custom background color (#F0F0F0), and export it as a BMP image using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and image format settings. Developers commonly need to customize barcode appearance (colors, fonts) and output formats for integration into documents, labels, or UI components. The snippet shows typical steps for setting parameters and saving the result. // Prompt: Create a barcode with custom background color #F0F0F0 (light gray) and save as a BMP file. // Tags: code128, barcode generation, bmp, background color, aspose.barcode, aspose.drawing @@ -10,8 +10,8 @@ using Aspose.Drawing; /// -/// Example program that generates a Code128 barcode with a custom light gray background -/// and saves it as a BMP file. +/// Example program that generates a Code128 barcode with a custom background color +/// and saves it as a BMP file using Aspose.BarCode. /// class Program { @@ -20,17 +20,23 @@ class Program /// static void Main() { - // Initialize a BarcodeGenerator for Code128 symbology with sample data "123456" - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // Define the output file path for the generated BMP image. + string outputPath = "barcode.bmp"; + + // Initialize the barcode generator with Code128 symbology. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128)) { - // Set the background color to light gray (#F0F0F0) + // Set the text that the barcode will encode. + generator.CodeText = "123456"; + + // Apply a custom light‑gray background color (#F0F0F0). generator.Parameters.BackColor = Color.FromArgb(0xF0, 0xF0, 0xF0); - // Save the generated barcode image as a BMP file named "barcode.bmp" - generator.Save("barcode.bmp"); + // Save the generated barcode image in BMP format to the specified path. + generator.Save(outputPath, BarCodeImageFormat.Bmp); } - // Inform the user that the barcode has been saved - Console.WriteLine("Barcode saved as barcode.bmp"); + // Inform the user where the barcode image has been saved. + Console.WriteLine($"Barcode saved to {outputPath}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/create-barcode-with-custom-text-font-calibri-size-13-pt-and-align-text-right-of-barcode.cs b/one-dimensional-barcode-types/create-barcode-with-custom-text-font-calibri-size-13-pt-and-align-text-right-of-barcode.cs index 2215952..d6116ec 100644 --- a/one-dimensional-barcode-types/create-barcode-with-custom-text-font-calibri-size-13-pt-and-align-text-right-of-barcode.cs +++ b/one-dimensional-barcode-types/create-barcode-with-custom-text-font-calibri-size-13-pt-and-align-text-right-of-barcode.cs @@ -1,40 +1,42 @@ -// Title: Create barcode with custom font and right-aligned text -// Description: Demonstrates how to generate a Code128 barcode with human‑readable text using Calibri 13 pt font and align the text to the right of the barcode. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and CodeTextParameters to customize barcode appearance. Typical use cases include branding, product labeling, and custom UI where specific font styling and text positioning are required. Developers often need to adjust font family, size, and alignment to match design guidelines. +// Title: Create Code128 barcode with right-aligned Calibri text +// Description: Demonstrates how to generate a Code128 barcode, set the human‑readable text font to Calibri 13 pt, and align the text to the right of the barcode image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and CodeTextParameters to customize human‑readable text. Typical use cases include branding, product labeling, and custom UI where specific font styling and text placement are required. Developers often need to adjust font family, size, and alignment to match design guidelines. // Prompt: Create a barcode with custom text font Calibri, size 13 pt, and align text right of the barcode. -// Tags: code128, barcode generation, custom font, text alignment, png, aspose.barcode +// Tags: code128, barcode generation, custom font, text alignment, png, aspose.barcode, aspose.barcode.generation, aspose.drawing using System; -using Aspose.BarCode.Generation; using Aspose.BarCode; +using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Example program that generates a Code128 barcode with custom text styling -/// and saves it as a PNG image. +/// Demonstrates generating a Code128 barcode with custom font and right-aligned text. /// class Program { /// - /// Entry point of the application. Creates a barcode, configures font and alignment, - /// then saves the result to a file. + /// Entry point that creates the barcode, applies font settings, aligns text, and saves the image. /// static void Main() { - // Initialize a barcode generator for Code128 symbology with the desired data. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Initialize a barcode generator for the Code128 symbology + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128)) { - // Configure the human‑readable text font to Calibri, 13 pt. + // Define the data to encode in the barcode + generator.CodeText = "Sample123"; + + // Set the human‑readable text font to Calibri, 13 pt generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Calibri"; generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 13f; - // Align the human‑readable text to the right side of the barcode. + // Position the text to the right side of the barcode generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Right; - // Save the generated barcode image as a PNG file. - generator.Save("barcode.png"); + // Save the generated barcode as a PNG image file + generator.Save("custom_barcode.png"); } - // Inform the user that the barcode has been created. - Console.WriteLine("Barcode generated and saved as 'barcode.png'."); + // Inform the user that the barcode has been created + Console.WriteLine("Barcode generated and saved as 'custom_barcode.png'."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/create-barcode-with-custom-text-font-verdana-size-10-pt-and-align-text-left-of-bars.cs b/one-dimensional-barcode-types/create-barcode-with-custom-text-font-verdana-size-10-pt-and-align-text-left-of-bars.cs index b482e02..6188b4a 100644 --- a/one-dimensional-barcode-types/create-barcode-with-custom-text-font-verdana-size-10-pt-and-align-text-left-of-bars.cs +++ b/one-dimensional-barcode-types/create-barcode-with-custom-text-font-verdana-size-10-pt-and-align-text-left-of-bars.cs @@ -1,45 +1,41 @@ -// Title: Generate Code128 barcode with Verdana font and left-aligned text -// Description: Demonstrates creating a Code128 barcode, setting the human‑readable text to Verdana 10 pt, and aligning it to the left of the bars. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to customize barcode text appearance using BarcodeGenerator, EncodeTypes, and CodeTextParameters. Developers often need to adjust font, size, and alignment for branding or readability when embedding barcodes in documents or labels. +// Title: Create Code128 barcode with custom Verdana font and left-aligned text +// Description: Demonstrates how to generate a Code128 barcode using Aspose.BarCode, set the human‑readable text to Verdana 10 pt, and align the text to the left of the bars. The example saves the result as a PNG image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and CodeTextParameters to customize barcode appearance. Typical use cases include creating barcodes with specific font styles and text alignment for labeling and packaging applications. Developers often need to adjust font family, size, and alignment to meet branding or layout requirements. // Prompt: Create a barcode with custom text font Verdana, size 10 pt, and align text left of the bars. -// Tags: code128, barcode generation, png output, font customization, codetextparameters, barcodgenerator +// Tags: code128, barcode generation, text formatting, png output, aspose.barcode, barcodegenerator, codetextparameters using System; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; /// -/// Demonstrates creating a barcode with custom font and left-aligned text. +/// Example program that generates a Code128 barcode with custom text font and alignment using Aspose.BarCode. /// class Program { /// - /// Entry point. Generates a Code128 barcode, applies Verdana 10pt font, left-aligns the text, and saves as PNG. + /// Entry point of the application. Generates the barcode and saves it as a PNG file. /// static void Main() { - // Define output file path - string outputPath = "custom_font_barcode.png"; - - // Initialize barcode generator for Code128 symbology + // Initialize a BarcodeGenerator for the Code128 symbology using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) { - // Text to encode in the barcode + // Set the data to be encoded in the barcode generator.CodeText = "Sample123"; - // Set human‑readable text font to Verdana, 10 pt + // Configure the human‑readable text font: Verdana, 10 pt generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Verdana"; generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 10f; - // Align the human‑readable text to the left of the bars + // Align the human‑readable text to the left side of the barcode bars generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Left; - // Save the generated barcode as a PNG image - generator.Save(outputPath, BarCodeImageFormat.Png); + // Save the generated barcode image to a PNG file + generator.Save("barcode.png"); } - // Inform the user where the barcode image was saved - Console.WriteLine($"Barcode saved to: {outputPath}"); + // Inform the user that the barcode has been generated + Console.WriteLine("Barcode generated: barcode.png"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/create-barcode-with-custom-text-positioned-above-bars-top-placement.cs b/one-dimensional-barcode-types/create-barcode-with-custom-text-positioned-above-bars-top-placement.cs index 904b0f1..c648187 100644 --- a/one-dimensional-barcode-types/create-barcode-with-custom-text-positioned-above-bars-top-placement.cs +++ b/one-dimensional-barcode-types/create-barcode-with-custom-text-positioned-above-bars-top-placement.cs @@ -1,8 +1,8 @@ -// Title: Generate Code128 barcode with custom text above the bars -// Description: Demonstrates how to create a Code128 barcode and position the human‑readable text on top of the bars, useful for labeling where the text must appear above the barcode. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and CodeTextParameters to customize barcode appearance. Developers often need to adjust text location, font, and color for branding or compliance, and this snippet shows the typical API calls for such customizations. +// Title: Generate a Code128 barcode with a custom top caption +// Description: Demonstrates how to create a Code128 barcode and place a custom text caption above the bars using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator and its Parameters to customize barcode appearance. Typical use cases include adding descriptive labels, product information, or branding above barcodes. Developers often need to adjust caption visibility, alignment, font, and color to meet design requirements. // Prompt: Create a barcode with custom text positioned above the bars (top placement). -// Tags: code128, barcode, text placement, png, aspose.barcode, barcodegenerator, codetextparameters +// Tags: code128, barcode symbology, caption, top placement, png, barcodegenerator, generation using System; using Aspose.BarCode; @@ -10,34 +10,31 @@ using Aspose.Drawing; /// -/// Example program that creates a Code128 barcode with custom text placed above the bars. +/// Demonstrates creating a Code128 barcode with a caption positioned above the bars. /// class Program { /// - /// Entry point. Generates the barcode, customizes the text appearance, and saves it as a PNG file. + /// Entry point of the example. Generates the barcode and saves it as a PNG file. /// static void Main() { - // Initialize a barcode generator for the Code128 symbology. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) + // Initialize a BarcodeGenerator for Code128 symbology with the desired code text. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) { - // Set the data to be encoded in the barcode. - generator.CodeText = "Custom Text"; - - // Position the human‑readable text above the barcode bars. - generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Above; - - // Optional: customize the font family, size, and color of the above text. - generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Arial"; - generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 12f; - generator.Parameters.Barcode.CodeTextParameters.Color = Color.Blue; + // Configure the caption that will appear above the barcode bars. + generator.Parameters.CaptionAbove.Text = "Top Caption"; + generator.Parameters.CaptionAbove.Visible = true; + generator.Parameters.CaptionAbove.Alignment = TextAlignment.Center; + generator.Parameters.CaptionAbove.TextColor = Color.Blue; + generator.Parameters.CaptionAbove.Font.FamilyName = "Helvetica"; + generator.Parameters.CaptionAbove.Font.Size.Point = 12f; // Save the generated barcode image to a PNG file. generator.Save("barcode.png"); } - // Output a simple confirmation message. - Console.WriteLine("Barcode generated and saved as 'barcode.png'."); + // Inform the user that the barcode image has been saved. + Console.WriteLine("Barcode image saved as 'barcode.png'."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/create-barcode-with-showcodetext-disabled-to-produce-image-without-human-readable-text.cs b/one-dimensional-barcode-types/create-barcode-with-showcodetext-disabled-to-produce-image-without-human-readable-text.cs index b3b4584..b3899de 100644 --- a/one-dimensional-barcode-types/create-barcode-with-showcodetext-disabled-to-produce-image-without-human-readable-text.cs +++ b/one-dimensional-barcode-types/create-barcode-with-showcodetext-disabled-to-produce-image-without-human-readable-text.cs @@ -1,40 +1,41 @@ -// Title: Generate Code128 barcode without human‑readable text -// Description: Demonstrates disabling the code text to create a clean barcode image. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode appearance using BarcodeGenerator and its Parameters. Developers often need to hide the human‑readable text for printing or embedding barcodes in UI where only the bars are required. The example shows setting CodeTextParameters.Location to CodeLocation.None and saving the result. +// Title: Generate Code128 Barcode without Human‑Readable Text +// Description: Demonstrates how to create a Code128 barcode image with the human‑readable text hidden, saving it as a PNG file. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and CodeTextParameters to control barcode appearance. Developers often need to produce barcodes without the accompanying code text for cleaner scans or aesthetic reasons, such as in packaging or labeling scenarios. // Prompt: Create a barcode with ShowCodeText disabled to produce an image without human‑readable text. -// Tags: code128, hidecodetext, png, generation, aspnet, aspnetcore, aspose.barcode +// Tags: code128, barcode generation, hide codetext, png output, aspose.barcode, barcodegenerator using System; -using Aspose.BarCode.Generation; using Aspose.BarCode; +using Aspose.BarCode.Generation; +using Aspose.Drawing; -namespace BarcodeSample +namespace BarcodeExample { /// - /// Demonstrates creating a Code128 barcode image with the human‑readable text disabled. + /// Demonstrates creating a barcode image with the code text hidden. /// class Program { /// - /// Entry point. Generates the barcode and saves it as a PNG file. + /// Creates a Code128 barcode without human‑readable text and saves it as a PNG file. /// static void Main() { // Define the output file path for the generated barcode image. string outputPath = "barcode.png"; - // Initialize a BarcodeGenerator for Code128 symbology with sample code text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Initialize a BarcodeGenerator for Code128 symbology with the desired data. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) { - // Disable the human‑readable text (code text) below the barcode. + // Hide the human‑readable text by setting its location to None. generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.None; - // Save the generated barcode image in PNG format to the specified path. - generator.Save(outputPath, BarCodeImageFormat.Png); + // Save the generated barcode as a PNG image to the specified path. + generator.Save(outputPath); } // Inform the user where the barcode image has been saved. - Console.WriteLine($"Barcode image saved to {outputPath}"); + Console.WriteLine($"Barcode image saved to: {outputPath}"); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/create-barcode-with-width-reduction-of-25-percent-and-test-readability-with-handheld-scanner.cs b/one-dimensional-barcode-types/create-barcode-with-width-reduction-of-25-percent-and-test-readability-with-handheld-scanner.cs index 9f5605a..317149e 100644 --- a/one-dimensional-barcode-types/create-barcode-with-width-reduction-of-25-percent-and-test-readability-with-handheld-scanner.cs +++ b/one-dimensional-barcode-types/create-barcode-with-width-reduction-of-25-percent-and-test-readability-with-handheld-scanner.cs @@ -1,59 +1,70 @@ -// Title: Generate Code128 barcode with 25% width reduction and verify readability -// Description: Creates a Code128 barcode image with a 25 percent width reduction and then reads it back to confirm it can be scanned with a handheld device. -// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It demonstrates using BarcodeGenerator to customize barcode dimensions and BarCodeReader to decode the generated image. Developers often need to adjust barcode size for specific printing constraints and validate scanability across devices. +// Title: Generate Code128 Barcode with 25% Width Reduction and Verify via Scanner Simulation +// Description: This example creates a Code128 barcode, reduces its bar width by 25 percent, saves it as a PNG, and then reads it back to simulate a handheld scanner verification. +// Category-Description: Demonstrates Aspose.BarCode generation and recognition workflows, focusing on barcode appearance customization (BarWidthReduction) and post‑generation validation. Uses BarcodeGenerator, BarCodeReader, and related parameter classes, typical for developers needing to fine‑tune barcode dimensions and ensure readability in real‑world scanning scenarios. // Prompt: Create a barcode with width reduction of 25 percent and test readability with a handheld scanner. -// Tags: code128, width-reduction, png, generation, recognition, aspnet, aspose.barcode +// Tags: code128, width reduction, barcode generation, barcode recognition, png, aspose.barcode, handheld scanner simulation using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Demonstrates creating a Code128 barcode with a 25 percent width reduction, -/// saving it as a PNG file, and then reading it back to verify scanner readability. +/// Demonstrates how to generate a Code128 barcode with a 25 percent width reduction, +/// save it as an image, and verify its readability using Aspose.BarCode's recognition API. /// class Program { /// - /// Entry point of the example. Generates the barcode, saves it, and validates it. + /// Entry point of the example. Generates the barcode, saves it, and then reads it back + /// to simulate scanning with a handheld device. /// static void Main() { // Define the output file path for the generated barcode image. - string outputPath = "barcode.png"; + string barcodePath = "barcode.png"; - // Create a Code128 barcode with the sample text "1234567890". - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // ------------------------------------------------------------ + // Generate a Code128 barcode with a 25% bar width reduction. + // ------------------------------------------------------------ + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789")) { - // Apply a 25% width reduction to the barcode bars. - generator.Parameters.Barcode.BarWidthReduction.Point = 0.25f; + // BarWidthReduction is expressed in points; here we set it to 25 (interpreted as 25%). + generator.Parameters.Barcode.BarWidthReduction.Point = 25f; // Save the generated barcode as a PNG image. - generator.Save(outputPath, BarCodeImageFormat.Png); + generator.Save(barcodePath, BarCodeImageFormat.Png); } // Verify that the barcode image file was successfully created. - if (!File.Exists(outputPath)) + if (!File.Exists(barcodePath)) { - Console.WriteLine($"Failed to create barcode image at '{outputPath}'."); + Console.WriteLine($"Failed to create barcode image at '{barcodePath}'."); return; } - // Initialize a barcode reader to decode the saved image. - using (var reader = new BarCodeReader(outputPath, DecodeType.AllSupportedTypes)) + // ------------------------------------------------------------ + // Read the barcode image to simulate a handheld scanner scan. + // ------------------------------------------------------------ + using (BarCodeReader reader = new BarCodeReader(barcodePath, DecodeType.Code128)) { - // Use a high‑performance quality preset for faster reading. - reader.QualitySettings = QualitySettings.HighPerformance; + bool found = false; - // Iterate through all detected barcodes in the image. + // Iterate through all detected barcodes (there should be only one in this case). foreach (var result in reader.ReadBarCodes()) { Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - Console.WriteLine($"Code Text: {result.CodeText}"); + Console.WriteLine($"Decoded Text: {result.CodeText}"); Console.WriteLine($"Confidence: {result.Confidence}"); - Console.WriteLine($"Reading Quality: {result.ReadingQuality}%"); + found = true; + } + + // Inform the user if no barcode was detected. + if (!found) + { + Console.WriteLine("No barcode detected. Scanning may have failed."); } } } diff --git a/one-dimensional-barcode-types/create-barcode-with-width-reduction-set-to-30-percent-and-verify-scanner-readability.cs b/one-dimensional-barcode-types/create-barcode-with-width-reduction-set-to-30-percent-and-verify-scanner-readability.cs index e092129..be32db2 100644 --- a/one-dimensional-barcode-types/create-barcode-with-width-reduction-set-to-30-percent-and-verify-scanner-readability.cs +++ b/one-dimensional-barcode-types/create-barcode-with-width-reduction-set-to-30-percent-and-verify-scanner-readability.cs @@ -1,8 +1,8 @@ -// Title: Create Code128 barcode with 30% width reduction and verify readability -// Description: Demonstrates how to generate a Code128 barcode with a 30 percent bar‑width reduction, save it as PNG, and confirm that a scanner can read it. -// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, illustrating the use of BarcodeGenerator for customizing barcode appearance (e.g., BarWidthReduction) and BarCodeReader for validating scan results. Developers often need to adjust visual parameters while ensuring scanner compatibility, making this pattern useful for packaging, inventory, and logistics applications. -// Prompt: Create a barcode with width reduction set to 30 percent and verify scanner readability. -// Tags: code128, width-reduction, barcode-generation, barcode-recognition, png, aspose.barcode +// Title: Generate Code128 Barcode with 30% Width Reduction and Verify Readability +// Description: This example creates a Code128 barcode, applies a 30 percent bar‑width reduction, saves it as a PNG image, and then reads it back to confirm scanner readability. +// Category-Description: Demonstrates Aspose.BarCode generation and recognition workflows. It showcases the use of BarcodeGenerator to customize barcode appearance (e.g., bar‑width reduction) and BarCodeReader to validate that the produced image can be decoded. Typical for developers who need to fine‑tune barcode dimensions for space‑constrained layouts and ensure downstream scanning reliability. Ideal for collections of examples on barcode customization, image output, and verification using Aspose.BarCode for .NET. +/// Prompt: Create a barcode with width reduction set to 30 percent and verify scanner readability. +/// Tags: code128, width reduction, barcode generation, barcode recognition, png, aspose.barcode, c# using System; using System.IO; @@ -11,72 +11,55 @@ using Aspose.Drawing; /// -/// Generates a Code128 barcode with a 30 percent bar‑width reduction, -/// saves it as a PNG image, and verifies that the barcode can be read -/// by a scanner using Aspose.BarCode's recognition API. +/// Demonstrates creating a Code128 barcode with a 30 percent bar‑width reduction, +/// saving it as PNG, and verifying that it can be read by a scanner. /// class Program { /// - /// Entry point of the example. Executes barcode creation, - /// saves the image, and validates readability. + /// Entry point of the example. Generates the barcode, saves it, and validates readability. /// static void Main() { - // Define output file and barcode content - const string outputPath = "barcode.png"; - const string codeText = "1234567890"; + // Define the output file path for the generated barcode image. + string outputPath = "barcode.png"; - // -------------------------------------------------------------------- - // Generate the barcode with custom visual parameters - // -------------------------------------------------------------------- - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // Create a barcode generator for Code128 with the sample text "1234567890". + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Apply a 30 percent reduction to the bar width + // Apply a 30 percent bar‑width reduction (value expressed in points). generator.Parameters.Barcode.BarWidthReduction.Point = 30f; - // Set foreground (bars) and background colors for clear contrast - generator.Parameters.Barcode.BarColor = Color.Black; - generator.Parameters.BackColor = Color.White; - - // Save the generated barcode as a PNG image + // Save the generated barcode as a PNG image to the specified path. generator.Save(outputPath, BarCodeImageFormat.Png); } - // -------------------------------------------------------------------- - // Verify that the generated image exists before attempting recognition - // -------------------------------------------------------------------- + // Verify that the barcode image file was created successfully. if (!File.Exists(outputPath)) { - Console.WriteLine($"Failed to generate barcode image at '{outputPath}'."); + Console.WriteLine($"Failed to create barcode image at '{outputPath}'."); return; } - // -------------------------------------------------------------------- - // Use BarCodeReader to scan the saved image and confirm readability - // -------------------------------------------------------------------- - using (var reader = new BarCodeReader(outputPath, DecodeType.AllSupportedTypes)) + // Use BarCodeReader to decode the saved image and confirm scanner readability. + using (BarCodeReader reader = new BarCodeReader(outputPath, DecodeType.Code128)) { - bool readable = false; + bool found = false; - // Iterate through all detected barcodes in the image + // Iterate through all detected barcodes in the image. foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"Detected CodeText: {result.CodeText}"); + Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}"); + Console.WriteLine($"Decoded Text: {result.CodeText}"); Console.WriteLine($"Confidence: {result.Confidence}"); - Console.WriteLine($"Reading Quality: {result.ReadingQuality}"); - - // Check if the detected text matches the original input - if (result.CodeText == codeText) - { - readable = true; - } + found = true; } - // Output final verification result - Console.WriteLine(readable - ? "Barcode is readable by the scanner." - : "Barcode could not be read correctly."); + // Inform the user if no readable barcode was found. + if (!found) + { + Console.WriteLine("No barcode detected or unreadable."); + } } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/create-barcode-with-width-reduction-set-to-5-percent-and-test-readability-on-low-resolution-mobile-scanners.cs b/one-dimensional-barcode-types/create-barcode-with-width-reduction-set-to-5-percent-and-test-readability-on-low-resolution-mobile-scanners.cs index 1dcd3d0..238cb2d 100644 --- a/one-dimensional-barcode-types/create-barcode-with-width-reduction-set-to-5-percent-and-test-readability-on-low-resolution-mobile-scanners.cs +++ b/one-dimensional-barcode-types/create-barcode-with-width-reduction-set-to-5-percent-and-test-readability-on-low-resolution-mobile-scanners.cs @@ -1,68 +1,83 @@ -// Title: Create Code128 barcode with 5% width reduction for low‑resolution scanner testing -// Description: Demonstrates generating a Code128 barcode with a 5 percent bar‑width reduction and simulating a low‑resolution mobile scanner to verify readability. -// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, illustrating how to configure barcode appearance (bar‑width reduction) and resolution settings, then read the barcode using high‑quality recognition. Developers often need to adjust bar dimensions and test scanning performance on devices with limited DPI, using classes like BarcodeGenerator, BarCodeReader, and QualitySettings. +// Title: Barcode generation with width reduction and low‑resolution readability test +// Description: Demonstrates creating a Code128 barcode with a 5 percent bar‑width reduction, then simulates a low‑resolution mobile scanner by downscaling the image and verifies that the barcode can still be read. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing how to adjust barcode appearance using the BarcodeGenerator.Parameters.Barcode.BarWidthReduction property and how to validate readability with BarCodeReader. Typical use cases include optimizing barcodes for small screens or low‑resolution capture devices. Developers often need to balance visual size reduction with scan reliability, making this pattern useful for mobile and IoT applications. // Prompt: Create a barcode with width reduction set to 5 percent and test readability on low‑resolution mobile scanners. -// Tags: code128, barwidthreduction, lowresolution, barcode-generation, barcode-recognition, qualitysettings, png +// Tags: code128, barwidthreduction, lowresolution, barcodegeneration, barcoderecognition, png, aspnet using System; using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Generates a Code128 barcode with a 5 percent bar‑width reduction, -/// saves it as a PNG, and then reads it back using high‑quality settings -/// to simulate scanning on a low‑resolution mobile device. +/// Demonstrates generating a Code128 barcode with a 5% bar‑width reduction, +/// downscaling it to simulate a low‑resolution mobile scanner, and reading it back. /// class Program { /// - /// Entry point of the example. Creates the barcode, saves it, - /// verifies the file, and performs recognition. + /// Entry point of the example. Generates the barcode, creates a low‑resolution version, + /// and attempts to decode it using Aspose.BarCode. /// static void Main() { - // Define the output file path for the generated barcode image. - string outputPath = "barcode.png"; + const string originalPath = "barcode.png"; + const string lowResPath = "barcode_lowres.png"; - // Create a Code128 barcode with sample text "1234567890". + // ------------------------------------------------------------ + // 1. Generate a high‑resolution Code128 barcode with 5% width reduction + // ------------------------------------------------------------ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Simulate a low‑resolution mobile scanner by setting the image resolution to 72 DPI. - generator.Parameters.Resolution = 72f; - - // Apply a 5 percent bar‑width reduction to the barcode. + // Apply a 5 percent bar‑width reduction generator.Parameters.Barcode.BarWidthReduction.Point = 5f; - // Save the generated barcode as a PNG file. - generator.Save(outputPath, BarCodeImageFormat.Png); + // Save the generated barcode as a PNG image + generator.Save(originalPath, BarCodeImageFormat.Png); } - // Verify that the barcode image file was successfully created. - if (!File.Exists(outputPath)) + // ------------------------------------------------------------ + // 2. Simulate a low‑resolution mobile scanner by downscaling the image + // ------------------------------------------------------------ + using (var originalBitmap = new Bitmap(originalPath)) { - Console.WriteLine($"Failed to create barcode image at '{outputPath}'."); - return; + // Target width for the low‑resolution image (maintain aspect ratio) + int targetWidth = 100; + int targetHeight = (int)Math.Round((double)originalBitmap.Height * targetWidth / originalBitmap.Width); + + using (var lowResBitmap = new Bitmap(targetWidth, targetHeight)) + { + using (var graphics = Graphics.FromImage(lowResBitmap)) + { + // Draw the original image onto the smaller bitmap (no high‑quality scaling needed) + graphics.DrawImage(originalBitmap, 0, 0, targetWidth, targetHeight); + } + + // Save the low‑resolution image for recognition testing + lowResBitmap.Save(lowResPath, ImageFormat.Png); + } } - // Read the barcode using high‑quality settings to emulate a mobile scanner. - using (var reader = new BarCodeReader(outputPath, DecodeType.AllSupportedTypes)) + // ------------------------------------------------------------ + // 3. Attempt to read the barcode from the low‑resolution image + // ------------------------------------------------------------ + using (var reader = new BarCodeReader(lowResPath, DecodeType.AllSupportedTypes)) { - // Enable high‑quality recognition to improve detection of low‑resolution images. - reader.QualitySettings = QualitySettings.HighQuality; + bool found = false; - // Iterate through all detected barcodes in the image. + // Iterate through all detected barcodes foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - Console.WriteLine($"Code Text: {result.CodeText}"); - Console.WriteLine($"Confidence: {result.Confidence}"); - Console.WriteLine($"Reading Quality: {result.ReadingQuality}"); + Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}"); + Console.WriteLine($"Decoded Text: {result.CodeText}"); + found = true; + } - // Output the bounding rectangle of the detected barcode region. - var bounds = result.Region.Rectangle; - Console.WriteLine($"Region: X={bounds.X}, Y={bounds.Y}, Width={bounds.Width}, Height={bounds.Height}"); + if (!found) + { + Console.WriteLine("No barcode detected in the low‑resolution image."); } } } diff --git a/one-dimensional-barcode-types/create-batch-job-processing-directory-of-csv-files-outputting-code-16k-images.cs b/one-dimensional-barcode-types/create-batch-job-processing-directory-of-csv-files-outputting-code-16k-images.cs index e7842f8..6777d21 100644 --- a/one-dimensional-barcode-types/create-batch-job-processing-directory-of-csv-files-outputting-code-16k-images.cs +++ b/one-dimensional-barcode-types/create-batch-job-processing-directory-of-csv-files-outputting-code-16k-images.cs @@ -1,92 +1,92 @@ // Title: Batch processing CSV files to generate Code 16K barcode images -// Description: This example reads all CSV files from a directory, creates a Code 16K barcode for each line, and saves the images as PNG files. -// Category-Description: Demonstrates batch barcode generation using Aspose.BarCode. It showcases the BarcodeGenerator class with EncodeTypes.Code16K, handling file I/O, and configuring barcode parameters. Ideal for developers needing to automate barcode creation from data files in bulk. +// Description: Demonstrates how to read CSV files from a directory, extract the first column as barcode data, and generate Code 16K barcode images saved as PNG files. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating batch barcode creation from data sources. It uses the BarcodeGenerator class to configure Code 16K parameters, Aspose.Drawing for image handling, and typical file I/O for processing multiple CSV files. Developers often need to automate barcode production for inventory, shipping, or document labeling, and this pattern shows how to integrate Aspose.BarCode into such workflows. // Prompt: Create batch job processing directory of CSV files, outputting Code 16K images. -// Tags: code16k, batch-processing, png, barcodegenerator, aspnet.barcode, generation +// Tags: code16k, barcode, generation, png, csv, batch, aspose.barcode, aspose.drawing using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Provides a console application that processes CSV files in a directory, -/// generates Code 16K barcodes for each line, and saves the results as PNG images. +/// Example program that reads CSV files from an input folder, +/// generates Code 16K barcodes for each row, and saves the images as PNG files. /// class Program { /// - /// Entry point of the application. - /// Accepts optional input and output directory arguments, creates sample data if needed, - /// and iterates through each CSV file to produce barcode images. + /// Entry point of the application. Performs directory setup, sample CSV creation, + /// and batch barcode generation. /// - /// - /// Command‑line arguments where: - /// args[0] – input directory path (optional), - /// args[1] – output directory path (optional). - /// - static void Main(string[] args) + static void Main() { - // Determine input and output directories (fallback to sample folders) - string inputDir = args.Length > 0 ? args[0] : "InputCsv"; - string outputDir = args.Length > 1 ? args[1] : "OutputBarcodes"; + // Define input and output directories relative to the current working directory + string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "InputCsv"); + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "OutputBarcodes"); - // Ensure the output directory exists - if (!Directory.Exists(outputDir)) - { - Directory.CreateDirectory(outputDir); - } + // Ensure the input and output directories exist + if (!Directory.Exists(inputFolder)) + Directory.CreateDirectory(inputFolder); + if (!Directory.Exists(outputFolder)) + Directory.CreateDirectory(outputFolder); - // If the input directory does not exist, create it and add a sample CSV file - if (!Directory.Exists(inputDir)) + // Seed a sample CSV file if the input folder is empty + string[] csvFiles = Directory.GetFiles(inputFolder, "*.csv"); + if (csvFiles.Length == 0) { - Directory.CreateDirectory(inputDir); - string sampleCsvPath = Path.Combine(inputDir, "sample.csv"); - File.WriteAllLines(sampleCsvPath, new[] + string samplePath = Path.Combine(inputFolder, "Sample.csv"); + File.WriteAllLines(samplePath, new[] { - "ABC1234567890", - "XYZ9876543210", - "CODE16KTEST" + "ABC123,Some other data", + "XYZ789,More data", + "CODE16K,Example" }); + csvFiles = new[] { samplePath }; } - // Process each CSV file in the input directory - foreach (string csvFilePath in Directory.GetFiles(inputDir, "*.csv")) + // Process each CSV file found in the input folder + foreach (string csvFile in csvFiles) { - // Base name of the CSV file without extension (used for output naming) - string csvFileName = Path.GetFileNameWithoutExtension(csvFilePath); // Read all lines from the current CSV file - string[] lines = File.ReadAllLines(csvFilePath); - - int lineIndex = 0; - foreach (string rawLine in lines) + string[] lines = File.ReadAllLines(csvFile); + for (int i = 0; i < lines.Length; i++) { - // Trim whitespace and skip empty lines - string codeText = rawLine.Trim(); - if (string.IsNullOrEmpty(codeText)) - { + // Split the line by commas and take the first column as the barcode text + string[] parts = lines[i].Split(','); + if (parts.Length == 0 || string.IsNullOrWhiteSpace(parts[0])) continue; - } - // Generate Code16K barcode for the current line + string codeText = parts[0].Trim(); + + // Create a barcode generator configured for Code 16K using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, codeText)) { - // Optional: set aspect ratio (default is 1.0) - generator.Parameters.Barcode.Code16K.AspectRatio = 1f; + // Set Code 16K specific parameters (aspect ratio and quiet zones) + generator.Parameters.Barcode.Code16K.AspectRatio = 1.0f; // default aspect ratio + generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = 10; // minimum allowed + generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = 1; // minimum allowed - // Build output file name: _line.png - string outputFileName = $"{csvFileName}_line{lineIndex}.png"; - string outputPath = Path.Combine(outputDir, outputFileName); + // Optional: adjust module size (X dimension) and image resolution + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Parameters.Resolution = 300f; - // Save the barcode image as PNG - generator.Save(outputPath); - } + // Generate the barcode image as a bitmap + using (Bitmap bitmap = generator.GenerateBarCodeImage()) + { + // Build the output file name using the CSV base name and row index + string baseName = Path.GetFileNameWithoutExtension(csvFile); + string outFile = Path.Combine(outputFolder, $"{baseName}_{i + 1}.png"); - lineIndex++; + // Save the bitmap as a PNG file using Aspose.Drawing.Imaging.ImageFormat + bitmap.Save(outFile, ImageFormat.Png); + } + } } } - // Indicate completion Console.WriteLine("Barcode generation completed."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/create-databar-expanded-stacked-barcode-with-three-columns-aspect-ratio-eight-save-bmp-image.cs b/one-dimensional-barcode-types/create-databar-expanded-stacked-barcode-with-three-columns-aspect-ratio-eight-save-bmp-image.cs index b05d6e2..f91fce8 100644 --- a/one-dimensional-barcode-types/create-databar-expanded-stacked-barcode-with-three-columns-aspect-ratio-eight-save-bmp-image.cs +++ b/one-dimensional-barcode-types/create-databar-expanded-stacked-barcode-with-three-columns-aspect-ratio-eight-save-bmp-image.cs @@ -1,35 +1,41 @@ -// Title: Create DataBar Expanded Stacked Barcode and Save as BMP -// Description: Demonstrates generating a DataBar Expanded Stacked barcode with three columns and an aspect ratio of eight, then saving it as a BMP image. -// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to configure DataBar-specific parameters using the BarcodeGenerator class. Typical use cases include creating high‑density retail barcodes for packaging and point‑of‑sale systems. Developers often need to adjust columns, aspect ratios, and output formats when working with GS1 DataBar symbologies. +// Title: Create DataBar Expanded Stacked barcode and save as BMP +// Description: Demonstrates generating a GS1 DataBar Expanded Stacked barcode with three columns and an aspect ratio of eight, then saving it as a BMP image. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use the BarcodeGenerator class with EncodeTypes.DatabarExpandedStacked. Developers often need to create high‑density DataBar barcodes for retail and inventory applications, adjusting parameters such as column count and aspect ratio to meet scanning requirements. The snippet illustrates typical steps: instantiate the generator, set code text, configure DataBar‑specific settings, and export the result to an image format. // Prompt: Create DataBar Expanded Stacked barcode with three columns, aspect ratio eight, save BMP image. -// Tags: databar, expanded stacked, barcode, bmp, generation, aspose.barcode, csharp +// Tags: databar, expanded stacked, barcode, generation, bmp, aspose.barcode, encode types, image output using System; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Example program that creates a DataBar Expanded Stacked barcode and saves it as a BMP file. +/// Example program that generates a GS1 DataBar Expanded Stacked barcode and saves it as a BMP file. /// class Program { /// - /// Entry point of the application. + /// Entry point that creates the barcode, configures its properties, and writes the image to disk. /// static void Main() { - // Initialize a barcode generator for the DataBar Expanded Stacked symbology - // and provide a sample GTIN code as the barcode text. - using (var generator = new BarcodeGenerator(EncodeTypes.DatabarExpandedStacked, "(01)12345678901231")) + // Initialize the barcode generator for the GS1 DataBar Expanded Stacked symbology + using (var generator = new BarcodeGenerator(EncodeTypes.DatabarExpandedStacked)) { - // Configure DataBar-specific settings: - // - Set the number of columns to three. - // - Set the aspect ratio to eight (wide barcode). + // Assign the data to be encoded (sample GS1 numeric string) + generator.CodeText = "123456789012"; + + // Configure DataBar‑specific parameters: + // - Columns: three columns for expanded stacked layout + // - AspectRatio: eight, defining the height‑to‑width proportion generator.Parameters.Barcode.DataBar.Columns = 3; // three columns - generator.Parameters.Barcode.DataBar.AspectRatio = 8f; // aspect ratio of eight + generator.Parameters.Barcode.DataBar.AspectRatio = 8f; // aspect ratio eight - // Save the generated barcode image in BMP format. + // Save the generated barcode as a BMP image file generator.Save("databar_expanded_stacked.bmp"); } + + // Output a simple confirmation message to the console + Console.WriteLine("DataBar Expanded Stacked barcode saved as databar_expanded_stacked.bmp"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/create-function-adjusting-itf-quiet-zone-coefficient-based-on-user-margin-return-jpeg-image.cs b/one-dimensional-barcode-types/create-function-adjusting-itf-quiet-zone-coefficient-based-on-user-margin-return-jpeg-image.cs index 489a4cb..892e5b4 100644 --- a/one-dimensional-barcode-types/create-function-adjusting-itf-quiet-zone-coefficient-based-on-user-margin-return-jpeg-image.cs +++ b/one-dimensional-barcode-types/create-function-adjusting-itf-quiet-zone-coefficient-based-on-user-margin-return-jpeg-image.cs @@ -1,8 +1,8 @@ -// Title: ITF14 Barcode Generation with Adjustable Quiet Zone -// Description: Demonstrates generating an ITF14 barcode, adjusting its quiet‑zone based on a user‑specified margin, and saving the result as a JPEG image. -// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to configure barcode parameters such as XDimension and quiet‑zone coefficient using the BarcodeGenerator class. Typical use cases include creating product packaging barcodes (e.g., ITF14) with custom margins for printing workflows. Developers often need to fine‑tune quiet‑zone settings to meet scanner requirements or layout constraints. +// Title: Adjust ITF-14 Quiet Zone Coefficient and Export as JPEG +// Description: Demonstrates how to calculate and set the quiet zone coefficient for an ITF‑14 barcode based on a user‑specified margin, then save the result as a JPEG image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and ITF parameters to customize barcode appearance. Typical use cases include fine‑tuning quiet zones for printing requirements or meeting specific scanner specifications. Developers often need to adjust module size, quiet zone, and output format when integrating barcodes into documents or labels. // Prompt: Create function adjusting ITF quiet zone coefficient based on user margin, return JPEG image. -// Tags: itf, barcode, quietzone, jpeg, generation, aspose.barcode +// Tags: itf, quiet zone, barcode generation, jpeg, aspose.barcode, c# using System; using System.IO; @@ -10,84 +10,60 @@ using Aspose.BarCode.Generation; using Aspose.Drawing.Imaging; -namespace ITFQuietZoneExample +/// +/// Provides an example of adjusting the quiet zone coefficient for an ITF‑14 barcode +/// and exporting the generated barcode as a JPEG image. +/// +class Program { /// - /// Provides a console entry point that generates an ITF14 barcode with a user‑defined quiet‑zone margin - /// and saves the resulting JPEG image to disk. + /// Adjusts the ITF quiet zone coefficient based on the provided margin (in points) + /// and returns the generated barcode image as a JPEG byte array. /// - class Program + /// The desired quiet zone margin expressed in points. + /// Byte array containing the JPEG image of the generated barcode. + static byte[] AdjustITFQuietZone(float marginPoints) { - /// - /// Sample usage: generate an ITF14 barcode with a 20‑point margin and save as JPEG. - /// - static void Main() - { - // 14‑digit ITF14 code to encode. - string codeText = "12345678901231"; + // Sample ITF-14 barcode requires exactly 14 digits. + const string sampleCode = "12345678901231"; - // Desired quiet‑zone margin in points. - float userMargin = 20f; + // Create the barcode generator for ITF-14. + using (var generator = new BarcodeGenerator(EncodeTypes.ITF14, sampleCode)) + { + // Set a reasonable XDimension (module size) in points. + generator.Parameters.Barcode.XDimension.Point = 2f; - // Output file name for the generated JPEG image. - string outputFile = "itf14.jpg"; + // Calculate the quiet zone coefficient. + // QuietZoneCoef = ceil(margin / XDimension). Minimum allowed value is 10. + int coef = (int)Math.Ceiling(marginPoints / generator.Parameters.Barcode.XDimension.Point); + if (coef < 10) + coef = 10; - try - { - // Generate the barcode and obtain JPEG bytes. - byte[] jpegBytes = GenerateITFBarcode(codeText, userMargin); + // Apply the calculated coefficient to the ITF parameters. + generator.Parameters.Barcode.ITF.QuietZoneCoef = coef; - // Write the JPEG bytes to the specified file. - File.WriteAllBytes(outputFile, jpegBytes); - - Console.WriteLine($"Barcode saved to {outputFile}"); - } - catch (Exception ex) + // Save the barcode to a memory stream as JPEG. + using (var ms = new MemoryStream()) { - // Output any errors that occur during generation or file I/O. - Console.WriteLine($"Error: {ex.Message}"); + generator.Save(ms, BarCodeImageFormat.Jpeg); + return ms.ToArray(); } } + } - /// - /// Generates an ITF14 barcode, adjusts the quiet‑zone coefficient based on the supplied margin, - /// and returns the image as a JPEG byte array. - /// - /// The 14‑digit code to encode. - /// Desired quiet‑zone margin in points. - /// JPEG image bytes. - static byte[] GenerateITFBarcode(string codeText, float margin) - { - // Validate that the code text is not null, empty, or whitespace. - if (string.IsNullOrWhiteSpace(codeText)) - throw new ArgumentException("Code text cannot be null or empty.", nameof(codeText)); - - // ITF14 requires exactly 14 numeric digits. - if (codeText.Length != 14 || !long.TryParse(codeText, out _)) - throw new ArgumentException("ITF14 code must be a 14‑digit numeric string.", nameof(codeText)); - - // Create the barcode generator for ITF14. - using (var generator = new BarcodeGenerator(EncodeTypes.ITF14, codeText)) - { - // Set a reasonable XDimension (module width) – 2 points by default. - generator.Parameters.Barcode.XDimension.Point = 2f; - - // Calculate the quiet‑zone coefficient. - // QuietZoneCoef = ceil(margin / XDimension). Minimum allowed value is 10. - int calculatedCoef = (int)Math.Ceiling(margin / generator.Parameters.Barcode.XDimension.Point); - if (calculatedCoef < 10) - calculatedCoef = 10; - - // Apply the coefficient to the ITF parameters. - generator.Parameters.Barcode.ITF.QuietZoneCoef = calculatedCoef; + /// + /// Entry point of the program. Demonstrates usage of + /// and writes the resulting JPEG image to disk. + /// + static void Main() + { + // Example usage: set a margin of 30 points. + float userMargin = 30f; + byte[] jpegData = AdjustITFQuietZone(userMargin); - // Generate the image into a memory stream as JPEG. - using (var ms = new MemoryStream()) - { - generator.Save(ms, BarCodeImageFormat.Jpeg); - return ms.ToArray(); - } - } - } + // Write the JPEG image to a file for verification. + const string outputPath = "ITF_QuietZoneAdjusted.jpg"; + File.WriteAllBytes(outputPath, jpegData); + Console.WriteLine($"Barcode image saved to {outputPath}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/create-memorystream-render-barcode-into-it-and-return-stream-from-web-api.cs b/one-dimensional-barcode-types/create-memorystream-render-barcode-into-it-and-return-stream-from-web-api.cs index c51ef33..e86c536 100644 --- a/one-dimensional-barcode-types/create-memorystream-render-barcode-into-it-and-return-stream-from-web-api.cs +++ b/one-dimensional-barcode-types/create-memorystream-render-barcode-into-it-and-return-stream-from-web-api.cs @@ -1,65 +1,64 @@ -// Title: Generate Barcode Image into MemoryStream for Web API -// Description: Demonstrates creating a Code128 barcode, rendering it to a PNG image stored in a MemoryStream, and returning the stream as would be done in a web API. -// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator, BarCodeImageFormat, and related parameter classes to produce barcode images on the fly. Typical use cases include generating barcodes for invoices, shipping labels, or tickets within ASP.NET Core endpoints. Developers often need to stream the image directly to HTTP responses without writing to disk. +// Title: Generate a Code128 barcode and return it as a MemoryStream +// Description: Demonstrates creating a Code128 barcode image in PNG format using Aspose.BarCode, storing it in a MemoryStream, and returning the stream for use in a web API response. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to use the BarcodeGenerator class to encode data, save the result to a stream, and manage stream positioning. Developers building web services or APIs often need to produce barcode images on‑the‑fly without writing temporary files, and this pattern shows the typical workflow with key classes such as BarcodeGenerator, EncodeTypes, BarCodeImageFormat, and MemoryStream. // Prompt: Create a MemoryStream, render the barcode into it, and return the stream from a web API. -// Tags: code128, barcode generation, png, memorystream, aspose.barcode, aspnet +// Tags: code128, barcode generation, png, memorystream, aspose.barcode using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; -namespace BarcodeApiSimulation +/// +/// Simulated API class that provides barcode generation functionality. +/// +class Program { /// - /// Simulates the core logic of a web API that generates a barcode image and returns it as a . + /// Generates a Code128 barcode image, writes it to a in PNG format, + /// and returns the stream positioned at the beginning for reading. /// - class Program + /// The text to encode in the barcode. + /// A containing the barcode image. + static MemoryStream GetBarcodeStream(string codeText) { - /// - /// Generates a barcode image for the specified text, writes it to a in PNG format, - /// and returns the stream positioned at the beginning for reading. - /// - /// The text to encode in the barcode. - /// A containing the PNG barcode image. - static MemoryStream GenerateBarcodeStream(string codeText) - { - // Create a memory stream to hold the generated image. - var memoryStream = new MemoryStream(); - - // Initialize the barcode generator with Code128 symbology and the provided text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) - { - // Optional: customize the barcode's appearance. - generator.Parameters.Barcode.BarColor = Color.Blue; // Set barcode bars to blue. - generator.Parameters.BackColor = Color.White; // Set background to white. + // Allocate a memory stream that will hold the generated PNG image. + var barcodeStream = new MemoryStream(); - // Save the barcode image into the memory stream as a PNG. - generator.Save(memoryStream, BarCodeImageFormat.Png); - } - - // Reset the stream position so callers can read from the beginning. - memoryStream.Position = 0; - return memoryStream; + // Create a BarcodeGenerator for Code128 symbology with the supplied text. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + { + // Persist the barcode image directly into the memory stream. + generator.Save(barcodeStream, BarCodeImageFormat.Png); } - /// - /// Entry point for the console demonstration. Generates a sample barcode and writes its size to the console. - /// In a real web API, the returned would be sent to the client. - /// - /// Command‑line arguments (not used). - static void Main(string[] args) + // Rewind the stream so callers can read from the start. + barcodeStream.Position = 0; + return barcodeStream; + } + + /// + /// Demonstrates the use of and optionally writes the image to a file. + /// In a real web API the returned stream would be sent as the HTTP response body. + /// + static void Main() + { + // Generate a barcode for the sample text "123ABC". + using (MemoryStream stream = GetBarcodeStream("123ABC")) { - const string sampleText = "123ABC"; + // Output the size of the generated image for verification. + Console.WriteLine($"Generated barcode image size: {stream.Length} bytes"); - // Generate the barcode stream for the sample text. - using (MemoryStream barcodeStream = GenerateBarcodeStream(sampleText)) + // Optional: save the stream to a physical file to inspect the result. + const string outputPath = "barcode.png"; + using (FileStream file = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) { - // Output the length of the generated stream for verification. - Console.WriteLine($"Generated barcode stream length: {barcodeStream.Length} bytes"); - // In a real API, the stream would be returned directly to the HTTP response. + stream.CopyTo(file); } + + Console.WriteLine($"Barcode image saved to {outputPath}"); } + + // Note: In production, the MemoryStream would be returned directly from a controller action. } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/create-powershell-module-accepting-barcode-data-outputting-code-16k-png-with-specified-quiet-zones.cs b/one-dimensional-barcode-types/create-powershell-module-accepting-barcode-data-outputting-code-16k-png-with-specified-quiet-zones.cs index 8094820..ebc985d 100644 --- a/one-dimensional-barcode-types/create-powershell-module-accepting-barcode-data-outputting-code-16k-png-with-specified-quiet-zones.cs +++ b/one-dimensional-barcode-types/create-powershell-module-accepting-barcode-data-outputting-code-16k-png-with-specified-quiet-zones.cs @@ -1,64 +1,66 @@ // Title: Generate Code 16K barcode PNG with custom quiet zones -// Description: Demonstrates creating a Code 16K barcode image using Aspose.BarCode, allowing input data and quiet‑zone coefficients via command‑line arguments. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, showcasing the BarcodeGenerator class with EncodeTypes.Code16K. It illustrates typical use cases such as customizing quiet zones and exporting to PNG, which developers often need when integrating barcode creation into scripts or CI pipelines. +// Description: Demonstrates creating a Code 16K barcode image, configuring left and right quiet zone coefficients, and saving the result as a PNG file. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use the BarcodeGenerator class with EncodeTypes.Code16K. Developers commonly use these APIs to produce high‑density barcodes for packaging, inventory, and shipping labels, adjusting parameters such as quiet zones and aspect ratio to meet printing specifications. // Prompt: Create PowerShell module accepting barcode data, outputting Code 16K PNG with specified quiet zones. -// Tags: code16k, barcode, generation, png, quietzone, aspose.barcode, csharp +// Tags: barcode, code16k, generation, png, quietzone, aspose.barcode, csharp using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -namespace Code16KGenerator +/// +/// Example program that generates a Code 16K barcode image with configurable quiet zones +/// and saves it as a PNG file using Aspose.BarCode. +/// +class Program { /// - /// Generates a Code 16K barcode image (PNG) using Aspose.BarCode. - /// Accepts optional command‑line arguments for the barcode data and quiet‑zone coefficients. + /// Entry point of the application. + /// Accepts optional command‑line arguments: barcode text, left quiet zone coefficient, right quiet zone coefficient. /// - class Program + /// Command‑line arguments. + static void Main(string[] args) { - /// - /// Entry point of the application. - /// Parses arguments, configures the barcode generator, and saves the PNG file. - /// - /// - /// args[0] – barcode data (default: "1234567890123456") - /// args[1] – left quiet‑zone coefficient (default: 10) - /// args[2] – right quiet‑zone coefficient (default: 1) - /// - static void Main(string[] args) - { - // Default barcode data and quiet‑zone coefficients - string codeText = "1234567890123456"; - int leftQuietZone = 10; // default left coefficient - int rightQuietZone = 1; // default right coefficient + // Default barcode data and quiet zone coefficients + string codeText = "1234567890"; + int quietLeft = 10; // default left quiet zone coefficient + int quietRight = 1; // default right quiet zone coefficient - // Override defaults with command‑line arguments, if provided - if (args.Length > 0 && !string.IsNullOrWhiteSpace(args[0])) - codeText = args[0]; + // Parse command‑line arguments if provided + if (args.Length > 0 && !string.IsNullOrWhiteSpace(args[0])) + codeText = args[0]; - if (args.Length > 1 && int.TryParse(args[1], out int left)) - leftQuietZone = left; + if (args.Length > 1 && int.TryParse(args[1], out int left)) + quietLeft = left; - if (args.Length > 2 && int.TryParse(args[2], out int right)) - rightQuietZone = right; + if (args.Length > 2 && int.TryParse(args[2], out int right)) + quietRight = right; - // Output file name for the generated PNG image - string outputPath = "code16k.png"; + // Determine output file path (current directory) + string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "code16k.png"); + try + { // Initialize the barcode generator for Code 16K symbology using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, codeText)) { - // Apply the specified quiet‑zone coefficients - generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = leftQuietZone; - generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = rightQuietZone; + // Apply quiet zone coefficients + generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = quietLeft; + generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = quietRight; + + // Optional: set aspect ratio (default is 1.0f) + generator.Parameters.Barcode.Code16K.AspectRatio = 1f; - // Save the barcode image as PNG - generator.Save(outputPath); + // Save the generated barcode as a PNG image + generator.Save(outputPath, BarCodeImageFormat.Png); } - // Inform the user where the file was saved - Console.WriteLine($"Code 16K barcode saved to '{Path.GetFullPath(outputPath)}'."); + Console.WriteLine($"Code16K barcode saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error generating barcode: {ex.Message}"); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/create-web-api-endpoint-returning-generated-code-16k-barcode-image-based-on-query-parameters.cs b/one-dimensional-barcode-types/create-web-api-endpoint-returning-generated-code-16k-barcode-image-based-on-query-parameters.cs index b1e7734..c07f5ae 100644 --- a/one-dimensional-barcode-types/create-web-api-endpoint-returning-generated-code-16k-barcode-image-based-on-query-parameters.cs +++ b/one-dimensional-barcode-types/create-web-api-endpoint-returning-generated-code-16k-barcode-image-based-on-query-parameters.cs @@ -1,58 +1,53 @@ -// Title: Generate Code 16K barcode image -// Description: Demonstrates generating a Code 16K barcode image using Aspose.BarCode and saving it to a file. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to use the BarcodeGenerator class with EncodeTypes.Code16K. Typical use cases include creating barcode images for inventory, shipping, or product labeling in .NET applications. Developers often need to customize parameters such as aspect ratio and output format before saving the image. +// Title: Generate Code 16K barcode image and return as Base64 string +// Description: Demonstrates creating a Code 16K barcode with custom aspect ratio and quiet zones, rendering it to PNG, and outputting the image as a Base64 string for use in an HTTP response. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode parameters (EncodeTypes, aspect ratio, quiet zones) with the BarcodeGenerator class, render the barcode to an image format (PNG), and retrieve the binary data. Typical use cases include web APIs that need to return barcode images on‑the‑fly, mobile apps generating barcodes for scanning, or batch processes creating printable barcode assets. Developers often need to adjust size, layout, and output format, making this pattern a common starting point for barcode‑related services. // Prompt: Create web API endpoint returning generated Code 16K barcode image based on query parameters. -// Tags: code16k, barcode, generation, png, aspose.barcode, aspnetcore, webapi +// Tags: code16k, barcode, generation, image, png, base64, aspose.barcode, aspnet, webapi using System; +using System.IO; +using System.Text; using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Example program that generates a Code 16K barcode image using Aspose.BarCode. +/// Sample console application that simulates a web API endpoint generating a Code 16K barcode. /// class Program { /// - /// Entry point of the application. Generates a barcode based on optional command‑line arguments. + /// Entry point that creates a barcode, encodes it to PNG, and writes the image as a Base64 string. /// - /// - /// args[0] – barcode text (default "1234567890") - /// args[1] – aspect ratio as a positive float (default 1.0) - /// args[2] – output file path (default "code16k.png") - /// - static void Main(string[] args) + static void Main() { - // Default values for barcode generation + // Simulated request parameters that would normally come from query string values string codeText = "1234567890"; - float aspectRatio = 1.0f; - string outputPath = "code16k.png"; + float aspectRatio = 2.0f; // Height/Width ratio for the barcode + int quietZoneLeftCoef = 10; // Minimum allowed quiet zone on the left side + int quietZoneRightCoef = 1; // Minimum allowed quiet zone on the right side - // Override defaults with command‑line arguments when provided - if (args.Length > 0 && !string.IsNullOrWhiteSpace(args[0])) - codeText = args[0]; - - if (args.Length > 1 && float.TryParse(args[1], out float parsedRatio)) - { - if (parsedRatio <= 0f) - throw new ArgumentOutOfRangeException(nameof(aspectRatio), "Aspect ratio must be positive."); - aspectRatio = parsedRatio; - } - - if (args.Length > 2 && !string.IsNullOrWhiteSpace(args[2])) - outputPath = args[2]; - - // Initialize the barcode generator for the Code 16K symbology + // Initialize the barcode generator for the Code16K symbology using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, codeText)) { - // Apply the specified aspect ratio to the Code 16K modules + // Apply Code16K‑specific settings generator.Parameters.Barcode.Code16K.AspectRatio = aspectRatio; - - // Save the generated barcode as a PNG image to the specified path - generator.Save(outputPath, BarCodeImageFormat.Png); + generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = quietZoneLeftCoef; + generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = quietZoneRightCoef; + + // Optionally define the output image size in points (300x150 points in this example) + generator.Parameters.ImageWidth.Point = 300f; + generator.Parameters.ImageHeight.Point = 150f; + + // Render the barcode to a memory stream in PNG format + using (var ms = new MemoryStream()) + { + generator.Save(ms, BarCodeImageFormat.Png); + byte[] imageBytes = ms.ToArray(); + + // Convert the PNG bytes to a Base64 string to simulate an HTTP response body + string base64 = Convert.ToBase64String(imageBytes); + Console.WriteLine(base64); + } } - - // Inform the user where the barcode image was saved - Console.WriteLine($"Code16K barcode saved to '{outputPath}'."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/develop-console-application-reading-csv-barcode-data-creating-corresponding-code-16k-png-images.cs b/one-dimensional-barcode-types/develop-console-application-reading-csv-barcode-data-creating-corresponding-code-16k-png-images.cs index ad93cfe..4d46c9a 100644 --- a/one-dimensional-barcode-types/develop-console-application-reading-csv-barcode-data-creating-corresponding-code-16k-png-images.cs +++ b/one-dimensional-barcode-types/develop-console-application-reading-csv-barcode-data-creating-corresponding-code-16k-png-images.cs @@ -1,8 +1,8 @@ -// Title: Generate Code 16K Barcodes from CSV -// Description: Reads a CSV file with filename and Code 16K text pairs and creates PNG barcode images using Aspose.BarCode. -// Category-Description: Demonstrates Aspose.BarCode barcode generation for the Code 16K symbology. Shows how to configure generator parameters, handle CSV input, and save images in PNG format. Ideal for developers needing batch barcode creation in console applications, covering key classes like BarcodeGenerator, EncodeTypes, and BarCodeImageFormat. +// Title: Generate Code 16K barcodes from CSV data +// Description: This example reads a CSV file containing filenames and barcode texts, then creates Code 16K PNG images using Aspose.BarCode. +// Category-Description: Demonstrates batch barcode generation with Aspose.BarCode in a console application. It showcases the BarcodeGenerator class, EncodeTypes.Code16K, and image saving via BarCodeImageFormat. Typical use cases include bulk creation of barcode assets for inventory, shipping, or labeling systems where developers need to automate image output from data sources. // Prompt: Develop console application reading CSV barcode data, creating corresponding Code 16K PNG images. -// Tags: code16k, barcode generation, png output, aspose.barcode, console app +// Tags: barcode, code16k, csv, png, batch-generation, aspose.barcode, console using System; using System.IO; @@ -11,85 +11,80 @@ using Aspose.Drawing; /// -/// Console application that reads a CSV file containing barcode data and generates -/// Code 16K PNG images using the Aspose.BarCode library. +/// Console application that reads barcode data from a CSV file and generates Code 16K PNG images. /// class Program { /// - /// Entry point of the application. Processes the CSV file and creates barcode images. + /// Entry point. Processes the CSV, generates barcodes, and saves them as PNG files. /// - /// Command‑line arguments (not used). - static void Main(string[] args) + static void Main() { - // Path to the CSV file containing barcode data. - string csvPath = "barcodes.csv"; + const string csvPath = "input.csv"; + const string outputFolder = "Barcodes"; - // If the CSV does not exist, create a small sample file. + // Verify that the CSV file exists if (!File.Exists(csvPath)) { - using (var writer = new StreamWriter(csvPath)) - { - writer.WriteLine("sample1.png,HELLO123"); - writer.WriteLine("sample2.png,WORLD456"); - } - Console.WriteLine($"Sample CSV created at '{csvPath}'."); + Console.WriteLine($"CSV file not found: {csvPath}"); + return; } - // Open the CSV for reading line by line. - using (var reader = new StreamReader(csvPath)) + // Ensure the output directory exists + if (!Directory.Exists(outputFolder)) { - string line; - int lineNumber = 0; - - // Process each non‑empty line. - while ((line = reader.ReadLine()) != null) - { - lineNumber++; - - // Skip blank lines. - if (string.IsNullOrWhiteSpace(line)) - continue; + Directory.CreateDirectory(outputFolder); + } - // Split the line into filename and barcode text. - string[] parts = line.Split(','); - if (parts.Length < 2) - { - Console.WriteLine($"Invalid format at line {lineNumber}: '{line}'. Expected 'filename,codeText'."); - continue; - } + // Read all lines from the CSV file + string[] lines = File.ReadAllLines(csvPath); + foreach (string rawLine in lines) + { + // Skip empty or whitespace-only lines + if (string.IsNullOrWhiteSpace(rawLine)) + continue; - string fileName = parts[0].Trim(); - string codeText = parts[1].Trim(); + // Expected CSV format: filename,codeText + string[] parts = rawLine.Split(','); + if (parts.Length < 2) + { + Console.WriteLine($"Invalid line (expected two columns): {rawLine}"); + continue; + } - // Validate that barcode text is present. - if (string.IsNullOrEmpty(codeText)) - { - Console.WriteLine($"Empty CodeText at line {lineNumber}."); - continue; - } + string fileName = parts[0].Trim(); + string codeText = parts[1].Trim(); - // Generate the barcode using Aspose.BarCode. - using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, codeText)) - { - // Enable automatic sizing based on content. - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; + // Validate that both filename and code text are provided + if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(codeText)) + { + Console.WriteLine($"Empty filename or codetext in line: {rawLine}"); + continue; + } - // Set Code16K‑specific aspect ratio (default is 1.0). - generator.Parameters.Barcode.Code16K.AspectRatio = 1.0f; + // Build the full output path and ensure a .png extension + string outputPath = Path.Combine(outputFolder, fileName); + if (!outputPath.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) + outputPath += ".png"; - // Optional visual settings: black bars on white background. - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; - generator.Parameters.BackColor = Aspose.Drawing.Color.White; + // Create and configure the barcode generator for Code16K + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code16K)) + { + // Set the text to encode + generator.CodeText = codeText; - // Build the full output path for the PNG file. - string outputPath = Path.Combine(Directory.GetCurrentDirectory(), fileName); + // Optional: configure Code16K specific parameters + generator.Parameters.Barcode.Code16K.AspectRatio = 1.0f; // default aspect ratio + generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = 1; // integer value + generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = 1; // integer value - // Save the generated barcode as a PNG image. - generator.Save(outputPath, BarCodeImageFormat.Png); - Console.WriteLine($"Generated '{outputPath}'."); - } + // Save the generated barcode as a PNG image + generator.Save(outputPath, BarCodeImageFormat.Png); } + + Console.WriteLine($"Generated barcode: {outputPath}"); } + + Console.WriteLine("Processing completed."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/develop-script-reading-barcode-specs-from-json-creating-databar-images-saving-to-folder.cs b/one-dimensional-barcode-types/develop-script-reading-barcode-specs-from-json-creating-databar-images-saving-to-folder.cs index b60519a..45a4340 100644 --- a/one-dimensional-barcode-types/develop-script-reading-barcode-specs-from-json-creating-databar-images-saving-to-folder.cs +++ b/one-dimensional-barcode-types/develop-script-reading-barcode-specs-from-json-creating-databar-images-saving-to-folder.cs @@ -1,127 +1,128 @@ -// Title: Generate DataBar barcodes from JSON specifications -// Description: Reads a JSON file describing DataBar barcode parameters, creates corresponding barcode images, and saves them to a folder. -// Category-Description: This example demonstrates Aspose.BarCode generation of DataBar symbologies (e.g., DatabarLimited, DatabarOmniDirectional). It uses BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes to produce PNG images. Developers working with bulk barcode creation, automated reporting, or inventory labeling can adapt this pattern for batch processing of barcode data. +// Title: Generate DataBar barcodes from JSON specifications and save as PNG images +// Description: This example reads a JSON file containing barcode symbology and code text, creates DataBar barcode images using Aspose.BarCode, and saves them to a designated folder. +// Category-Description: Demonstrates Aspose.BarCode generation workflow for DataBar symbologies. It covers reading input data with System.Text.Json, mapping symbology names to EncodeTypes via reflection, configuring BarcodeGenerator, and exporting PNG files. Ideal for developers needing batch barcode creation, automated report generation, or inventory labeling solutions. // Prompt: Develop script reading barcode specs from JSON, creating DataBar images, saving to folder. -// Tags: databar, barcode generation, png, aspose.barcode, aspose.drawing, json +// Tags: barcode, databar, generation, json, png, aspose.barcode, encode types, batch processing 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 BarcodeDataBarGenerator +namespace BarcodeGeneratorApp { /// - /// Represents a single barcode specification read from JSON. + /// Model that matches the structure of each barcode specification in the input JSON file. /// public class BarcodeSpec { - public string Symbology { get; set; } // e.g., "DatabarLimited", "DatabarOmniDirectional" - public string CodeText { get; set; } // Text to encode - public string FileName { get; set; } // Output image file name + public string Symbology { get; set; } + public string CodeText { get; set; } } /// - /// Entry point for the DataBar barcode generation example. + /// Entry point for the barcode generation console application. + /// Reads specifications from a JSON file, generates DataBar barcodes, and saves them as PNG images. /// class Program { /// - /// Reads barcode specifications from a JSON file, generates DataBar barcode images, and saves them to the output folder. + /// Main method that orchestrates reading, processing, and saving barcode images. /// static void Main() { - // Path to the input JSON file containing an array of BarcodeSpec objects. - const string jsonPath = "barcodes.json"; + // Path to the JSON file that contains an array of barcode specifications. + const string jsonPath = "barcodeSpecs.json"; - // Directory where generated barcode images will be stored. - const string outputFolder = "output"; - - // Verify that the JSON input file exists. + // Verify that the JSON file exists before attempting to read it. if (!File.Exists(jsonPath)) { - Console.WriteLine($"Input file not found: {jsonPath}"); + Console.WriteLine($"JSON file not found: {jsonPath}"); return; } - // Ensure the output directory exists; create it if necessary. - if (!Directory.Exists(outputFolder)) - { - Directory.CreateDirectory(outputFolder); - } - - // Deserialize the JSON specifications into a list of BarcodeSpec objects. - List specs; + // Read the entire JSON content and deserialize it into an array of BarcodeSpec objects. + string jsonContent = File.ReadAllText(jsonPath); + BarcodeSpec[] specs; try { - string jsonContent = File.ReadAllText(jsonPath); - specs = JsonSerializer.Deserialize>(jsonContent); + specs = JsonSerializer.Deserialize(jsonContent); if (specs == null) { - Console.WriteLine("No barcode specifications found in the JSON file."); + Console.WriteLine("No barcode specifications found in JSON."); return; } } catch (Exception ex) { - Console.WriteLine($"Failed to read or parse JSON: {ex.Message}"); + Console.WriteLine($"Failed to parse JSON: {ex.Message}"); return; } - // Process each specification, limiting the number of items for safety. - int processedCount = 0; - const int maxItems = 10; // safety cap - foreach (var spec in specs) + // Ensure the output directory exists; create it if it does not. + const string outputDir = "Barcodes"; + if (!Directory.Exists(outputDir)) { - if (processedCount >= maxItems) - break; + Directory.CreateDirectory(outputDir); + } + + // Iterate over each barcode specification and generate the corresponding image. + for (int i = 0; i < specs.Length; i++) + { + var spec = specs[i]; + + // Validate that a symbology name is provided. + if (string.IsNullOrWhiteSpace(spec?.Symbology)) + { + Console.WriteLine($"Specification #{i + 1} missing symbology."); + continue; + } - // Validate that all required fields are present. - if (string.IsNullOrWhiteSpace(spec.Symbology) || - string.IsNullOrWhiteSpace(spec.CodeText) || - string.IsNullOrWhiteSpace(spec.FileName)) + // Resolve the symbology name to a BaseEncodeType using reflection (case‑insensitive). + var field = typeof(EncodeTypes).GetField(spec.Symbology, + BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase); + if (field == null) { - Console.WriteLine("Skipping incomplete specification."); + Console.WriteLine($"Unknown symbology '{spec.Symbology}' in specification #{i + 1}."); continue; } - // Resolve the symbology name to an EncodeTypes field via reflection. - var fieldInfo = typeof(EncodeTypes).GetField(spec.Symbology); - if (fieldInfo == null) + if (!(field.GetValue(null) is BaseEncodeType encodeType)) { - Console.WriteLine($"Unknown symbology: {spec.Symbology}"); + Console.WriteLine($"Failed to obtain encode type for '{spec.Symbology}'."); continue; } - BaseEncodeType encodeType = (BaseEncodeType)fieldInfo.GetValue(null); + // Determine the code text to encode; provide a default if none is supplied. + string codeText = spec.CodeText; + if (string.IsNullOrWhiteSpace(codeText)) + { + // Use a generic GTIN‑like value for DataBarLimited; otherwise a simple numeric string. + codeText = encodeType == EncodeTypes.DatabarLimited + ? "(01)08888888888888" + : "(01)12345678901231"; + } - // Create the barcode generator with the resolved type and provided text. - using (var generator = new BarcodeGenerator(encodeType, spec.CodeText)) + // Create the barcode generator, assign the code text, and save the image as PNG. + using (var generator = new BarcodeGenerator(encodeType)) { - // Configure common settings for DataBar images. - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; - generator.Parameters.BackColor = Aspose.Drawing.Color.White; - - // Determine the full output path for the image file. - string outputPath = Path.Combine(outputFolder, spec.FileName); - try - { - // Save the generated barcode as a PNG image. - generator.Save(outputPath, BarCodeImageFormat.Png); - Console.WriteLine($"Generated: {outputPath}"); - } - catch (Exception ex) - { - Console.WriteLine($"Failed to generate barcode for {spec.FileName}: {ex.Message}"); - } + generator.CodeText = codeText; + + // Construct a unique file name based on the symbology type and index. + string fileName = $"{encodeType.TypeName}_{i + 1}.png"; + string filePath = Path.Combine(outputDir, fileName); + + // Save the generated barcode image in PNG format. + generator.Save(filePath, BarCodeImageFormat.Png); } - processedCount++; + Console.WriteLine($"Generated barcode #{i + 1}: {spec.Symbology} -> {codeText}"); } + + // Program completes without waiting for user input. } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/enable-automatic-size-adjustment-so-dimensions-adapt-based-on-length-of-codetext.cs b/one-dimensional-barcode-types/enable-automatic-size-adjustment-so-dimensions-adapt-based-on-length-of-codetext.cs index 17aed39..91f57f7 100644 --- a/one-dimensional-barcode-types/enable-automatic-size-adjustment-so-dimensions-adapt-based-on-length-of-codetext.cs +++ b/one-dimensional-barcode-types/enable-automatic-size-adjustment-so-dimensions-adapt-based-on-length-of-codetext.cs @@ -1,45 +1,62 @@ // Title: Automatic barcode size adjustment based on CodeText length -// Description: Demonstrates enabling auto‑size mode and dynamically setting image dimensions so the barcode adapts to the length of the supplied CodeText. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator, AutoSizeMode, and image dimension parameters. Developers often need to create barcodes that automatically fit varying data lengths for labels, receipts, or inventory tags. The snippet shows typical usage of EncodeTypes, BarcodeGenerator.Parameters, and saving the output image. +// Description: Demonstrates how to generate Code128 barcodes where the image dimensions automatically adapt to the length of the supplied CodeText. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and AutoSizeMode for dynamic sizing. Developers often need to create barcodes of varying lengths without manually calculating dimensions, and this pattern shows typical usage for generating PNG images in batch. // Prompt: Enable automatic size adjustment so dimensions adapt based on the length of CodeText. -// Tags: barcode, autosize, code128, image-dimensions, aspose.barcode, generation +// Tags: barcode, code128, autosize, dynamic sizing, png, aspose.barcode, generation using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing.Imaging; /// -/// Generates a Code128 barcode with automatic size adjustment based on the length of the provided CodeText. +/// Demonstrates automatic size adjustment for Code128 barcodes based on the length of the CodeText. /// class Program { /// - /// Entry point of the example. Creates a barcode, configures auto‑size mode, calculates dimensions, and saves the image. + /// Entry point. Generates a set of barcodes with varying text lengths, saving each as a PNG file. /// static void Main() { - // Sample code text; in real scenarios this could come from any source. - string codeText = "Sample12345"; + // Define a collection of sample code texts with different lengths + string[] codeTexts = new[] + { + "A1", + "ABC123", + "LongerCodeTextExample12345", + "EvenLongerCodeTextExampleThatExceedsTypicalLengths1234567890" + }; + + // Ensure the output directory exists before saving images + string outputDir = "Barcodes"; + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } - // Initialize a barcode generator for Code128 with the specified code text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // Iterate over each sample text and generate a corresponding barcode + foreach (var text in codeTexts) { - // Enable automatic size adjustment using interpolation mode. - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; + // Initialize the generator for Code128, which supports alphanumeric strings + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, text)) + { + // Set AutoSizeMode to None to keep the default automatic sizing behavior explicit + generator.Parameters.AutoSizeMode = AutoSizeMode.None; - // Calculate image dimensions based on the length of the code text. - // Width grows with the number of characters; height remains constant. - float width = 100f + codeText.Length * 10f; // points - float height = 50f; // points + // Optionally reduce the X-dimension to keep the overall image size reasonable + generator.Parameters.Barcode.XDimension.Point = 2f; - // Apply the calculated dimensions to the generator. - generator.Parameters.ImageWidth.Point = width; - generator.Parameters.ImageHeight.Point = height; + // Build a filename that reflects the length of the code text + string fileName = Path.Combine(outputDir, $"barcode_{text.Length}.png"); - // Save the generated barcode image to a file. - generator.Save("auto_sized_barcode.png"); - } + // Save the generated barcode as a PNG image + generator.Save(fileName, BarCodeImageFormat.Png); - Console.WriteLine("Barcode generated and saved as 'auto_sized_barcode.png'."); + // Output a simple status message to the console + Console.WriteLine($"Generated barcode for text length {text.Length}: {fileName}"); + } + } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/enable-checksum-calculation-choose-mod10-algorithm-and-verify-checksum-after-generation.cs b/one-dimensional-barcode-types/enable-checksum-calculation-choose-mod10-algorithm-and-verify-checksum-after-generation.cs index cf9c3e7..05fa1c5 100644 --- a/one-dimensional-barcode-types/enable-checksum-calculation-choose-mod10-algorithm-and-verify-checksum-after-generation.cs +++ b/one-dimensional-barcode-types/enable-checksum-calculation-choose-mod10-algorithm-and-verify-checksum-after-generation.cs @@ -1,72 +1,56 @@ -// Title: Enable Mod10 checksum for Codabar barcode and verify it -// Description: Demonstrates generating a Codabar barcode with checksum enabled using the Mod10 algorithm, then reads the barcode to confirm the checksum is present. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, illustrating how to configure checksum settings for one‑dimensional symbologies. It uses BarcodeGenerator for creating barcodes and BarCodeReader for decoding, common tasks when developers need data integrity verification in inventory, shipping, or point‑of‑sale systems. +// Title: Generate and Verify Codabar Barcode with Mod10 Checksum +// Description: Demonstrates how to generate a Codabar barcode with checksum enabled using the Mod10 algorithm, save it as an image, and then recognize it while validating the checksum. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It shows how to configure checksum settings on the BarcodeGenerator, use Codabar-specific parameters, and perform checksum validation with BarCodeReader. Developers working with one-dimensional symbologies often need to ensure data integrity by enabling and verifying checksums during both encoding and decoding phases. // Prompt: Enable checksum calculation, choose Mod10 algorithm, and verify the checksum after generation. -// Tags: codabar, checksum, mod10, generation, recognition, aspose.barcode, one-dimensional +// Tags: codabar, checksum, mod10, barcode generation, barcode recognition, aspose.barcode, one-dimensional, csharp using System; -using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Demonstrates enabling Mod10 checksum for a Codabar barcode, saving it, and verifying the checksum during recognition. +/// Example program that creates a Codabar barcode with a Mod10 checksum, +/// saves it to a PNG file, and then reads it back while validating the checksum. /// class Program { /// - /// Entry point. Generates a Codabar barcode with checksum, saves it, and validates the checksum on read. + /// Entry point of the example. Generates the barcode, saves it, and verifies the checksum during recognition. /// static void Main() { - // Define the output file path for the generated barcode image - string outputPath = "codabar.png"; - - // Sample Codabar text including start/stop symbols (A...A) - string codeText = "A123456A"; - - // Create a barcode generator for Codabar with the specified text - using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, codeText)) + // Initialize a Codabar barcode generator with sample code text. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Codabar, "A12345B")) { - // Enable checksum calculation for the barcode + // Enable checksum generation for the barcode. generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes; - // Set the checksum algorithm to Mod10 for Codabar + // Select the Mod10 algorithm for Codabar checksum calculation. generator.Parameters.Barcode.Codabar.ChecksumMode = CodabarChecksumMode.Mod10; - // Save the generated barcode image to the specified file - generator.Save(outputPath); - } - - // Verify that the barcode image file was successfully created - if (!File.Exists(outputPath)) - { - Console.WriteLine("Failed to generate the barcode image."); - return; - } + // Allow generation even if the code text is slightly incorrect. + generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; - // Initialize a barcode reader to decode the saved image using Codabar symbology - using (var reader = new BarCodeReader(outputPath, DecodeType.Codabar)) - { - // Turn on checksum validation during the recognition process - reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; + // Generate the barcode image and save it to a file (format inferred from extension). + using (Aspose.Drawing.Bitmap image = generator.GenerateBarCodeImage()) + { + generator.Save("codabar.png"); + } - // Iterate through all recognized barcodes (should be only one in this case) - foreach (var result in reader.ReadBarCodes()) + // Create a reader to recognize the saved barcode and validate its checksum. + using (BarCodeReader reader = new BarCodeReader("codabar.png", DecodeType.Codabar)) { - // Output the recognized text and the extracted checksum value - Console.WriteLine($"Recognized CodeText: {result.CodeText}"); - Console.WriteLine($"Extracted Checksum: {result.Extended.OneD.CheckSum}"); + // Turn on checksum validation during the recognition process. + reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; - // Simple verification: ensure a checksum value was returned - if (!string.IsNullOrEmpty(result.Extended.OneD.CheckSum)) - { - Console.WriteLine("Checksum verification succeeded."); - } - else + // Iterate through all recognized barcodes (there should be one). + foreach (BarCodeResult result in reader.ReadBarCodes()) { - Console.WriteLine("Checksum verification failed."); + Console.WriteLine("Recognized CodeText: " + result.CodeText); + // Output the checksum value if it is present in the extended OneD parameters. + Console.WriteLine("Checksum (if any): " + result.Extended.OneD.CheckSum); } } } diff --git a/one-dimensional-barcode-types/export-barcode-configuration-to-xml-edit-forecolor-attribute-to-green-re-import-and-generate-updated-image.cs b/one-dimensional-barcode-types/export-barcode-configuration-to-xml-edit-forecolor-attribute-to-green-re-import-and-generate-updated-image.cs index 40dd82c..5c159d3 100644 --- a/one-dimensional-barcode-types/export-barcode-configuration-to-xml-edit-forecolor-attribute-to-green-re-import-and-generate-updated-image.cs +++ b/one-dimensional-barcode-types/export-barcode-configuration-to-xml-edit-forecolor-attribute-to-green-re-import-and-generate-updated-image.cs @@ -1,85 +1,73 @@ -// Title: Export barcode configuration to XML, modify foreground color, and regenerate image -// Description: Demonstrates exporting a barcode generator's settings to XML, changing the bar color to green, re-importing the configuration, and saving the updated barcode image. -// Category-Description: This example belongs to the Aspose.BarCode configuration management category, illustrating how to use BarcodeGenerator's ExportToXml and ImportFromXml methods. Developers often need to persist barcode settings, edit them (e.g., colors, sizes) via XML, and recreate barcodes without rebuilding code. The key API classes include BarcodeGenerator, EncodeTypes, and XML handling via System.Xml.Linq. +// Title: Export, edit, and re-import barcode configuration via XML to change bar color +// Description: Demonstrates exporting a barcode generator's settings to an XML file, modifying the bar color to green, re‑importing the configuration, and generating a PNG image with the updated appearance. +// Category-Description: This example belongs to the Aspose.BarCode configuration management category. It shows how to use BarcodeGenerator.ExportToXml and BarcodeGenerator.ImportFromXml together with Aspose.Drawing to persist, edit, and reuse barcode settings. Typical scenarios include batch processing, dynamic style changes, and integration with external configuration systems where developers need to programmatically adjust barcode properties such as colors, fonts, or symbology. // Prompt: Export barcode configuration to XML, edit ForeColor attribute to green, re‑import, and generate updated image. -// Tags: barcode, export, import, xml, color, code128, aspose.barcode, image generation +// Tags: barcode, export, import, xml, color, code128, png, aspose.barcode, aspose.drawing using System; using System.IO; -using System.Linq; using System.Xml.Linq; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Example program that exports a barcode configuration to XML, modifies the foreground color, -/// re-imports the configuration, and generates an updated barcode image. +/// Demonstrates exporting a barcode configuration to XML, editing the bar color, +/// re‑importing the configuration, and generating an updated barcode image. /// class Program { /// - /// Entry point of the example. Performs the export‑modify‑import workflow and saves the resulting images. + /// Entry point of the example. Performs the export‑modify‑import workflow and saves the resulting PNG image. /// static void Main() { - // Define file paths in the current working directory - string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "barcode.png"); - string xmlPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode.xml"); - string updatedImagePath = Path.Combine(Directory.GetCurrentDirectory(), "barcode_updated.png"); + // Define file paths for the temporary XML configuration and the final PNG image. + string xmlPath = Path.Combine(Environment.CurrentDirectory, "barcode.xml"); + string imagePath = Path.Combine(Environment.CurrentDirectory, "barcode.png"); - // Step 1: Create a barcode generator, generate the initial image, and export its configuration to XML + // -------------------------------------------------------------------- + // 1. Create a barcode generator with sample data and export its settings. + // -------------------------------------------------------------------- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) { - generator.Save(imagePath); // Save the original barcode image - generator.ExportToXml(xmlPath); // Export the generator's settings to an XML file + // Export the current generator configuration to an XML file. + generator.ExportToXml(xmlPath); } - // Verify that the XML file was created before attempting to modify it - if (!File.Exists(xmlPath)) - { - Console.WriteLine("Exported XML file not found."); - return; - } - - // Step 2: Load the exported XML and change the bar (foreground) color to green + // -------------------------------------------------------------------- + // 2. Load the exported XML, modify the BarColor element to "Green", and save. + // -------------------------------------------------------------------- XDocument doc = XDocument.Load(xmlPath); + XElement barColorElement = doc.Root + ?.Element("Parameters") + ?.Element("Barcode") + ?.Element("BarColor"); - // Try to locate a element and set its value to green (ARGB hex format) - var barColorElement = doc.Descendants("BarColor").FirstOrDefault(); if (barColorElement != null) { - // Green color in ARGB format (#FF00FF00) - barColorElement.Value = "#FF00FF00"; - } - else - { - // If is not present, look for a ForeColor attribute on any element - var elementWithForeColor = doc.Descendants() - .FirstOrDefault(e => e.Attribute("ForeColor") != null); - if (elementWithForeColor != null) - { - elementWithForeColor.SetAttributeValue("ForeColor", "#FF00FF00"); - } - else - { - Console.WriteLine("No BarColor or ForeColor node found in XML."); - return; - } + // Change the bar color value to green. + barColorElement.Value = "Green"; } - // Save the modified XML back to disk + // Persist the modified XML back to disk. doc.Save(xmlPath); - // Step 3: Import the modified XML to create a new generator and save the updated barcode image - using (var generatorModified = BarcodeGenerator.ImportFromXml(xmlPath)) + // -------------------------------------------------------------------- + // 3. Import the modified configuration and generate the barcode image. + // -------------------------------------------------------------------- + using (var importedGenerator = BarcodeGenerator.ImportFromXml(xmlPath)) { - // The generator automatically applies the color defined in the XML (green) - generatorModified.Save(updatedImagePath); + // Generate a bitmap image using the updated settings. + using (Bitmap bitmap = importedGenerator.GenerateBarCodeImage()) + { + // Save the bitmap as a PNG file. + bitmap.Save(imagePath, ImageFormat.Png); + } } - // Output the locations of the generated files - Console.WriteLine("Original barcode saved to: " + imagePath); - Console.WriteLine("Modified barcode saved to: " + updatedImagePath); + // Output the location of the generated image for verification. + Console.WriteLine("Barcode image generated at: " + imagePath); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/export-barcode-state-to-xml-change-widthreduction-to-10-percent-re-import-and-generate-updated-barcode.cs b/one-dimensional-barcode-types/export-barcode-state-to-xml-change-widthreduction-to-10-percent-re-import-and-generate-updated-barcode.cs index 255680d..28a770c 100644 --- a/one-dimensional-barcode-types/export-barcode-state-to-xml-change-widthreduction-to-10-percent-re-import-and-generate-updated-barcode.cs +++ b/one-dimensional-barcode-types/export-barcode-state-to-xml-change-widthreduction-to-10-percent-re-import-and-generate-updated-barcode.cs @@ -1,8 +1,8 @@ -// Title: Export barcode state to XML, modify WidthReduction, and regenerate barcode -// Description: Demonstrates exporting a barcode generator's configuration to XML, adjusting the BarWidthReduction property, re‑importing the settings, and creating an updated barcode image. -// Category-Description: This example belongs to the Aspose.BarCode configuration management category, illustrating how to persist barcode generation settings using ExportToXml and ImportFromXml. It showcases key API classes such as BarcodeGenerator, EncodeTypes, and the Parameters.Barcode settings, useful for developers who need to store, modify, or version barcode configurations across environments. +// Title: Export Barcode State to XML, Modify Width Reduction, and Regenerate Barcode +// Description: Demonstrates exporting a barcode generator's state to an XML file, adjusting the BarWidthReduction property, and creating an updated barcode image. +// Category-Description: This example belongs to the Aspose.BarCode generation and state management category. It shows how to use BarcodeGenerator to save a barcode image, export its configuration to XML, modify parameters such as BarWidthReduction, re-import the configuration, and generate a new barcode. Developers working with barcode customization, persistence, and batch processing commonly use the BarcodeGenerator, EncodeTypes, and related parameter classes to store and reuse barcode settings. // Prompt: Export barcode state to XML, change WidthReduction to 10 percent, re‑import, and generate updated barcode. -// Tags: barcode, export, import, xml, widthreduction, code128, aspose.barcode, generation +// Tags: barcode, code128, xml, export, import, widthreduction, generation, aspose.barcode using System; using System.IO; @@ -10,54 +10,56 @@ using Aspose.BarCode.Generation; /// -/// Demonstrates exporting a barcode's configuration to XML, modifying the width reduction, -/// re‑importing the configuration, and generating an updated barcode image. +/// Example program that demonstrates exporting a barcode's configuration to XML, +/// modifying the BarWidthReduction setting, and regenerating the barcode image. /// class Program { /// - /// Entry point of the example. Performs the export, modification, import, and save steps. + /// Entry point of the example. Creates an initial barcode, saves its state, + /// updates the width reduction, and saves the updated barcode. /// static void Main() { - // Define temporary XML file path and final image output path - string xmlPath = "barcode.xml"; - string outputPath = "updated.png"; + // Define file paths for the original image, XML state, and updated image. + string originalImagePath = "barcode_original.png"; + string xmlPath = "barcode_state.xml"; + string updatedImagePath = "barcode_updated.png"; - // -------------------------------------------------------------------- - // Create a barcode generator, configure basic properties, and export its state to XML - // -------------------------------------------------------------------- - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // ------------------------------------------------------------ + // Step 1: Generate a barcode, save the image, and export its state to XML. + // ------------------------------------------------------------ + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) { - // Export current generator settings to an XML file + // Save the original barcode image to disk. + generator.Save(originalImagePath); + + // Export the generator's configuration (state) to an XML file. bool exported = generator.ExportToXml(xmlPath); - if (!exported) - { - Console.WriteLine("Failed to export barcode settings to XML."); - return; - } + Console.WriteLine($"Exported to XML: {exported}"); } - // Ensure the XML file was created before attempting to import it + // ------------------------------------------------------------ + // Step 2: Verify the XML file exists before attempting import. + // ------------------------------------------------------------ if (!File.Exists(xmlPath)) { - Console.WriteLine($"XML file not found: {xmlPath}"); + Console.WriteLine("XML file not found. Exiting."); return; } - // -------------------------------------------------------------------- - // Import the barcode settings from the XML file, modify WidthReduction, and save the updated barcode - // -------------------------------------------------------------------- - using (var importedGenerator = BarcodeGenerator.ImportFromXml(xmlPath)) + // ------------------------------------------------------------ + // Step 3: Import the barcode generator from the XML, modify the + // BarWidthReduction property, and save the updated barcode image. + // ------------------------------------------------------------ + using (BarcodeGenerator importedGenerator = BarcodeGenerator.ImportFromXml(xmlPath)) { - // Set BarWidthReduction to 10 percent (value expressed in points as required by the API) + // Set BarWidthReduction to 10 points (approximately 10 percent of the bar width). importedGenerator.Parameters.Barcode.BarWidthReduction.Point = 10f; - // Save the updated barcode image to the specified output path - importedGenerator.Save(outputPath); + // Save the updated barcode image to disk. + importedGenerator.Save(updatedImagePath); + Console.WriteLine($"Updated barcode saved to: {updatedImagePath}"); } - - // Inform the user where the updated barcode image was saved - Console.WriteLine($"Updated barcode saved to: {outputPath}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/export-barcode-state-to-xml-modify-widthreduction-attribute-and-re-import-to-observe-visual-changes.cs b/one-dimensional-barcode-types/export-barcode-state-to-xml-modify-widthreduction-attribute-and-re-import-to-observe-visual-changes.cs index 1be4a8e..e2cda7f 100644 --- a/one-dimensional-barcode-types/export-barcode-state-to-xml-modify-widthreduction-attribute-and-re-import-to-observe-visual-changes.cs +++ b/one-dimensional-barcode-types/export-barcode-state-to-xml-modify-widthreduction-attribute-and-re-import-to-observe-visual-changes.cs @@ -1,20 +1,19 @@ -// Title: Export barcode state to XML, modify WidthReduction, and re-import -// Description: Demonstrates exporting a barcode generator's configuration to XML, adjusting the BarWidthReduction attribute, and re-importing to produce a modified barcode image. -// Category-Description: This example belongs to the Aspose.BarCode configuration management category, illustrating how to persist barcode settings using ExportToXml and ImportFromXml, manipulate XML directly, and regenerate barcodes. Developers working with barcode generation often need to store, edit, or version‑control settings; key classes include BarcodeGenerator, BarcodeParameters, and XML handling via System.Xml.Linq. +// Title: Export barcode state to XML, modify BarWidthReduction, and re‑import +// Description: Demonstrates how to export a barcode generator's configuration to XML, edit the BarWidthReduction attribute, and reload the settings to produce a modified barcode image. +// Category-Description: This example belongs to the Aspose.BarCode configuration management category, illustrating the use of BarcodeGenerator.ExportToXml and BarcodeGenerator.ImportFromXml. Developers often need to persist barcode settings, adjust parameters programmatically via XML, and regenerate barcodes without recreating the generator from scratch. Typical use cases include batch processing, dynamic styling, and integration with external configuration systems. // Prompt: Export barcode state to XML, modify WidthReduction attribute, and re‑import to observe visual changes. -// Tags: barcode, xml, widthreduction, export, import, aspose.barcode, code128, image +// Tags: barcode, widthreduction, xml, export, import, aspose.barcode, code128, png using System; using System.IO; -using System.Linq; using System.Xml.Linq; using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Example program that shows how to export a barcode's configuration to XML, -/// modify the BarWidthReduction attribute, and re‑import the settings -/// to generate a visually altered barcode image. +/// Example program that shows how to export a barcode generator's state to XML, +/// modify the BarWidthReduction attribute, and re‑import the XML to generate a +/// barcode with updated visual properties. /// class Program { @@ -24,85 +23,69 @@ class Program /// static void Main() { - // Define file names for the XML configuration and output images. - const string xmlPath = "barcode.xml"; - const string originalImagePath = "original.png"; - const string modifiedImagePath = "modified.png"; + // Define file paths for the original image, modified image, and XML state file. + string outputDir = Directory.GetCurrentDirectory(); + string originalImagePath = Path.Combine(outputDir, "barcode_original.png"); + string modifiedImagePath = Path.Combine(outputDir, "barcode_modified.png"); + string xmlPath = Path.Combine(outputDir, "barcode_state.xml"); - // ------------------------------------------------------------ - // Step 1: Create a barcode generator, configure it, export to XML, - // and save the original image. - // ------------------------------------------------------------ - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789")) + // Step 1: Create a barcode generator, configure it, and save the original image. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - // Set an initial BarWidthReduction (default is 0). + // Set an initial BarWidthReduction (default is 0 points). generator.Parameters.Barcode.BarWidthReduction.Point = 0f; - // Export the current barcode settings to an XML file. - bool exportSuccess = generator.ExportToXml(xmlPath); - if (!exportSuccess) - { - Console.WriteLine("Failed to export barcode settings to XML."); - return; - } + // Save the barcode as a PNG file. + generator.Save(originalImagePath, BarCodeImageFormat.Png); - // Save the barcode image generated with the original settings. - generator.Save(originalImagePath); + // Export the generator's configuration to an XML file. + bool exportSuccess = generator.ExportToXml(xmlPath); + Console.WriteLine($"Export to XML {(exportSuccess ? "succeeded" : "failed")} at: {xmlPath}"); } - // ------------------------------------------------------------ - // Step 2: Load the exported XML, modify BarWidthReduction, and save it. - // ------------------------------------------------------------ - if (!File.Exists(xmlPath)) + // Step 2: Load the exported XML, locate the BarWidthReduction element, and modify its value. + if (File.Exists(xmlPath)) { - Console.WriteLine($"XML file not found: {xmlPath}"); - return; - } + XDocument doc = XDocument.Load(xmlPath); - XDocument doc = XDocument.Load(xmlPath); + // Find the element representing BarWidthReduction (case‑insensitive search). + var reductionElement = doc.Descendants() + .FirstOrDefault(e => string.Equals(e.Name.LocalName, "BarWidthReduction", StringComparison.OrdinalIgnoreCase)); - // Locate the BarWidthReduction element (it may be an element or attribute). - XElement reductionElement = doc.Root?.Descendants("BarWidthReduction").FirstOrDefault(); - if (reductionElement != null) - { - // Update the reduction value (e.g., 0.5 points). - reductionElement.Value = "0.5"; + if (reductionElement != null) + { + // Update the reduction value to 0.5 points. + reductionElement.Value = "0.5"; + doc.Save(xmlPath); + Console.WriteLine("Modified BarWidthReduction to 0.5 in XML."); + } + else + { + Console.WriteLine("BarWidthReduction element not found in XML; cannot modify."); + } } else { - // If the element does not exist, create it under the root element. - XElement root = doc.Root; - if (root != null) - { - root.Add(new XElement("BarWidthReduction", "0.5")); - } + Console.WriteLine("XML file not found; aborting modification step."); + return; } - // Persist the modified XML back to disk. - doc.Save(xmlPath); - - // ------------------------------------------------------------ - // Step 3: Import the modified XML into a new generator and save the updated image. - // ------------------------------------------------------------ - using (var modifiedGenerator = BarcodeGenerator.ImportFromXml(xmlPath)) + // Step 3: Import the modified XML to create a new barcode generator instance. + BarcodeGenerator modifiedGenerator = BarcodeGenerator.ImportFromXml(xmlPath); + if (modifiedGenerator == null) { - if (modifiedGenerator == null) - { - Console.WriteLine("Failed to import barcode settings from XML."); - return; - } - - // Ensure the BarWidthReduction reflects the modified value. - // (Import should apply it, but we set it explicitly for safety.) - modifiedGenerator.Parameters.Barcode.BarWidthReduction.Point = 0.5f; + Console.WriteLine("Failed to import generator from modified XML."); + return; + } - // Save the barcode image generated with the modified settings. - modifiedGenerator.Save(modifiedImagePath); + // Save the barcode image generated with the modified settings. + using (modifiedGenerator) + { + modifiedGenerator.Save(modifiedImagePath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved modified barcode image to: {modifiedImagePath}"); } - // Indicate successful completion and provide file locations. - Console.WriteLine("Barcode generation completed."); - Console.WriteLine($"Original image: {originalImagePath}"); - Console.WriteLine($"Modified image: {modifiedImagePath}"); + // Indicate that the process has completed. + Console.WriteLine("Process completed. Compare the original and modified barcode images."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/export-barcode-xml-edit-ydimension-attribute-re-import-and-observe-vertical-size-adjustment.cs b/one-dimensional-barcode-types/export-barcode-xml-edit-ydimension-attribute-re-import-and-observe-vertical-size-adjustment.cs index d1156b1..fc35d65 100644 --- a/one-dimensional-barcode-types/export-barcode-xml-edit-ydimension-attribute-re-import-and-observe-vertical-size-adjustment.cs +++ b/one-dimensional-barcode-types/export-barcode-xml-edit-ydimension-attribute-re-import-and-observe-vertical-size-adjustment.cs @@ -1,80 +1,102 @@ -// Title: Export barcode to XML, edit YDimension, re-import and compare images -// Description: Demonstrates exporting barcode generator settings to XML, modifying the YDimension attribute to change bar height, and re-importing to generate an updated barcode image. -// Category-Description: This example belongs to the Aspose.BarCode generation and configuration category, showcasing how to persist generator parameters via XML, edit them manually, and reload them. It highlights key classes such as BarcodeGenerator, EncodeTypes, and AutoSizeMode, useful for developers needing to programmatically adjust barcode dimensions or store settings for later reuse. +// Title: Export barcode to XML, modify YDimension, re‑import and compare size +// Description: Shows how to export a barcode's settings to XML, edit the YDimension (BarHeight) attribute, re‑import the modified XML, and observe the resulting change in the barcode's vertical size. +// Category-Description: This example belongs to the Aspose.BarCode generation and serialization category. It demonstrates using BarcodeGenerator to create a barcode, exporting its configuration with ExportToXml, editing the XML manually, and re‑creating a generator via ImportFromXml. Typical use cases include persisting barcode settings, batch editing, or integrating with external configuration systems. Developers often work with BarcodeGenerator, BarCodeImageFormat, and XML manipulation classes for such scenarios. // Prompt: Export barcode XML, edit YDimension attribute, re‑import, and observe vertical size adjustment. -// Tags: barcode, xml, ydimension, generation, autosizemode, aspose.barcode, code128 +// Tags: barcode, xml, export, import, ydimension, barheight, aspose.barcode, image, generation using System; using System.IO; using System.Xml.Linq; +using System.Linq; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Demonstrates exporting a barcode's configuration to XML, editing the YDimension attribute, -/// re-importing the configuration, and observing the effect on the barcode's vertical size. +/// Demonstrates exporting a barcode to XML, modifying the YDimension (BarHeight) attribute, +/// re‑importing the XML, and observing the effect on the barcode's vertical size. /// class Program { /// - /// Entry point of the example. Generates a Code128 barcode, saves it, modifies its YDimension via XML, - /// and saves the updated barcode image. + /// Entry point that performs the export‑modify‑import workflow and prints image heights. /// static void Main() { - // Define file paths for temporary XML and PNG images - string xmlPath = "barcode.xml"; - string beforeImage = "barcode_before.png"; - string afterImage = "barcode_after.png"; + // Paths for temporary files + string originalXml = "barcode_original.xml"; + string modifiedXml = "barcode_modified.xml"; + string originalImg = "barcode_original.png"; + string modifiedImg = "barcode_modified.png"; - // Create a barcode generator for Code128 with sample text - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // 1. Create a barcode generator and set a vertical size (BarHeight) + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - // Disable automatic sizing so that YDimension influences bar height - generator.Parameters.AutoSizeMode = AutoSizeMode.None; + // Set bar height (vertical size) – this will be reflected in the exported XML + generator.Parameters.Barcode.BarHeight.Point = 50f; // 50 points height - // Save the initial barcode image (before modification) - generator.Save(beforeImage); + // Export generator settings to XML + generator.ExportToXml(originalXml); - // Export the generator's settings to an XML file - generator.ExportToXml(xmlPath); + // Save the original barcode image for comparison + generator.Save(originalImg, BarCodeImageFormat.Png); } - // Ensure the XML file was successfully created - if (!File.Exists(xmlPath)) + // 2. Load the exported XML, modify the YDimension attribute (simulated by BarHeight) + if (!File.Exists(originalXml)) { - Console.WriteLine($"Failed to create XML file at '{xmlPath}'."); + Console.WriteLine("Exported XML not found."); return; } - // Load the XML, modify the YDimension attribute, and write the changes back - XDocument doc = XDocument.Load(xmlPath); - XElement root = doc.Root; - if (root != null) + XDocument doc = XDocument.Load(originalXml); + // The XML structure contains a BarHeight element; we treat it as YDimension for this demo + XElement barHeightElement = doc.Root?.Descendants("BarHeight").FirstOrDefault(); + if (barHeightElement != null) { - // Increase YDimension (e.g., to 10 points) to make bars taller - root.SetAttributeValue("YDimension", "10"); - doc.Save(xmlPath); + // Change the value to a larger height (e.g., 80 points) + barHeightElement.Value = "80"; } else { - Console.WriteLine("Invalid XML structure: missing root element."); + // If not present, add it under the Barcode element + XElement barcodeElem = doc.Root?.Descendants("Barcode").FirstOrDefault(); + if (barcodeElem != null) + { + barcodeElem.Add(new XElement("BarHeight", "80")); + } + } + + // Save the modified XML + doc.Save(modifiedXml); + + // 3. Re‑import the barcode from the modified XML + if (!File.Exists(modifiedXml)) + { + Console.WriteLine("Modified XML not found."); return; } - // Import the modified XML into a new generator instance - using (var modifiedGenerator = BarcodeGenerator.ImportFromXml(xmlPath)) + using (var modifiedGenerator = BarcodeGenerator.ImportFromXml(modifiedXml)) { - // Preserve the same AutoSizeMode setting as the original generator - modifiedGenerator.Parameters.AutoSizeMode = AutoSizeMode.None; + // Save the barcode generated from the modified settings + modifiedGenerator.Save(modifiedImg, BarCodeImageFormat.Png); - // Save the barcode image after the YDimension change - modifiedGenerator.Save(afterImage); + // 4. Observe vertical size adjustment by checking image height + using (Bitmap bmp = modifiedGenerator.GenerateBarCodeImage()) + { + Console.WriteLine($"Modified barcode image height (pixels): {bmp.Height}"); + } } - // Output the locations of the generated files - Console.WriteLine($"Barcode before modification saved to: {beforeImage}"); - Console.WriteLine($"Barcode after modification saved to: {afterImage}"); - Console.WriteLine($"XML with edited YDimension saved to: {xmlPath}"); + // 5. Also display original image height for comparison + using (var originalGenerator = BarcodeGenerator.ImportFromXml(originalXml)) + { + using (Bitmap bmp = originalGenerator.GenerateBarCodeImage()) + { + Console.WriteLine($"Original barcode image height (pixels): {bmp.Height}"); + } + } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/export-barcode-xml-modify-codabarstopsymbol-to-b-re-import-and-generate-barcode-with-new-stop-character.cs b/one-dimensional-barcode-types/export-barcode-xml-modify-codabarstopsymbol-to-b-re-import-and-generate-barcode-with-new-stop-character.cs index 3a00ad6..7bde442 100644 --- a/one-dimensional-barcode-types/export-barcode-xml-modify-codabarstopsymbol-to-b-re-import-and-generate-barcode-with-new-stop-character.cs +++ b/one-dimensional-barcode-types/export-barcode-xml-modify-codabarstopsymbol-to-b-re-import-and-generate-barcode-with-new-stop-character.cs @@ -1,75 +1,76 @@ -// Title: Export, modify, and re-import Codabar barcode settings via XML -// Description: Demonstrates exporting a Codabar barcode generator's settings to XML, editing the stop symbol, re-importing the modified settings, and generating a new barcode image. -// Category-Description: This example belongs to the Aspose.BarCode settings management category, showcasing how to use BarcodeGenerator.ExportToXml and BarcodeGenerator.ImportFromXml. Typical use cases include persisting barcode configurations, batch editing via XML, and regenerating barcodes with altered parameters. Developers often need to programmatically adjust symbology options such as stop symbols, and this snippet illustrates that workflow. +// Title: Export Codabar barcode settings to XML, modify stop symbol, re-import and generate image +// Description: Demonstrates exporting a Codabar barcode generator's configuration to XML, editing the CodabarStopSymbol to 'B', importing the modified XML, and creating a barcode image with the new stop character. +// Category-Description: This example belongs to the Aspose.BarCode configuration management category. It shows how to use BarcodeGenerator.ExportToXml and BarcodeGenerator.ImportFromXml to persist and modify barcode settings. Typical use cases include batch updating barcode parameters, customizing symbology options, and integrating external configuration files. Developers often need to adjust properties like stop symbols, checksum settings, or visual styles without recompiling code. // Prompt: Export barcode XML, modify CodabarStopSymbol to B, re‑import, and generate barcode with new stop character. -// Tags: codabar, barcode, xml, export, import, modification, generation, aspose.barcode +// Tags: codabar, stop-symbol, xml, export, import, barcode-generation, aspose.barcode, configuration using System; using System.IO; -using System.Linq; using System.Xml.Linq; +using System.Linq; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// /// Example program that exports a Codabar barcode configuration to XML, -/// modifies the stop symbol, re-imports the configuration, and generates a new barcode image. +/// modifies the stop symbol, re-imports the configuration, and generates a barcode image. /// class Program { /// - /// Entry point of the example. Executes the export‑modify‑import workflow and saves the resulting barcode image. + /// Entry point of the example. Performs export, modification, import, and image generation steps. /// static void Main() { - // Define file paths relative to the current working directory. - string xmlPath = "codabar_original.xml"; - string modifiedXmlPath = "codabar_modified.xml"; - string outputImagePath = "codabar_modified.png"; + // Define file paths for the intermediate XML and final PNG image + string xmlPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode.xml"); + string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode_modified.png"); - // 1. Create a Codabar barcode generator with an initial code text and export its settings to XML. - using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, "A123456A")) + // Step 1: Create a Codabar barcode generator with default settings and export its configuration to XML + using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, "123456")) { - // Export the generator's configuration (including symbology options) to an XML file. generator.ExportToXml(xmlPath); } - // 2. Load the exported XML, locate the CodabarStopSymbol element, change its value to 'B', and save the modified XML. - if (!File.Exists(xmlPath)) + // Step 2: Load the exported XML, locate the CodabarStopSymbol element, change its value to "B", and save the XML + if (File.Exists(xmlPath)) { - Console.WriteLine($"Error: XML file '{xmlPath}' not found."); - return; - } + XDocument doc = XDocument.Load(xmlPath); - XDocument doc = XDocument.Load(xmlPath); - // Find the element that defines the stop symbol (case‑sensitive). - XElement stopSymbolElement = doc.Root?.Descendants("CodabarStopSymbol").FirstOrDefault(); - if (stopSymbolElement == null) - { - Console.WriteLine("Error: CodabarStopSymbol element not found in XML."); - return; - } + // Perform a case‑insensitive search for the element named "CodabarStopSymbol" + var stopSymbolElement = doc.Descendants() + .FirstOrDefault(e => string.Equals(e.Name.LocalName, "CodabarStopSymbol", StringComparison.OrdinalIgnoreCase)); - // Update the stop symbol value. - stopSymbolElement.Value = "B"; - doc.Save(modifiedXmlPath); - - // 3. Import the modified XML back into a BarcodeGenerator, adjust the code text, and generate the barcode image. - if (!File.Exists(modifiedXmlPath)) + if (stopSymbolElement != null) + { + // Update the element's value to the enum name representing stop symbol B + stopSymbolElement.Value = "B"; + doc.Save(xmlPath); + } + else + { + Console.WriteLine("CodabarStopSymbol element not found in XML."); + return; + } + } + else { - Console.WriteLine($"Error: Modified XML file '{modifiedXmlPath}' not found."); + Console.WriteLine("Exported XML file not found."); return; } - using (var modifiedGenerator = BarcodeGenerator.ImportFromXml(modifiedXmlPath)) + // Step 3: Import the modified XML back into a new generator instance and generate the barcode image + using (var importedGenerator = BarcodeGenerator.ImportFromXml(xmlPath)) { - // Set the code text to use the new stop symbol. - modifiedGenerator.CodeText = "B123456B"; + // Optional verification of the imported stop symbol + var stopSymbol = importedGenerator.Parameters.Barcode.Codabar.StopSymbol; + Console.WriteLine($"Imported Stop Symbol: {stopSymbol}"); - // Save the resulting barcode image to the specified file. - modifiedGenerator.Save(outputImagePath); + // Save the generated barcode image with the updated stop symbol + importedGenerator.Save(outputPath); } - Console.WriteLine($"Barcode image generated: {outputImagePath}"); + Console.WriteLine($"Barcode image saved to: {outputPath}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/export-barcode-xml-state-edit-ydimension-re-render-to-observe-size-change.cs b/one-dimensional-barcode-types/export-barcode-xml-state-edit-ydimension-re-render-to-observe-size-change.cs index 9293ef5..4532fa5 100644 --- a/one-dimensional-barcode-types/export-barcode-xml-state-edit-ydimension-re-render-to-observe-size-change.cs +++ b/one-dimensional-barcode-types/export-barcode-xml-state-edit-ydimension-re-render-to-observe-size-change.cs @@ -1,74 +1,61 @@ -// Title: Export barcode XML state, edit YDimension, and re‑render -// Description: Demonstrates exporting a barcode's configuration to XML, modifying the YDimension property, and generating a new image to see the size change. -// Category-Description: This example belongs to the Aspose.BarCode generation and manipulation category, showcasing how to persist barcode settings via XML, adjust dimensional properties, and re‑create images. It uses BarcodeGenerator, its Parameters, and ImportFromXml methods—common tasks for developers needing dynamic barcode customization and state persistence. +// Title: Export barcode XML state, modify YDimension, and re-render +// Description: Demonstrates how to export a BarcodeGenerator's configuration to XML, change the bar height (Y dimension), and generate new images to observe size differences. +// Category-Description: This example belongs to the Aspose.BarCode generation and configuration category, showcasing the use of BarcodeGenerator, ExportToXml, ImportFromXml, and bar dimension properties. Typical use cases include persisting barcode settings, batch editing, and dynamic resizing for different output requirements. Developers often need to serialize settings, adjust parameters like YDimension, and regenerate barcodes without recreating the generator from scratch. // Prompt: Export barcode XML state, edit YDimension, re‑render to observe size change. -// Tags: code128, export, edit, render, png, xml, barcodegenerator, parameters +// Tags: barcode, code128, export, xml, ydimension, barheight, aspose.barcode, generation, image, png, serialization using System; using System.IO; using Aspose.BarCode.Generation; -using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Demonstrates exporting a barcode's state to XML, modifying its YDimension, and re‑rendering the image. +/// Demonstrates exporting a barcode generator's state to XML, modifying the Y dimension, and re‑rendering the barcode. /// class Program { /// - /// Entry point of the example. Generates an initial barcode, saves its XML state, modifies YDimension, and saves the updated barcode image. + /// Entry point. Generates a barcode, saves its original image, exports its configuration to XML, + /// imports it, changes the bar height, and saves the modified image. /// static void Main() { - // Define file paths for the initial image, XML state, and the modified image. - string initialImagePath = "barcode_initial.png"; - string xmlPath = "barcode_state.xml"; - string modifiedImagePath = "barcode_modified.png"; - - // 1. Create a barcode generator for Code128 and save the initial image. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) - { - // Set a small size for visibility. - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - generator.Parameters.ImageWidth.Point = 200f; - generator.Parameters.ImageHeight.Point = 80f; - - // Save the generated barcode image. - generator.Save(initialImagePath); - - // Export the current generator state to an XML file. - generator.ExportToXml(xmlPath); - } - - // 2. Verify that the XML file was created before attempting to import. - if (!File.Exists(xmlPath)) + // Create initial barcode generator with a sample code text. + using (BarcodeGenerator generator1 = new BarcodeGenerator(EncodeTypes.Code128, "123456")) { - Console.WriteLine($"XML file not found: {xmlPath}"); - return; - } + // Set initial bar height (Y dimension) to 30 points. + generator1.Parameters.Barcode.BarHeight.Point = 30f; - // 3. Load the barcode generator from the exported XML. - using (var generatorFromXml = BarcodeGenerator.ImportFromXml(xmlPath)) - { - // Attempt to modify the YDimension property if it exists for the barcode type. - var barcodeParams = generatorFromXml.Parameters.Barcode; - var yDimProp = barcodeParams.GetType().GetProperty("YDimension"); - if (yDimProp != null) - { - // YDimension is a Unit; increase its value to 5 points. - var unit = (Unit) yDimProp.GetValue(barcodeParams); - unit.Point = 5f; - Console.WriteLine("YDimension modified to 5 points."); - } - else + // Export the generator's state to XML in a memory stream. + using (MemoryStream xmlStream = new MemoryStream()) { - Console.WriteLine("YDimension property not available for this barcode type."); + generator1.ExportToXml(xmlStream); + xmlStream.Position = 0; // Reset for reading. + + // Render the original barcode and output its size. + using (Aspose.Drawing.Bitmap originalImage = generator1.GenerateBarCodeImage()) + { + Console.WriteLine($"Original image size: {originalImage.Width}x{originalImage.Height} pixels"); + generator1.Save("barcode_original.png", BarCodeImageFormat.Png); + } + + // Import the XML into a new generator instance. + BarcodeGenerator generator2 = BarcodeGenerator.ImportFromXml(xmlStream); + + // Modify the Y dimension (bar height) to a larger value. + generator2.Parameters.Barcode.BarHeight.Point = 80f; + + // Render the modified barcode and output its new size. + using (Aspose.Drawing.Bitmap modifiedImage = generator2.GenerateBarCodeImage()) + { + Console.WriteLine($"Modified image size: {modifiedImage.Width}x{modifiedImage.Height} pixels"); + generator2.Save("barcode_modified.png", BarCodeImageFormat.Png); + } + + // Dispose the imported generator explicitly. + generator2.Dispose(); } - - // 4. Save the modified barcode image to observe the size change. - generatorFromXml.Save(modifiedImagePath); } - - Console.WriteLine("Processing completed."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/export-current-barcode-configuration-to-xml-file-then-import-it-in-another-application.cs b/one-dimensional-barcode-types/export-current-barcode-configuration-to-xml-file-then-import-it-in-another-application.cs index 164cf26..110d6e6 100644 --- a/one-dimensional-barcode-types/export-current-barcode-configuration-to-xml-file-then-import-it-in-another-application.cs +++ b/one-dimensional-barcode-types/export-current-barcode-configuration-to-xml-file-then-import-it-in-another-application.cs @@ -1,61 +1,47 @@ -// Title: Export barcode configuration to XML and reuse it -// Description: Demonstrates exporting the current barcode generator settings to an XML file and then importing those settings in another application to create a barcode image. -// Category-Description: This example belongs to the Aspose.BarCode configuration management category, showcasing how to persist and reuse barcode generation settings via XML. It highlights the use of BarcodeGenerator, ExportToXml, and ImportFromXml APIs, which are essential for developers needing consistent barcode appearance across multiple applications or sessions. Typical use cases include configuration sharing, version control of barcode settings, and automated deployment pipelines. +// Title: Export and Import Barcode Configuration via XML +// Description: Demonstrates exporting a configured barcode generator to an XML file and importing it later to recreate the same barcode. +// Category-Description: Shows how to use Aspose.BarCode's configuration export/import APIs. This example belongs to the configuration management category, illustrating the use of BarcodeGenerator.ExportToXml and BarcodeGenerator.ImportFromXml to persist and reuse barcode settings across applications. Developers often need to share barcode configurations, automate deployment, or maintain consistency, and these APIs provide a straightforward XML-based approach. // Prompt: Export current barcode configuration to an XML file, then import it in another application. -// Tags: barcode symbology, export, import, xml, configuration, generation, aspose.barcode +// Tags: barcode, export, import, xml, configuration, aspose.barcode, code128, image, generation using System; -using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Demonstrates exporting a barcode generator's configuration to an XML file -/// and importing that configuration to generate a barcode image in a separate step. +/// Example program that exports a barcode generator's configuration to XML, +/// then imports the configuration to generate the same barcode in a new context. /// class Program { /// - /// Entry point of the example. Exports barcode settings to XML, then imports them to create an image. + /// Entry point of the example. Creates a barcode, exports its settings, + /// and demonstrates importing those settings to generate an identical barcode. /// static void Main() { - // Define file paths for the XML configuration and the resulting barcode image. - string xmlPath = "barcodeConfig.xml"; - string imagePath = "barcode.png"; - - // -------------------------------------------------------------------- - // Create a barcode generator, configure it, and export its settings. - // -------------------------------------------------------------------- + // ------------------- Create and configure a barcode ------------------- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) { - // Optional: customize a visual property (e.g., barcode color). - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue; + // Set human‑readable text styling (font family and size) + generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Arial"; + generator.Parameters.Barcode.CodeTextParameters.Font.Size.Pixels = 14f; - // Export the current configuration to an XML file. + // Export the current configuration to an XML file + string xmlPath = "barcodeConfig.xml"; bool exportSuccess = generator.ExportToXml(xmlPath); - Console.WriteLine(exportSuccess - ? $"Configuration exported to '{xmlPath}'." - : $"Failed to export configuration to '{xmlPath}'."); - } + Console.WriteLine($"Export succeeded: {exportSuccess}"); - // --------------------------------------------------------------- - // Verify that the XML file was created before attempting import. - // --------------------------------------------------------------- - if (!File.Exists(xmlPath)) - { - Console.WriteLine($"XML file '{xmlPath}' does not exist. Exiting."); - return; + // Optionally save the barcode image generated with the current settings + generator.Save("barcode.png"); } - // --------------------------------------------------------------- - // Import the barcode configuration from the XML file and save image. - // --------------------------------------------------------------- - using (var importedGenerator = BarcodeGenerator.ImportFromXml(xmlPath)) + // ------------------- Import configuration in another context ------------------- + string importXmlPath = "barcodeConfig.xml"; + using (var importedGenerator = BarcodeGenerator.ImportFromXml(importXmlPath)) { - // Generate and save the barcode image using the imported settings. - importedGenerator.Save(imagePath); - Console.WriteLine($"Barcode image saved to '{imagePath}'."); + // Generate and save the barcode using the imported settings + importedGenerator.Save("importedBarcode.png", BarCodeImageFormat.Png); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-50-codabar-barcodes-from-csv-file-saving-each-as-individual-png-image.cs b/one-dimensional-barcode-types/generate-50-codabar-barcodes-from-csv-file-saving-each-as-individual-png-image.cs index d949b21..f29de6a 100644 --- a/one-dimensional-barcode-types/generate-50-codabar-barcodes-from-csv-file-saving-each-as-individual-png-image.cs +++ b/one-dimensional-barcode-types/generate-50-codabar-barcodes-from-csv-file-saving-each-as-individual-png-image.cs @@ -1,62 +1,71 @@ -// Title: Generate Codabar Barcodes from CSV -// Description: Creates up to 50 Codabar barcodes from a CSV file, each saved as an individual PNG image. -// Category-Description: This example belongs to the Aspose.BarCode generation category, demonstrating how to read data from a CSV source and produce barcode images using the BarcodeGenerator class. Typical use cases include batch creation of product labels, inventory tags, or any scenario where multiple barcodes must be generated programmatically. Developers often need to iterate over input records, configure the desired symbology, and export images in common formats such as PNG. +// Title: Generate 50 Codabar barcodes from CSV and save each as PNG +// Description: This example reads up to 50 Codabar values from a CSV file (creating a sample file if missing) and generates individual PNG images for each barcode. +// Category-Description: Demonstrates Aspose.BarCode barcode generation using the BarcodeGenerator class with EncodeTypes.Codabar. Typical scenarios include batch creation of barcode images from data sources such as CSV files for inventory, shipping, or point‑of‑sale systems. Developers often need to configure start/stop symbols, choose image formats, and handle file I/O efficiently. // Prompt: Generate 50 Codabar barcodes from a CSV file, saving each as an individual PNG image. -// Tags: codabar, barcode generation, png, csv, batch, aspose.barcode +// Tags: codabar, barcode, generation, png, csv, aspose.barcode, encode-types, image-output using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -namespace BarcodeBatchGenerator +/// +/// Demonstrates generating Codabar barcodes from a CSV file and saving each as a PNG image. +/// +class Program { /// - /// Demonstrates batch generation of Codabar barcodes from a CSV file using Aspose.BarCode. + /// Entry point that reads barcode data, creates Codabar barcodes, and writes PNG files. /// - class Program + static void Main() { - /// - /// Entry point of the application. Reads up to 50 lines from a CSV file and creates a PNG barcode for each non‑empty entry. - /// - /// Optional command‑line argument specifying the path to the CSV file. - static void Main(string[] args) - { - // Determine CSV file path (first argument or default "input.csv") - string csvPath = args.Length > 0 ? args[0] : "input.csv"; + // Path to the CSV file containing Codabar values (one per line). + string csvPath = "codes.csv"; - // Verify that the CSV file exists before proceeding - if (!File.Exists(csvPath)) + // If the CSV does not exist, create a sample file with 50 Codabar values. + if (!File.Exists(csvPath)) + { + using (StreamWriter writer = new StreamWriter(csvPath)) { - Console.WriteLine($"CSV file not found: {csvPath}"); - return; + for (int i = 1; i <= 50; i++) + { + // Codabar requires start/stop symbols (A, B, C, D). Use 'A' for both. + string code = $"A{i:D5}A"; + writer.WriteLine(code); + } } + } + + // Read all lines from the CSV file. + string[] lines = File.ReadAllLines(csvPath); - // Read all lines from the CSV file into an array - string[] lines = File.ReadAllLines(csvPath); + // Process up to 50 entries (or fewer if the file has less). + int count = Math.Min(50, lines.Length); + for (int i = 0; i < count; i++) + { + string codeText = lines[i].Trim(); - // Process a maximum of 50 entries to avoid excessive output - int maxCount = Math.Min(50, lines.Length); - for (int i = 0; i < maxCount; i++) + // Skip empty lines and report them. + if (string.IsNullOrEmpty(codeText)) { - // Trim whitespace from the current line to obtain the barcode text - string codeText = lines[i].Trim(); + Console.WriteLine($"Line {i + 1} is empty. Skipping."); + continue; + } - // Skip empty lines to prevent generating blank barcodes - if (string.IsNullOrEmpty(codeText)) - { - continue; - } + // Create a Codabar barcode generator with the specified code text. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Codabar, codeText)) + { + // Optional: set start/stop symbols explicitly (default is 'A'). + generator.Parameters.Barcode.Codabar.StartSymbol = CodabarSymbol.A; + generator.Parameters.Barcode.Codabar.StopSymbol = CodabarSymbol.A; - // Build output file name (e.g., barcode_1.png) using a 1‑based index + // Save each barcode as an individual PNG file. string outputFile = $"barcode_{i + 1}.png"; - - // Create a barcode generator for Codabar symbology and save the image as PNG - using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, codeText)) - { - generator.Save(outputFile, BarCodeImageFormat.Png); - } + generator.Save(outputFile, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode {i + 1} to '{outputFile}'."); } } + + Console.WriteLine("Barcode generation completed."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-barcode-apply-custom-foreground-color-ff00ff-export-to-png-and-verify-color-accuracy-with-image-analysis.cs b/one-dimensional-barcode-types/generate-barcode-apply-custom-foreground-color-ff00ff-export-to-png-and-verify-color-accuracy-with-image-analysis.cs index 57e4163..a850a4d 100644 --- a/one-dimensional-barcode-types/generate-barcode-apply-custom-foreground-color-ff00ff-export-to-png-and-verify-color-accuracy-with-image-analysis.cs +++ b/one-dimensional-barcode-types/generate-barcode-apply-custom-foreground-color-ff00ff-export-to-png-and-verify-color-accuracy-with-image-analysis.cs @@ -1,69 +1,75 @@ -// Title: Generate Code128 barcode with custom magenta foreground and verify color -// Description: Creates a Code128 barcode, applies a custom magenta foreground color, saves it as PNG, and checks the pixel color to confirm accuracy. -// Category-Description: This example demonstrates Aspose.BarCode generation with color customization and basic image analysis. It uses BarcodeGenerator, EncodeTypes, BarCodeImageFormat, and Aspose.Drawing's Bitmap/Color classes to produce a branded barcode, a common requirement for marketing materials and inventory systems. Developers often need to apply corporate colors to barcodes and verify the output programmatically. +// Title: Generate Code128 barcode with custom magenta foreground and verify color in PNG +// Description: Demonstrates creating a Code128 barcode, applying a custom foreground color #FF00FF, exporting it to a PNG file, and confirming the color via simple image analysis. +// Category-Description: This example belongs to the Aspose.BarCode generation and rendering category, showcasing how to customize barcode appearance using the BarcodeGenerator class, set visual properties like BarColor, export to common image formats via BarCodeImageFormat, and perform basic validation with Aspose.Drawing. Developers often need to tailor barcode colors for branding or UI integration and verify output correctness in automated pipelines. // Prompt: Generate a barcode, apply custom foreground color #FF00FF, export to PNG, and verify color accuracy with image analysis. -// Tags: code128, barcode generation, color customization, png, image verification, aspose.barcode, aspose.drawing +// Tags: code128, barcode, color, png, generation, verification, aspose.barcode, aspose.drawing using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Demonstrates how to generate a Code128 barcode with a custom magenta foreground, -/// save it as a PNG file, and verify the color using simple image analysis. +/// Example program that generates a Code128 barcode with a custom magenta foreground, +/// saves it as a PNG image, and verifies that the expected color is present in the output. /// class Program { /// - /// Entry point of the example. Executes barcode creation, saving, and color verification. + /// Entry point of the example. Performs barcode creation, saving, and color verification. /// static void Main() { - // Define the full path for the output PNG file. - string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode.png"); + // Define the output file path for the generated PNG image. + string outputPath = "barcode.png"; - // Initialize the barcode generator for Code128 symbology. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) + // Create a barcode generator for Code128 with the sample text "Test123". + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123")) { - // Set the data to encode. - generator.CodeText = "Test123"; - - // Apply a custom foreground color (magenta #FF00FF). + // Apply a custom foreground color #FF00FF (magenta) to the barcode bars. generator.Parameters.Barcode.BarColor = Color.FromArgb(255, 0, 255); - // Save the generated barcode as a PNG image. + // Save the generated barcode as a PNG file. generator.Save(outputPath, BarCodeImageFormat.Png); } - // Ensure the image file was created successfully. + // Ensure the image file was created before attempting verification. if (!File.Exists(outputPath)) { Console.WriteLine("Failed to create barcode image."); return; } - // Load the saved PNG for pixel-level inspection. - using (var bitmap = new Bitmap(outputPath)) + // Load the saved PNG image for pixel-level analysis. + using (var image = Image.FromFile(outputPath)) + using (var bitmap = (Bitmap)image) { - // Choose a pixel near the image center, where barcode bars are expected. - int x = bitmap.Width / 2; - int y = bitmap.Height / 2; - Color pixelColor = bitmap.GetPixel(x, y); - - // Define the expected magenta color. + // Define the expected foreground color to look for. Color expectedColor = Color.FromArgb(255, 0, 255); + bool colorFound = false; - // Compare the actual pixel color with the expected color. - if (pixelColor.ToArgb() == expectedColor.ToArgb()) - { - Console.WriteLine("Foreground color verification succeeded."); - } - else + // Scan only a small region (up to 20x20 pixels) to keep processing fast. + int maxX = Math.Min(bitmap.Width, 20); + int maxY = Math.Min(bitmap.Height, 20); + + for (int y = 0; y < maxY && !colorFound; y++) { - Console.WriteLine($"Foreground color verification failed. Expected ARGB: {expectedColor.ToArgb()}, Actual ARGB: {pixelColor.ToArgb()}"); + for (int x = 0; x < maxX && !colorFound; x++) + { + // Compare the pixel's ARGB value with the expected color. + if (bitmap.GetPixel(x, y).ToArgb() == expectedColor.ToArgb()) + { + colorFound = true; + } + } } + + // Output the verification result. + Console.WriteLine(colorFound + ? "Color verification passed: foreground color matches #FF00FF." + : "Color verification failed: foreground color not found."); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-barcode-disable-showcodetext-and-confirm-output-contains-only-barcode-pattern.cs b/one-dimensional-barcode-types/generate-barcode-disable-showcodetext-and-confirm-output-contains-only-barcode-pattern.cs index 534d46d..caeff08 100644 --- a/one-dimensional-barcode-types/generate-barcode-disable-showcodetext-and-confirm-output-contains-only-barcode-pattern.cs +++ b/one-dimensional-barcode-types/generate-barcode-disable-showcodetext-and-confirm-output-contains-only-barcode-pattern.cs @@ -1,52 +1,44 @@ -// Title: Generate Code128 barcode without human‑readable text -// Description: Demonstrates creating a Code128 barcode image while disabling the displayed code text. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode appearance using BarcodeGenerator and its Parameters. Typical use cases include producing clean barcode images for printing or embedding where human‑readable text is not required. Developers often need to adjust CodeTextParameters, such as Location, Font, and Visibility, to meet specific design requirements. +// Title: Generate Code128 barcode without human‑readable text and save as PNG +// Description: Demonstrates creating a Code128 barcode, disabling the displayed code text, and saving the result as a PNG image. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode appearance using BarcodeGenerator and its Parameters. Developers commonly use these APIs to customize symbology, hide or position human‑readable text, and export barcodes in various image formats for integration into documents, labels, or web applications. // Prompt: Generate a barcode, disable ShowCodeText, and confirm output contains only the barcode pattern. -// Tags: code128, barcode generation, hide codetext, image output, aspose.barcode, csharp +// Tags: code128, hidecodetext, png, barcodegenerator, aspose.barcode using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; -/// -/// Example program that generates a Code128 barcode image with the human‑readable text disabled. -/// -class Program +namespace BarcodeSample { /// - /// Entry point. Creates a barcode, saves it to a PNG file, and verifies the file was written. + /// Provides a simple console application that generates a Code128 barcode, + /// disables the human‑readable text, and saves the image as a PNG file. /// - static void Main() + class Program { - // Define the output file path - string outputPath = "barcode.png"; - - // Ensure a previous file does not interfere with the demo - if (File.Exists(outputPath)) + /// + /// Entry point of the application. Creates the barcode, configures visual settings, + /// and writes the output file to the current directory. + /// + static void Main() { - File.Delete(outputPath); - } + // Initialize a BarcodeGenerator for Code128 with the desired code text ("12345"). + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "12345")) + { + // Hide the human‑readable text by setting its location to None (equivalent to disabling ShowCodeText). + generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.None; - // Initialize the barcode generator for Code128 with sample data - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) - { - // Hide the human‑readable code text (equivalent to disabling ShowCodeText) - generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.None; + // Determine the full path for the output PNG file in the current working directory. + string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode.png"); - // Persist the barcode image to the specified file - generator.Save(outputPath); - } + // Save the generated 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)) - { - Console.WriteLine($"Barcode image saved to '{outputPath}'."); - Console.WriteLine("Human‑readable text is disabled; the output contains only the barcode pattern."); - } - else - { - Console.WriteLine("Failed to generate the barcode image."); + // Inform the user that the barcode has been generated without the code text. + Console.WriteLine("Barcode generated and saved to 'barcode.png' with ShowCodeText disabled."); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-barcode-export-its-xml-edit-codabarstartsymbol-attribute-and-re-import-to-change-start-character.cs b/one-dimensional-barcode-types/generate-barcode-export-its-xml-edit-codabarstartsymbol-attribute-and-re-import-to-change-start-character.cs index 9e9bd09..0ee42f1 100644 --- a/one-dimensional-barcode-types/generate-barcode-export-its-xml-edit-codabarstartsymbol-attribute-and-re-import-to-change-start-character.cs +++ b/one-dimensional-barcode-types/generate-barcode-export-its-xml-edit-codabarstartsymbol-attribute-and-re-import-to-change-start-character.cs @@ -1,78 +1,43 @@ -// Title: Generate Codabar barcode, modify start symbol via XML, and re‑import -// Description: Demonstrates creating a Codabar barcode, exporting its settings to XML, editing the start symbol attribute, and re‑importing to produce a barcode with a new start character. -// Category-Description: This example belongs to the Aspose.BarCode generation and XML manipulation category. It showcases the use of BarcodeGenerator for creating barcodes, ExportToXml for persisting settings, and ImportFromXml for re‑creating a generator with modified parameters. Typical use cases include batch barcode customization, dynamic symbol changes, and configuration persistence. Developers often need to adjust barcode attributes programmatically without rebuilding the entire generator. +// Title: Generate Codabar barcode, modify start/stop symbols via XML, and save updated image +// Description: This example creates a Codabar barcode, exports its configuration to an XML file, edits the start/stop symbols, and re‑imports the settings to generate a new barcode image. +// Category-Description: Demonstrates barcode generation and configuration management using Aspose.BarCode. It shows how to use BarcodeGenerator to create a barcode, persist its parameters with ExportToXml, modify specific properties (Codabar start/stop symbols) in the XML, and reload the configuration with ImportFromXml to produce an updated barcode. Useful for developers who need to store, edit, or version barcode settings without rebuilding the generator each time. // Prompt: Generate a barcode, export its XML, edit CodabarStartSymbol attribute, and re‑import to change start character. -// Tags: codabar, barcode, xml, start-symbol, generation, aspose.barcode +// Tags: codabar, barcode generation, xml export, xml import, startstop symbol, aspose.barcode, c# using System; -using System.IO; -using System.Linq; -using System.Xml.Linq; using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Example program that creates a Codabar barcode, modifies its start symbol via XML, -/// and generates the final barcode image with the updated settings. +/// Demonstrates creating a Codabar barcode, exporting its settings to XML, +/// modifying the start/stop symbols, and regenerating the barcode image. /// class Program { /// - /// Entry point of the example. Executes the barcode creation, XML export/modification, - /// and final image generation steps. + /// Entry point of the example. /// static void Main() { - // Define file paths for the intermediate XML files and the final image. - const string xmlPath = "codabar.xml"; - const string modifiedXmlPath = "codabar_modified.xml"; - const string outputImagePath = "codabar_final.png"; - - // 1. Create a Codabar barcode generator with the default start/stop symbol 'A'. + // Step 1: Generate a Codabar barcode with default start/stop symbols (A) and save the image. using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, "A123456A")) { - // Export the generator's current configuration to an XML file. - generator.ExportToXml(xmlPath); - } - - // 2. Load the exported XML and change the CodabarStartSymbol to 'B'. - if (!File.Exists(xmlPath)) - { - Console.WriteLine($"Error: XML file '{xmlPath}' not found."); - return; - } - - XDocument doc = XDocument.Load(xmlPath); - // Locate the CodabarStartSymbol element within the XML structure. - XElement startSymbolElement = doc.Root?.Descendants("CodabarStartSymbol").FirstOrDefault(); - if (startSymbolElement == null) - { - Console.WriteLine("Error: CodabarStartSymbol element not found in XML."); - return; - } - - // Update the element's value to the new start symbol. - startSymbolElement.Value = "B"; + // Save the original barcode image. + generator.Save("codabar_original.png"); - // Save the modified XML to a new file. - doc.Save(modifiedXmlPath); - - // 3. Import the modified XML to create a new generator with the updated start symbol. - if (!File.Exists(modifiedXmlPath)) - { - Console.WriteLine($"Error: Modified XML file '{modifiedXmlPath}' not found."); - return; + // Export the current barcode configuration to an XML file for later editing. + generator.ExportToXml("codabar.xml"); } - using (var generatorModified = BarcodeGenerator.ImportFromXml(modifiedXmlPath)) + // Step 2: Load the barcode configuration from the XML file, modify the start/stop symbols, and save the new image. + using (var generatorFromXml = BarcodeGenerator.ImportFromXml("codabar.xml")) { - // The CodeText still contains the old start/stop symbols; update it to match the new symbol. - generatorModified.CodeText = "B123456B"; + // Change both the start and stop symbols to 'C'. + generatorFromXml.Parameters.Barcode.Codabar.StartSymbol = CodabarSymbol.C; + generatorFromXml.Parameters.Barcode.Codabar.StopSymbol = CodabarSymbol.C; - // Save the final barcode image to the specified path. - generatorModified.Save(outputImagePath); + // Save the modified barcode image in PNG format. + generatorFromXml.Save("codabar_modified.png", BarCodeImageFormat.Png); } - - Console.WriteLine($"Barcode generated with new start symbol and saved to '{outputImagePath}'."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-barcode-export-its-xml-modify-codabarchecksummode-to-mod16-re-import-and-verify-checksum-calculation.cs b/one-dimensional-barcode-types/generate-barcode-export-its-xml-modify-codabarchecksummode-to-mod16-re-import-and-verify-checksum-calculation.cs index 9d819a8..24fc502 100644 --- a/one-dimensional-barcode-types/generate-barcode-export-its-xml-modify-codabarchecksummode-to-mod16-re-import-and-verify-checksum-calculation.cs +++ b/one-dimensional-barcode-types/generate-barcode-export-its-xml-modify-codabarchecksummode-to-mod16-re-import-and-verify-checksum-calculation.cs @@ -1,8 +1,8 @@ -// Title: Codabar Barcode Generation with XML Export/Import and Checksum Mode Modification -// Description: Demonstrates creating a Codabar barcode, exporting its settings to XML, changing the checksum mode to Mod16, re‑importing, and verifying decoding. -// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes, exporting/importing settings via XML, and BarCodeReader for decoding. Developers often need to adjust barcode parameters programmatically, persist configurations, and validate that changes (e.g., checksum modes) are applied correctly. Ideal for learning how to manipulate Codabar checksum settings using Aspose.BarCode APIs. +// Title: Generate Codabar barcode, export to XML, modify checksum mode, re‑import and verify +// Description: Demonstrates creating a Codabar barcode, exporting its configuration to XML, changing the CodabarChecksumMode to Mod16, re‑importing the settings, and confirming checksum validation through reading. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It shows how to use BarcodeGenerator to create barcodes, export and import settings via XML, adjust checksum modes, and employ BarCodeReader for validation. Developers working with one‑dimensional symbologies often need to persist generator configurations, modify checksum behavior, and verify encoded data programmatically. // Prompt: Generate a barcode, export its XML, modify CodabarChecksumMode to Mod16, re‑import, and verify checksum calculation. -// Tags: codabar, checksum, xml, export, import, generation, recognition, aspose.barcode +// Tags: codabar, checksum, xml, export, import, barcode generation, barcode recognition, aspose.barcode using System; using System.IO; @@ -11,65 +11,84 @@ using Aspose.BarCode.BarCodeRecognition; /// -/// Example program that creates a Codabar barcode, exports its configuration to XML, -/// modifies the checksum mode, re‑imports the settings, and verifies decoding. +/// Example program that creates a Codabar barcode, manipulates its XML configuration, +/// re‑imports the settings, and validates the checksum using Aspose.BarCode APIs. /// class Program { /// - /// Entry point of the example. Executes barcode generation, XML export/import, - /// checksum mode modification, and verification steps. + /// Entry point of the example. Executes the barcode generation, XML export/import, + /// and checksum verification workflow. /// static void Main() { - // Prepare output directory - string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "output"); - Directory.CreateDirectory(outputDir); + // Define temporary file paths for XML configuration and barcode images + string xmlPath = Path.Combine(Path.GetTempPath(), "codabar.xml"); + string imgPath = Path.Combine(Path.GetTempPath(), "codabar.png"); - // Define file paths for XML and images - string xmlPath = Path.Combine(outputDir, "codabar.xml"); - string imgPath1 = Path.Combine(outputDir, "codabar_initial.png"); - string imgPath2 = Path.Combine(outputDir, "codabar_modified.png"); - - // 1. Create a Codabar barcode, enable checksum, set initial mode, save image and export to XML + // 1. Create a Codabar barcode generator with sample code text using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, "A123456A")) { - // Enable checksum calculation + // Enable checksum calculation (optional for Codabar but required for verification) generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes; - // Set an initial checksum mode (Mod10) to demonstrate change later - generator.Parameters.Barcode.Codabar.ChecksumMode = CodabarChecksumMode.Mod10; - - // Save the initial barcode image - generator.Save(imgPath1); - // Export generator settings to XML for later reuse + // Export the generator's settings to an XML file for later modification generator.ExportToXml(xmlPath); + + // Save the generated barcode image (used later for checksum verification) + generator.Save(imgPath, BarCodeImageFormat.Png); } - // 2. Import settings from XML, modify checksum mode to Mod16, and save a new image - using (var importedGen = BarcodeGenerator.ImportFromXml(xmlPath)) + // 2. Modify the exported XML to set CodabarChecksumMode to Mod16 + if (!File.Exists(xmlPath)) { - // Change checksum mode to Mod16 - importedGen.Parameters.Barcode.Codabar.ChecksumMode = CodabarChecksumMode.Mod16; - // Ensure checksum generation remains enabled - importedGen.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes; + Console.WriteLine("XML file was not created."); + return; + } + + string xmlContent = File.ReadAllText(xmlPath); - // Save the modified barcode image - importedGen.Save(imgPath2); + // Replace any existing checksum mode with Mod16 (default is Mod16, but we enforce it) + xmlContent = xmlContent.Replace("Mod10", "Mod16"); - Console.WriteLine($"Checksum mode after import and modification: {importedGen.Parameters.Barcode.Codabar.ChecksumMode}"); + // If the element was not present, add it under the Codabar settings + if (!xmlContent.Contains("")) + { + // Simple insertion before the closing tag + xmlContent = xmlContent.Replace("", " Mod16\n"); } - // 3. Read the modified barcode to verify it can be decoded - using (var reader = new BarCodeReader(imgPath2, DecodeType.Codabar)) + // Write the updated XML back to the file system + File.WriteAllText(xmlPath, xmlContent); + + // 3. Re‑import the barcode generator from the modified XML + using (var importedGenerator = BarcodeGenerator.ImportFromXml(xmlPath)) { - foreach (var result in reader.ReadBarCodes()) + // Ensure checksum remains enabled after import + importedGenerator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes; + + // Save the regenerated barcode image (optional, used for verification) + string regeneratedImgPath = Path.Combine(Path.GetTempPath(), "codabar_regenerated.png"); + importedGenerator.Save(regeneratedImgPath, BarCodeImageFormat.Png); + + // 4. Verify checksum calculation by reading the regenerated barcode + using (var reader = new BarCodeReader(regeneratedImgPath, DecodeType.Codabar)) { - Console.WriteLine($"Decoded CodeText: {result.CodeText}"); - // Codabar does not expose a checksum value via the reader; successful decoding confirms validity. + // Enable checksum validation during reading + reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; + + // Iterate through all detected barcodes (should be only one) + foreach (var result in reader.ReadBarCodes()) + { + Console.WriteLine($"CodeText: {result.CodeText}"); + // For Codabar, checksum is available in the OneD extended parameters + Console.WriteLine($"Checksum: {result.Extended.OneD.CheckSum}"); + } } } - Console.WriteLine("Barcode generation, XML export/import, and verification completed."); + // Clean up temporary files (optional) + try { File.Delete(xmlPath); } catch { } + try { File.Delete(imgPath); } catch { } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-barcode-image-at-600-dpi-resolution-for-high-quality-glossy-label-printing.cs b/one-dimensional-barcode-types/generate-barcode-image-at-600-dpi-resolution-for-high-quality-glossy-label-printing.cs index c6d71cd..805dda7 100644 --- a/one-dimensional-barcode-types/generate-barcode-image-at-600-dpi-resolution-for-high-quality-glossy-label-printing.cs +++ b/one-dimensional-barcode-types/generate-barcode-image-at-600-dpi-resolution-for-high-quality-glossy-label-printing.cs @@ -1,38 +1,45 @@ -// Title: Generate high‑resolution Code128 barcode image -// Description: Demonstrates creating a Code128 barcode and saving it as a PNG with 600 DPI resolution for high‑quality glossy label printing. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to configure barcode parameters such as resolution using the BarcodeGenerator class. Typical use cases include producing high‑resolution images for printing on glossy labels, packaging, or product identification. Developers often need to set DPI, choose symbology, and export to common image formats. +// Title: Generate high‑resolution barcode image for glossy label printing +// Description: Demonstrates how to create a Code128 barcode image at 600 DPI, suitable for high‑quality glossy label output. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and resolution settings. Typical use cases include producing printable barcodes for product labels, packaging, and inventory tags where high resolution and color control are required. Developers often need to adjust DPI, anti‑aliasing, and colors to meet printing specifications. // Prompt: Generate a barcode image at 600 DPI resolution for high‑quality glossy label printing. -// Tags: code128, barcode generation, resolution, png, aspose.barcode, aspose.drawing +// Tags: barcode, code128, resolution, dpi, png, aspose.barcode, image generation, anti-aliasing, color using System; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; -namespace BarcodeSample +/// +/// Example program that generates a Code128 barcode image at 600 DPI for high‑quality glossy label printing. +/// +class Program { /// - /// Sample program that generates a Code128 barcode image with a resolution of 600 DPI. + /// Entry point. Creates the barcode, configures resolution, colors, and saves as PNG. /// - class Program + static void Main() { - /// - /// Entry point of the application. Creates a barcode, sets high resolution, and saves it as PNG. - /// - static void Main() + // Define the output file path for the generated barcode image. + string outputPath = "barcode.png"; + + // Initialize a BarcodeGenerator for Code128 with the sample code text. + using (Aspose.BarCode.Generation.BarcodeGenerator generator = new Aspose.BarCode.Generation.BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Initialize the barcode generator with Code128 symbology and sample data. - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) - { - // Configure the generator to use 600 DPI for high‑quality glossy label printing. - generator.Parameters.Resolution = 600f; + // Set the image resolution to 600 DPI for high‑quality printing. + generator.Parameters.Resolution = 600f; + + // Enable anti‑aliasing to improve visual smoothness. + generator.Parameters.UseAntiAlias = true; - // Save the generated barcode as a PNG file. - generator.Save("barcode.png"); - } + // Configure bar (foreground) and background colors suitable for glossy labels. + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; - // Inform the user that the barcode image has been created. - Console.WriteLine("Barcode image generated at 600 DPI: barcode.png"); + // Save the barcode image as PNG (lossless format) with the specified resolution. + generator.Save(outputPath, BarCodeImageFormat.Png); } + + // Inform the user where the barcode image was saved. + Console.WriteLine($"Barcode image saved to {outputPath}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-barcode-set-showcodetext-to-false-and-confirm-only-bars-are-present-in-output-file.cs b/one-dimensional-barcode-types/generate-barcode-set-showcodetext-to-false-and-confirm-only-bars-are-present-in-output-file.cs index f7a8db3..56b5f69 100644 --- a/one-dimensional-barcode-types/generate-barcode-set-showcodetext-to-false-and-confirm-only-bars-are-present-in-output-file.cs +++ b/one-dimensional-barcode-types/generate-barcode-set-showcodetext-to-false-and-confirm-only-bars-are-present-in-output-file.cs @@ -1,80 +1,54 @@ -// Title: Generate Code128 barcode without human‑readable text and verify bar‑only output -// Description: This example creates a Code128 barcode, disables the code text display, saves it as a PNG file, and checks that the image contains only the bar and background colors. -// Category-Description: Demonstrates Aspose.BarCode generation features, focusing on hiding the human‑readable code text (ShowCodeText) for a clean barcode image. It uses BarcodeGenerator, EncodeTypes, and barcode parameters to customize appearance, then validates the output using Aspose.Drawing bitmap analysis. Ideal for developers needing bar‑only images for printing or scanning workflows. +// Title: Generate Code128 barcode without human‑readable text +// Description: Demonstrates creating a Code128 barcode, disabling the displayed code text, and saving the result as a PNG image containing only the bars. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure BarcodeGenerator parameters such as CodeTextParameters to control visual output. Typical use cases include producing clean bar‑only images for printing or embedding where human‑readable text is unnecessary. Developers often need to adjust symbology settings, hide code text, and export to common image formats using classes like BarcodeGenerator, EncodeTypes, and BarCodeImageFormat. // Prompt: Generate a barcode, set ShowCodeText to false, and confirm only bars are present in the output file. -// Tags: code128, hidecodetext, png, aspose.barcode, aspose.drawing +// Tags: code128, generate, hidecodetext, png, barcodegenerator, aspose.barcode using System; -using System.Collections.Generic; using System.IO; -using Aspose.BarCode.Generation; using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Example program that generates a Code128 barcode without displaying the code text, -/// saves it as a PNG file, and verifies that the resulting image contains only the bar -/// color and the background color. +/// Example program that generates a Code128 barcode, hides the human‑readable text, +/// and saves the image as a PNG file containing only the bars. /// class Program { /// - /// Entry point of the example. Performs barcode generation, saves the image, - /// and runs a simple verification of the pixel colors. + /// Entry point of the application. /// static void Main() { // Define the output file path for the generated barcode image. string outputPath = "barcode.png"; - // Create a barcode generator for Code128 with the sample text "1234567890". - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Ensure the directory for the output file exists; create it if necessary. + string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(directory)) { - // Hide the human‑readable text (show only the bars). - generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.None; + Directory.CreateDirectory(directory); + } - // Optional: set the bar color to black and the background to white. - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; - generator.Parameters.BackColor = Aspose.Drawing.Color.White; + // Initialize a BarcodeGenerator for Code128 symbology with sample data. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) + { + // Hide the human‑readable text by setting its location to None (equivalent to ShowCodeText = false). + generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.None; - // Save the barcode image to the specified path (PNG format by default). - generator.Save(outputPath); + // Save the barcode as a PNG image; only the bars will be rendered. + generator.Save(outputPath, BarCodeImageFormat.Png); } - // Verify that the saved image file exists. - if (!File.Exists(outputPath)) + // Verify that the barcode image file was successfully created and inform the user. + if (File.Exists(outputPath)) { - Console.WriteLine($"Failed to create the barcode image at '{outputPath}'."); - return; + Console.WriteLine($"Barcode saved to '{outputPath}'. Human‑readable text is hidden, so only bars are present."); } - - // Load the saved image for pixel analysis. - using (var bitmap = new Bitmap(outputPath)) + else { - var distinctColors = new HashSet(); - - // Scan all pixels (acceptable for small images) to collect distinct colors. - for (int y = 0; y < bitmap.Height; y++) - { - for (int x = 0; x < bitmap.Width; x++) - { - distinctColors.Add(bitmap.GetPixel(x, y)); - - // Early exit if more than two distinct colors are found. - if (distinctColors.Count > 2) - break; - } - - if (distinctColors.Count > 2) - break; - } - - // Output verification result based on the number of distinct colors. - if (distinctColors.Count <= 2) - Console.WriteLine("Verification passed: only bars (and background) are present in the output file."); - else - Console.WriteLine("Verification failed: additional elements detected in the output file."); + Console.WriteLine("Failed to create the barcode image."); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-barcode-set-showcodetext-to-true-and-position-text-above-bars-with-small-vertical-offset.cs b/one-dimensional-barcode-types/generate-barcode-set-showcodetext-to-true-and-position-text-above-bars-with-small-vertical-offset.cs index 1165ea8..0243172 100644 --- a/one-dimensional-barcode-types/generate-barcode-set-showcodetext-to-true-and-position-text-above-bars-with-small-vertical-offset.cs +++ b/one-dimensional-barcode-types/generate-barcode-set-showcodetext-to-true-and-position-text-above-bars-with-small-vertical-offset.cs @@ -1,42 +1,40 @@ // Title: Generate Code128 barcode with text above bars -// Description: Demonstrates creating a Code128 barcode, showing the human‑readable text above the bars with a small vertical offset. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode appearance using BarcodeGenerator, EncodeTypes, and CodeTextParameters. Typical use cases include adding readable text to barcodes for labeling products or documents, where developers need to control text location, spacing, and font. The snippet serves as a reference for developers searching for barcode text positioning techniques. +// Description: Demonstrates how to create a Code128 barcode, enable the human‑readable text, position it above the bars, and apply a small vertical offset before saving as PNG. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator and related parameter classes (CodeTextParameters, CodeLocation, TextAlignment). Typical use cases include creating printable barcodes with customized text placement for inventory, shipping, or retail applications. Developers often need to adjust text location, alignment, and spacing to meet branding or layout requirements. // Prompt: Generate a barcode, set ShowCodeText to true, and position text above bars with a small vertical offset. -// Tags: code128, barcode, generation, showcodetext, textposition, aspnet, aspose.barcode, imageoutput +// Tags: code128, barcode generation, showcodetext, text above, vertical offset, png, aspose.barcode, barcodgenerator, codetextparameters using System; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; /// -/// Example program that generates a Code128 barcode, displays the human‑readable text -/// above the bars, and applies a small vertical offset for better visual separation. +/// Demonstrates generating a Code128 barcode with human‑readable text positioned above the bars. /// class Program { /// - /// Entry point of the example. Creates the barcode, configures text appearance, - /// and saves the result as a PNG image. + /// Entry point that creates the barcode, configures text display, and saves the image. /// static void Main() { - // Initialize a BarcodeGenerator for Code128 with the sample value "1234567890" - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Initialize the barcode generator for Code128 with the sample text. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) { - // Ensure the human‑readable text is displayed (ShowCodeText is true by default when location is set) - // Position the text above the barcode bars + // Show the human‑readable text and place it above the bars. generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Above; - // Apply a small vertical offset (2 points) between the text and the bars + // Apply a small vertical offset (2 points) between the text and the bars. generator.Parameters.Barcode.CodeTextParameters.Space.Point = 2f; - // Optional: customize the font for better visibility - generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Arial"; - generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 10f; + // Center the text horizontally. + generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center; - // Save the generated barcode image to a file + // Save the generated barcode as a PNG image. generator.Save("barcode.png"); } + + // Output the location of the generated file. + Console.WriteLine("Barcode generated: barcode.png"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-barcode-with-custom-foreground-color-00ff00-lime-and-save-as-high-quality-tiff-file.cs b/one-dimensional-barcode-types/generate-barcode-with-custom-foreground-color-00ff00-lime-and-save-as-high-quality-tiff-file.cs index bc67c71..f5f2d27 100644 --- a/one-dimensional-barcode-types/generate-barcode-with-custom-foreground-color-00ff00-lime-and-save-as-high-quality-tiff-file.cs +++ b/one-dimensional-barcode-types/generate-barcode-with-custom-foreground-color-00ff00-lime-and-save-as-high-quality-tiff-file.cs @@ -1,35 +1,44 @@ -// Title: Generate a lime-colored Code128 barcode and save as high‑resolution TIFF -// Description: Demonstrates how to set a custom foreground color (#00FF00) for a barcode and export it as a high‑quality TIFF image. -// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating usage of BarcodeGenerator, EncodeTypes, and rendering parameters such as BarColor and Resolution. Developers often need to customize barcode appearance and output format for printing or archival purposes. The snippet shows typical steps for creating, styling, and saving barcodes in .NET applications. +// Title: Generate a Code128 barcode with lime foreground color and save as high‑quality TIFF +// Description: This example creates a Code128 barcode, applies a custom lime (#00FF00) bar color, sets a high resolution, and saves the result as a TIFF file. +// Category-Description: Aspose.BarCode generation examples showing how to customize barcode appearance and output format. It covers using BarcodeGenerator, setting Parameters such as Resolution and BarColor, and saving to image formats like TIFF. Developers often need to produce high‑resolution barcodes for print media, requiring precise color and DPI control. // Prompt: Generate a barcode with custom foreground color #00FF00 (lime) and save as a high‑quality TIFF file. -// Tags: code128, barcode, color, tiff, highresolution, aspnet, aspose.barcode, generation +// Tags: code128, barcode-generation, tiff, aspose.barcode, aspose.drawing using System; -using Aspose.BarCode; +using System.IO; using Aspose.BarCode.Generation; using Aspose.Drawing; -/// -/// Entry point for the barcode generation example. -/// -class Program +namespace BarcodeExample { /// - /// Generates a Code128 barcode with lime foreground color and saves it as a 300 DPI TIFF file. + /// Demonstrates generating a Code128 barcode with a custom lime foreground color and saving it as a high‑quality TIFF image. /// - static void Main() + class Program { - // Initialize the barcode generator with Code128 symbology and sample data. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + /// + /// Entry point of the example. Creates the barcode, configures appearance, and writes the image to disk. + /// + static void Main() { - // Apply lime color (#00FF00) to the bars. - generator.Parameters.Barcode.BarColor = Color.FromArgb(0, 255, 0); + // Define the output file name + string outputFile = "barcode.tiff"; - // Set resolution to 300 DPI for high‑quality output. - generator.Parameters.Resolution = 300f; + // Initialize a BarcodeGenerator for Code128 with sample data + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + { + // Configure high resolution (e.g., 300 DPI) for print‑quality output + generator.Parameters.Resolution = 300f; - // Save the generated barcode as a TIFF image. - generator.Save("barcode.tiff"); + // Set the bar (foreground) color to lime (#00FF00) + generator.Parameters.Barcode.BarColor = Color.FromArgb(0, 255, 0); + + // Save the generated barcode as a TIFF image + generator.Save(outputFile, BarCodeImageFormat.Tiff); + } + + // Inform the user where the file was saved + Console.WriteLine($"Barcode saved to {Path.GetFullPath(outputFile)}"); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-barcode-with-xdimension-of-033-mm-to-meet-specific-industry-size-standards.cs b/one-dimensional-barcode-types/generate-barcode-with-xdimension-of-033-mm-to-meet-specific-industry-size-standards.cs index d7e30d9..9e06e04 100644 --- a/one-dimensional-barcode-types/generate-barcode-with-xdimension-of-033-mm-to-meet-specific-industry-size-standards.cs +++ b/one-dimensional-barcode-types/generate-barcode-with-xdimension-of-033-mm-to-meet-specific-industry-size-standards.cs @@ -1,33 +1,41 @@ -// Title: Generate Code128 barcode with specific XDimension -// Description: Demonstrates creating a Code128 barcode, setting its XDimension to 0.33 mm, and saving the result as a PNG image. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode dimensions using the BarcodeGenerator class. Developers often need to adjust XDimension to meet industry size standards for scanning reliability. Typical use cases include customizing barcode size for packaging, labeling, and compliance with printing specifications. +// Title: Generate Code128 barcode with precise XDimension +// Description: Demonstrates creating a Code128 barcode image with an XDimension of 0.33 mm, suitable for industry‑specific size requirements. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode parameters such as module size (XDimension) using the BarcodeGenerator class. Typical use cases include producing barcodes that must conform to strict dimensional standards for packaging, logistics, or retail scanning. Developers often need to adjust XDimension, set symbology, and export to common image formats like PNG. // Prompt: Generate a barcode with XDimension of 0.33 mm to meet specific industry size standards. -// Tags: code128, barcode generation, png output, xdimension, aspnet.barcode, barcodegenerator +// Tags: code128, barcode generation, png, xdimension, aspose.barcode using System; +using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Example program that generates a Code128 barcode with a custom XDimension and saves it as a PNG file. +/// Example program that creates a Code128 barcode image with a specific XDimension. /// class Program { /// - /// Entry point of the application. Creates a barcode, configures its XDimension, and writes the image to disk. + /// Entry point. Generates the barcode and saves it as a PNG file. /// static void Main() { - // Initialize the barcode generator with Code128 symbology and sample data. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // Define the output file path for the generated barcode image. + string outputPath = "barcode.png"; + + // Initialize a BarcodeGenerator for the Code128 symbology. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128)) { - // Configure the XDimension (module width) to 0.33 millimeters as required by industry standards. + // Set the text that will be encoded into the barcode. + generator.CodeText = "1234567890"; + + // Configure the XDimension (module width) to 0.33 millimeters. generator.Parameters.Barcode.XDimension.Millimeters = 0.33f; - // Save the generated barcode image in PNG format. - generator.Save("barcode.png"); + // Save the generated barcode as a PNG image to the specified path. + generator.Save(outputPath, BarCodeImageFormat.Png); } - // Inform the user that the barcode has been successfully generated. - Console.WriteLine("Barcode generated: barcode.png"); + // Inform the user where the barcode image has been saved. + Console.WriteLine($"Barcode saved to {outputPath}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-b-stop-symbol-c-and-embed-image-in-html-page.cs b/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-b-stop-symbol-c-and-embed-image-in-html-page.cs index bda3e21..e34ec5a 100644 --- a/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-b-stop-symbol-c-and-embed-image-in-html-page.cs +++ b/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-b-stop-symbol-c-and-embed-image-in-html-page.cs @@ -1,58 +1,59 @@ -// Title: Generate Codabar Barcode with Custom Start/Stop Symbols and Embed in HTML -// Description: This example creates a Codabar barcode using start symbol B and stop symbol C, saves it as a PNG image, and embeds the image in a simple HTML page. -// Category-Description: Demonstrates Aspose.BarCode generation for the Codabar symbology. It showcases the BarcodeGenerator class, setting Codabar-specific parameters (start/stop symbols), saving the barcode as an image, and producing an HTML file that references the image. Ideal for developers needing to integrate barcode images into web content or reports. +// Title: Generate Codabar barcode with custom start/stop symbols and embed in HTML +// Description: Creates a Codabar barcode using start symbol B and stop symbol C, converts it to a PNG image, encodes it as Base64, and embeds it in a simple HTML file. +// Category-Description: This example demonstrates Aspose.BarCode generation of one-dimensional barcodes, focusing on Codabar symbology. It shows how to configure barcode parameters, render the image to a stream, and embed the result in HTML. Developers working with barcode creation, image handling, and web integration commonly use BarcodeGenerator, EncodeTypes, BarCodeImageFormat, and related parameter classes. // Prompt: Generate a Codabar barcode with start symbol B, stop symbol C, and embed the image in an HTML page. -// Tags: codabar, barcode, generation, png, html, aspose.barcode +// Tags: codabar, barcode, generation, png, html, aspose.barcode, aspose.drawing using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Demonstrates how to generate a Codabar barcode with custom start/stop symbols -/// and embed the resulting image into an HTML page using Aspose.BarCode. +/// Demonstrates how to generate a Codabar barcode with specific start/stop symbols, +/// convert it to a PNG image, and embed the image directly into an HTML file using Base64 encoding. /// class Program { /// - /// Entry point of the example. Generates the barcode, saves it as PNG, - /// creates an HTML file that references the image, and writes the HTML to disk. + /// Entry point of the example. Generates the barcode, creates the HTML, and writes the output file. /// static void Main() { - // Define file names for the barcode image and the HTML page. - string imagePath = "codabar.png"; - string htmlPath = "barcode.html"; + // Define the raw barcode data (without start/stop symbols) + const string codeText = "123456"; - // Create a Codabar barcode generator inside a using block to ensure proper disposal. + // Initialize the barcode generator for Codabar symbology using (var generator = new BarcodeGenerator(EncodeTypes.Codabar)) { - // Set the data to encode (the raw numeric string without start/stop symbols). - generator.CodeText = "123456"; + // Assign the data to be encoded + generator.CodeText = codeText; - // Configure the Codabar start and stop symbols: B for start, C for stop. + // Configure start and stop symbols as required (B and C) generator.Parameters.Barcode.Codabar.StartSymbol = CodabarSymbol.B; generator.Parameters.Barcode.Codabar.StopSymbol = CodabarSymbol.C; - // Save the generated barcode as a PNG image to the specified path. - generator.Save(imagePath); + // Render the barcode to a memory stream in PNG format + using (var ms = new MemoryStream()) + { + generator.Save(ms, BarCodeImageFormat.Png); + byte[] imageBytes = ms.ToArray(); + + // Convert the PNG bytes to a Base64 string for embedding + string base64 = Convert.ToBase64String(imageBytes); + + // Build a minimal HTML page that displays the barcode image + string html = $"

Codabar Barcode (Start B, Stop C)

" + + $"\"Codabar" + + $""; + + // Write the HTML content to a file named 'barcode.html' + File.WriteAllText("barcode.html", html); + } } - // Build a minimal HTML document that embeds the generated barcode image. - string htmlContent = $@" - - - - Codabar Barcode - - -

Codabar Barcode (Start: B, Stop: C)

- - -"; - - // Write the HTML content to a file on disk. - File.WriteAllText(htmlPath, htmlContent); + // Inform the user that the operation completed successfully + Console.WriteLine("Barcode image embedded in 'barcode.html'."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-c-stop-symbol-d-and-embed-image-in-word-document.cs b/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-c-stop-symbol-d-and-embed-image-in-word-document.cs index f72c260..5fd997d 100644 --- a/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-c-stop-symbol-d-and-embed-image-in-word-document.cs +++ b/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-c-stop-symbol-d-and-embed-image-in-word-document.cs @@ -1,8 +1,8 @@ -// Title: Generate Codabar barcode and embed it in a Word document -// Description: Demonstrates creating a Codabar barcode with start symbol C and stop symbol D, saving it as a PNG image, and inserting the image into a Word document. -// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator (Aspose.BarCode.Generation) together with Aspose.Words to produce printable documents. Typical use cases include generating inventory labels, shipping tags, or any printable media that requires barcode data embedded in Word files. Developers often need to configure symbology settings, export barcode images, and programmatically manipulate Word documents. +// Title: Generate Codabar barcode and embed in Word document +// Description: Creates a Codabar barcode with start symbol C and stop symbol D, renders it as a PNG image in memory, and inserts the image into a Word document. +// Category-Description: This example demonstrates how to use Aspose.BarCode to generate barcodes and Aspose.Words to embed images into Word files. It covers barcode generation (EncodeTypes, BarcodeGenerator), configuring barcode parameters (Codabar start/stop symbols), saving the barcode to a stream, and inserting the image into a document via DocumentBuilder. Ideal for developers needing to automate document creation with barcodes for inventory, shipping, or tracking. // Prompt: Generate a Codabar barcode with start symbol C, stop symbol D, and embed the image in a Word document. -// Tags: codabar, barcode generation, word document, aspose.barcode, aspose.words, image embedding +// Tags: codabar, barcode generation, image embedding, word document, aspose.barcode, aspose.words using System; using System.IO; @@ -11,48 +11,44 @@ using Aspose.Words; /// -/// Example program that creates a Codabar barcode, saves it as an image, -/// and embeds the image into a Word document using Aspose libraries. +/// Demonstrates generating a Codabar barcode with custom start/stop symbols +/// and embedding the resulting image into a Word document using Aspose libraries. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Generates the barcode, inserts it into a Word file, + /// and saves the document to disk. /// static void Main() { - // Define file paths for the temporary barcode image and the final Word document. - string imagePath = "codabar.png"; - string docPath = "Codabar.docx"; + // Define the output Word document path + string outputDocPath = "Codabar.docx"; - // Remove any existing files to ensure a clean run. - if (File.Exists(imagePath)) - File.Delete(imagePath); - if (File.Exists(docPath)) - File.Delete(docPath); - - // Generate a Codabar barcode with start symbol C and stop symbol D. - using (var generator = new BarcodeGenerator(EncodeTypes.Codabar)) + // Initialize a barcode generator for Codabar with sample data + using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, "123456")) { - // Set the data to encode (excluding start/stop symbols). - generator.CodeText = "123456"; - - // Configure the start and stop symbols for Codabar. + // Configure start and stop symbols to C and D respectively generator.Parameters.Barcode.Codabar.StartSymbol = CodabarSymbol.C; generator.Parameters.Barcode.Codabar.StopSymbol = CodabarSymbol.D; - // Save the generated barcode as a PNG image. - generator.Save(imagePath); - } + // Render the barcode to a memory stream in PNG format + using (var imageStream = new MemoryStream()) + { + generator.Save(imageStream, BarCodeImageFormat.Png); + imageStream.Position = 0; // Reset stream position for reading - // Create a new Word document and insert the barcode image. - var doc = new Document(); - var builder = new DocumentBuilder(doc); - builder.InsertImage(imagePath); - doc.Save(docPath); + // Create a new Word document and insert the barcode image + var doc = new Document(); + var builder = new DocumentBuilder(doc); + builder.InsertImage(imageStream); + + // Save the Word document to the specified path + doc.Save(outputDocPath); + } + } - // Clean up the temporary barcode image file. - if (File.Exists(imagePath)) - File.Delete(imagePath); + // Output the full path of the generated document + Console.WriteLine($"Codabar barcode embedded in Word document: {Path.GetFullPath(outputDocPath)}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-stop-symbol-b-and-embed-it-in-pdf-report.cs b/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-stop-symbol-b-and-embed-it-in-pdf-report.cs index 973897b..1b6c266 100644 --- a/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-stop-symbol-b-and-embed-it-in-pdf-report.cs +++ b/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-stop-symbol-b-and-embed-it-in-pdf-report.cs @@ -1,53 +1,76 @@ +// Title: Generate Codabar barcode and embed in PDF +// Description: Demonstrates creating a Codabar barcode with start symbol A and stop symbol B, rendering it as an image, and inserting it into a PDF report. +// Category-Description: This example belongs to the Aspose.BarCode for .NET barcode generation category, showing how to use BarcodeGenerator with Codabar symbology, configure start/stop symbols, and combine the output with Aspose.Pdf to produce a PDF document. Developers often need to generate barcodes for inventory, shipping, or point‑of‑sale systems and embed them in reports or invoices; the key classes are BarcodeGenerator, EncodeTypes, CodabarSymbol, and Aspose.Pdf.Document. +// Prompt: Generate a Codabar barcode with start symbol A, stop symbol B, and embed it in a PDF report. +// Tags: codabar, barcode generation, pdf, aspose.barcode, aspose.pdf, csharp, example + using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; -using Aspose.Drawing.Imaging; using Aspose.Pdf; +/// +/// Demonstrates generating a Codabar barcode and embedding it into a PDF document. +/// class Program { + /// + /// Entry point of the example. Creates a Codabar barcode with start/stop symbols, + /// saves it to a memory stream, and inserts the image into a PDF file. + /// static void Main() { - // Define output file names - const string barcodeImagePath = "codabar.png"; - const string pdfReportPath = "CodabarReport.pdf"; + // Define the output PDF file path + string pdfPath = "CodabarReport.pdf"; - // Create Codabar barcode with start symbol A and stop symbol B - using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, "123456")) + // Initialize a Codabar barcode generator + using (var generator = new BarcodeGenerator(EncodeTypes.Codabar)) { - // Set start and stop symbols + // Set the barcode data (excluding start/stop symbols) + generator.CodeText = "123456"; + + // Configure start and stop symbols: A (start) and B (stop) generator.Parameters.Barcode.Codabar.StartSymbol = CodabarSymbol.A; generator.Parameters.Barcode.Codabar.StopSymbol = CodabarSymbol.B; - // Optional: set colors + // Optional visual settings: black bars on white background generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; generator.Parameters.BackColor = Aspose.Drawing.Color.White; - // Save barcode image to a file (also keep it in memory for PDF embedding) - generator.Save(barcodeImagePath); - using (var barcodeStream = new MemoryStream()) + // Render the barcode to a memory stream in PNG format + var barcodeStream = new MemoryStream(); + generator.Save(barcodeStream, BarCodeImageFormat.Png); + barcodeStream.Position = 0; // Reset stream position for reading + + // Create a new PDF document and add a page + using (var pdfDoc = new Document()) { - generator.Save(barcodeStream, BarCodeImageFormat.Png); - barcodeStream.Position = 0; + var page = pdfDoc.Pages.Add(); - // Create PDF document and embed the barcode image - using (var pdfDoc = new Document()) + // Create an Aspose.Pdf.Image from the barcode stream + var pdfImage = new Image { - var page = pdfDoc.Pages.Add(); + ImageStream = barcodeStream, + FixWidth = 200.0, + FixHeight = 100.0, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + Margin = new MarginInfo { Top = 20 } + }; - // Define rectangle where the image will be placed (llx, lly, urx, ury) - var rect = new Aspose.Pdf.Rectangle(100, 500, 400, 700); - page.AddImage(barcodeStream, rect); + // Insert the barcode image into the PDF page + page.Paragraphs.Add(pdfImage); - // Save the PDF report - pdfDoc.Save(pdfReportPath); - } + // Save the PDF document to the specified path + pdfDoc.Save(pdfPath); } + + // Release the memory stream resources + barcodeStream.Dispose(); } - Console.WriteLine($"Barcode image saved to: {Path.GetFullPath(barcodeImagePath)}"); - Console.WriteLine($"PDF report saved to: {Path.GetFullPath(pdfReportPath)}"); + // Inform the user where the PDF was saved + Console.WriteLine($"PDF report generated: {Path.GetFullPath(pdfPath)}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-stop-symbol-d-and-embed-png-in-pdf-report.cs b/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-stop-symbol-d-and-embed-png-in-pdf-report.cs index 43d56de..c35792e 100644 --- a/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-stop-symbol-d-and-embed-png-in-pdf-report.cs +++ b/one-dimensional-barcode-types/generate-codabar-barcode-with-start-symbol-stop-symbol-d-and-embed-png-in-pdf-report.cs @@ -1,63 +1,73 @@ -// Title: Generate Codabar barcode and embed in PDF report -// Description: Demonstrates creating a Codabar barcode with specific start/stop symbols, saving it as PNG, and embedding the image into a PDF document. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation and Aspose.Pdf document creation category. It showcases the use of BarcodeGenerator, Codabar settings, BarCodeImageFormat, and Aspose.Pdf Document/Image classes to produce printable reports. Developers often need to generate barcodes and combine them with PDF reports for invoices, shipping labels, or inventory documents. +// Title: Generate Codabar barcode and embed it in a PDF report +// Description: This example creates a Codabar barcode with start symbol A and stop symbol D, saves the barcode as a PNG image, and embeds the image into a PDF document. +// Category-Description: Demonstrates Aspose.BarCode barcode generation (EncodeTypes.Codabar, BarcodeGenerator) combined with Aspose.Pdf PDF creation. Typical for reports, invoices, or labels where a barcode image must be included in a PDF. Developers often need to configure barcode parameters, render to an image stream, and place the image on a PDF page using Aspose.Pdf.Image. // Prompt: Generate a Codabar barcode with start symbol A, stop symbol D, and embed the PNG in a PDF report. -// Tags: codabar, barcode generation, pdf embedding, aspose.barcode, aspose.pdf, png, pdf +// Tags: codabar, barcode generation, png, pdf, aspose.barcode, aspose.pdf using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Pdf; +using Aspose.Pdf.Text; /// -/// Program entry point demonstrating Codabar barcode generation and PDF embedding. +/// Demonstrates how to generate a Codabar barcode, save it as PNG, and embed it into a PDF report. /// class Program { /// - /// Generates a Codabar barcode PNG with start symbol A and stop symbol D, then embeds it into a PDF report. + /// Entry point of the example. Generates the barcode, creates a PDF, and saves the result. /// static void Main() { - // Define output file names - const string pngPath = "codabar.png"; + // Define the output PDF file path const string pdfPath = "CodabarReport.pdf"; - // Create a Codabar barcode with start symbol A and stop symbol D - using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, "123456")) + // Initialize a Codabar barcode generator with start symbol A and stop symbol D + using (var generator = new BarcodeGenerator(EncodeTypes.Codabar)) { - // Explicitly set the start and stop symbols + // Set the data to encode in the barcode + generator.CodeText = "123456"; + + // Configure start and stop symbols for Codabar generator.Parameters.Barcode.Codabar.StartSymbol = CodabarSymbol.A; generator.Parameters.Barcode.Codabar.StopSymbol = CodabarSymbol.D; - // Save the generated barcode as a PNG image - generator.Save(pngPath, BarCodeImageFormat.Png); - } - - // Create a new PDF document and embed the generated PNG image - using (var pdfDoc = new Document()) - { - // Add a new page to the PDF - var page = pdfDoc.Pages.Add(); + // Optional visual settings: black bars on white background + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; - // Create an image object that references the PNG file - var image = new Aspose.Pdf.Image + // Render the barcode to a memory stream in PNG format + using (var barcodeStream = new MemoryStream()) { - File = pngPath - // Image dimensions can be set here if needed (in points, 1 point = 1/72 inch) - // Width = 200, - // Height = 100 - }; + generator.Save(barcodeStream, BarCodeImageFormat.Png); + barcodeStream.Position = 0; // Reset stream position for reading + + // Create a new PDF document and add a page + var pdfDoc = new Document(); + var page = pdfDoc.Pages.Add(); + + // Create an image object that reads from the barcode stream + var pdfImage = new Aspose.Pdf.Image + { + ImageStream = barcodeStream, + FixWidth = 200f, + FixHeight = 200f, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + Margin = new MarginInfo { Top = 20 } + }; - // Add the image to the page's content - page.Paragraphs.Add(image); + // Add the image to the PDF page + page.Paragraphs.Add(pdfImage); - // Save the PDF report to disk - pdfDoc.Save(pdfPath); + // Save the PDF document to the specified path + pdfDoc.Save(pdfPath); + } } - // Inform the user where the files have been saved - Console.WriteLine($"Barcode PNG saved to: {pngPath}"); - Console.WriteLine($"PDF report saved to: {pdfPath}"); + // Output the location of the generated PDF + Console.WriteLine($"PDF report generated: {Path.GetFullPath(pdfPath)}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-codablock-f-barcode-with-multiline-data-and-export-image-as-bmp-file.cs b/one-dimensional-barcode-types/generate-codablock-f-barcode-with-multiline-data-and-export-image-as-bmp-file.cs index f30077e..348893f 100644 --- a/one-dimensional-barcode-types/generate-codablock-f-barcode-with-multiline-data-and-export-image-as-bmp-file.cs +++ b/one-dimensional-barcode-types/generate-codablock-f-barcode-with-multiline-data-and-export-image-as-bmp-file.cs @@ -1,41 +1,48 @@ -// Title: Generate Codablock‑F barcode with multiline data and save as BMP +// Title: Generate Codablock‑F Barcode with Multiline Data and Save as BMP // Description: Demonstrates creating a Codablock‑F barcode containing multiple lines of text and exporting it to a BMP image file. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class with EncodeTypes.CodablockF. Developers often need to encode multiline data in 2‑D barcodes for inventory, shipping, or document tracking, and then output the result in common image formats such as BMP, PNG, or JPEG. The snippet shows setting the CodeText, optional matrix dimensions, and saving the image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to use the BarcodeGenerator class with EncodeTypes.CodablockF. It shows setting multiline CodeText, configuring Codablock‑F specific parameters such as rows and columns, and saving the result in BMP format. Developers working on inventory, shipping labels, or any application requiring high‑density 2‑D barcodes can reference this pattern for quick implementation. // Prompt: Generate a Codablock‑F barcode with multiline data and export the image as a BMP file. -// Tags: codablockf, barcode, generation, bmp, multiline, aspose.barcode +// Tags: codablockf, barcode, generation, multiline, bmp, aspose.barcode using System; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Demonstrates generating a Codablock‑F barcode with multiline data and saving it as a BMP image. +/// Example program that creates a Codablock‑F barcode with multiline data +/// and saves it as a BMP image using Aspose.BarCode. /// class Program { /// - /// Entry point of the example. Creates the barcode and writes a confirmation message. + /// Entry point of the application. + /// Generates the barcode, configures layout, and writes the image to disk. /// static void Main() { - // Define multiline text that will be encoded in the barcode. - string codeText = "First line\nSecond line\nThird line"; + // Define the output file path for the BMP image. + string outputPath = "codablockf.bmp"; + + // Prepare multiline text to be encoded in the barcode. + // Each line is separated by a carriage‑return/line‑feed sequence. + string codeText = "First line\r\nSecond line\r\nThird line"; // Initialize the barcode generator for the Codablock‑F symbology. - using (var generator = new BarcodeGenerator(EncodeTypes.CodablockF)) + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.CodablockF)) { // Assign the multiline text to the generator. generator.CodeText = codeText; - // Optional: specify the number of rows and columns for the barcode matrix. - // generator.Parameters.Barcode.CodablockRows = 3; - // generator.Parameters.Barcode.CodablockColumns = 10; + // Optional: fine‑tune the barcode layout by specifying rows and columns. + generator.Parameters.Barcode.Codablock.Rows = 3; + generator.Parameters.Barcode.Codablock.Columns = 30; - // Save the generated barcode as a BMP image file. - generator.Save("codablockf.bmp"); + // Save the generated barcode as a BMP file. + generator.Save(outputPath, BarCodeImageFormat.Bmp); } - // Inform the user that the barcode image has been saved. - Console.WriteLine("Codablock‑F barcode saved as codablockf.bmp"); + // Inform the user where the file has been saved. + Console.WriteLine($"Codablock‑F barcode saved to: {outputPath}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-code-16k-barcode-with-aspect-ratio-nine-and-save-as-png-image.cs b/one-dimensional-barcode-types/generate-code-16k-barcode-with-aspect-ratio-nine-and-save-as-png-image.cs index 770eec0..3fea9af 100644 --- a/one-dimensional-barcode-types/generate-code-16k-barcode-with-aspect-ratio-nine-and-save-as-png-image.cs +++ b/one-dimensional-barcode-types/generate-code-16k-barcode-with-aspect-ratio-nine-and-save-as-png-image.cs @@ -1,35 +1,38 @@ // Title: Generate Code 16K barcode with aspect ratio nine and save as PNG -// Description: Demonstrates creating a Code 16K barcode, setting its aspect ratio to nine, and saving it as a PNG image using Aspose.BarCode. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to configure symbology‑specific parameters such as aspect ratio for Code 16K. It showcases the use of the BarcodeGenerator class together with EncodeTypes and barcode parameter objects, a common task for developers needing to produce high‑density linear barcodes for inventory, shipping, or packaging applications. +// Description: Demonstrates creating a Code 16K barcode, setting its aspect ratio to nine, and saving it as a PNG image file. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to use the BarcodeGenerator class with EncodeTypes.Code16K. It shows configuring symbology‑specific parameters such as AspectRatio, a common requirement when customizing barcode dimensions for printing or scanning applications. Developers looking for code samples on barcode creation, parameter tuning, and image export will find this pattern useful. // Prompt: Generate a Code 16K barcode with aspect ratio nine and save as PNG image. -// Tags: code16k, barcode, generation, png, aspose.barcode, aspectratio +// Tags: code16k, barcode, generation, aspectratio, png, aspose.barcode, csharp using System; -using Aspose.BarCode.Generation; using Aspose.BarCode; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeRecognition; /// -/// Example program that generates a Code 16K barcode with a custom aspect ratio -/// and saves it as a PNG image file. +/// Demonstrates generating a Code 16K barcode with a custom aspect ratio and saving it as a PNG image. /// class Program { /// - /// Entry point of the application. + /// Entry point that creates the barcode, configures its aspect ratio, saves the image, and writes a confirmation message. /// static void Main() { // Initialize a barcode generator for the Code 16K symbology - using (var generator = new BarcodeGenerator(EncodeTypes.Code16K)) + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code16K)) { // Define the data to encode in the barcode generator.CodeText = "1234567890"; - // Configure the Code 16K specific parameter: set aspect ratio to 9 + // Configure the aspect ratio (height/width) to 9 for Code 16K generator.Parameters.Barcode.Code16K.AspectRatio = 9f; - // Save the generated barcode as a PNG image in the current directory + // Export the generated barcode to a PNG file generator.Save("code16k.png"); } + + // Inform the user that the barcode image has been created + Console.WriteLine("Code 16K barcode generated and saved as code16k.png"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-code-16k-barcode-with-maximum-77-characters-save-high-resolution-tiff.cs b/one-dimensional-barcode-types/generate-code-16k-barcode-with-maximum-77-characters-save-high-resolution-tiff.cs index 167213e..062e1df 100644 --- a/one-dimensional-barcode-types/generate-code-16k-barcode-with-maximum-77-characters-save-high-resolution-tiff.cs +++ b/one-dimensional-barcode-types/generate-code-16k-barcode-with-maximum-77-characters-save-high-resolution-tiff.cs @@ -1,45 +1,60 @@ // Title: Generate Code 16K barcode and save as high‑resolution TIFF // Description: Demonstrates creating a Code 16K barcode with the maximum 77‑character payload and exporting it to a 300 DPI TIFF image. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode parameters such as resolution, aspect ratio, and quiet zones using the BarcodeGenerator and related parameter classes. Typical use cases include producing high‑quality printable barcodes for packaging, shipping labels, or archival documents. Developers often need to adjust DPI and module sizing to meet printing standards, and this snippet shows the essential API calls. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class with EncodeTypes.Code16K. It shows typical steps such as setting resolution, configuring symbology‑specific parameters, and saving the result in a high‑resolution raster format. Developers working with barcode creation, especially for Code 16K, can reference this pattern for custom payloads and image output requirements. // Prompt: Generate Code 16K barcode with maximum 77 characters, save high‑resolution TIFF. -// Tags: code16k, barcode, generation, tiff, highresolution, aspose.barcode, aspose.drawing +// Tags: code16k, barcode, generation, tiff, highresolution, aspose.barcode, encode-types, imageformat using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing.Imaging; +using Aspose.Drawing; /// -/// Example program that generates a Code 16K barcode with the maximum allowed -/// 77 characters and saves it as a high‑resolution TIFF image. +/// Example program that creates a Code 16K barcode with the maximum allowed +/// 77‑character text and saves it as a high‑resolution TIFF image. /// class Program { /// - /// Entry point of the example. Creates the barcode, configures its parameters, - /// and writes the result to a TIFF file. + /// Entry point of the example. Generates the barcode and writes the output file path to the console. /// static void Main() { - // Define the barcode text – exactly 77 characters, the maximum for Code 16K. - string codeText = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789AB"; + // Define the output file name (saved in the application’s working directory) + const string outputPath = "code16k.tiff"; - // Initialize the barcode generator for the Code 16K symbology with the provided text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, codeText)) + // Sample payload that uses the full 77‑character limit for Code 16K + string codeText = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN"; + + // Validate length to avoid runtime errors from the barcode generator + if (codeText.Length > 77) + { + throw new ArgumentException("Code text exceeds the maximum length of 77 characters."); + } + + // Initialize the barcode generator with Code 16K symbology and the prepared text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code16K, codeText)) { - // Set the output resolution to 300 DPI for high‑quality printing. - generator.Parameters.Resolution = 300f; + // Set image resolution to 300 DPI for high‑quality output + generator.Parameters.Resolution = 300; + + // Configure optional Code 16K‑specific settings + generator.Parameters.Barcode.Code16K.AspectRatio = 1.0f; // Default aspect ratio + generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = 10; // Default left quiet zone coefficient + generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = 1; // Default right quiet zone coefficient + + // Disable filled bars to keep the visual style consistent + generator.Parameters.Barcode.FilledBars = false; - // Configure Code 16K‑specific visual parameters. - generator.Parameters.Barcode.Code16K.AspectRatio = 1.0f; // Square modules. - generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = 10; // Left quiet zone coefficient. - generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = 1; // Right quiet zone coefficient. + // Suppress exceptions for incorrect code text (not required for valid Code 16K data) + generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; - // Save the generated barcode as a TIFF image with the specified resolution. - generator.Save("code16k.tif"); + // Save the generated barcode as a TIFF image with the specified resolution + generator.Save(outputPath, BarCodeImageFormat.Tiff); } - // Inform the user that the file has been created. - Console.WriteLine("Code16K barcode saved as 'code16k.tif'."); + // Inform the user where the file was saved + Console.WriteLine($"Code16K barcode saved to '{Path.GetFullPath(outputPath)}'."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-code-16k-barcodes-with-varying-quiet-zone-coefficients-in-loop-store-png-files.cs b/one-dimensional-barcode-types/generate-code-16k-barcodes-with-varying-quiet-zone-coefficients-in-loop-store-png-files.cs index 481b9cc..a95bc3a 100644 --- a/one-dimensional-barcode-types/generate-code-16k-barcodes-with-varying-quiet-zone-coefficients-in-loop-store-png-files.cs +++ b/one-dimensional-barcode-types/generate-code-16k-barcodes-with-varying-quiet-zone-coefficients-in-loop-store-png-files.cs @@ -1,66 +1,54 @@ // Title: Generate Code 16K barcodes with varying quiet zone coefficients -// Description: Demonstrates creating Code 16K barcodes with different quiet zone settings and saving them as PNG images. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to configure Code16K symbology parameters such as aspect ratio and quiet zone coefficients. It shows typical usage of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes for batch barcode creation, a common task for developers needing customized barcode outputs. +// Description: This example creates Code 16K barcodes using different quiet‑zone left and right coefficient values and saves each barcode as a PNG image. +// Category-Description: Demonstrates Aspose.BarCode barcode generation techniques, focusing on parameter customization such as quiet‑zone coefficients and aspect ratio. The example uses BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes, which are commonly employed by developers to produce and export barcodes in various formats for labeling, inventory, and tracking applications. // Prompt: Generate Code 16K barcodes with varying quiet zone coefficients in loop, store PNG files. -// Tags: barcode symbology, code16k, quiet zone, png output, aspose.barcode, generation +// Tags: code16k, quietzone, barcode, generation, png, aspose.barcode, encode-types, image-format using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.BarCode; /// -/// Generates a series of Code 16K barcodes with varying quiet zone coefficients -/// and saves each barcode as a PNG file in an output directory. +/// Program that generates Code 16K barcodes with varying quiet‑zone coefficients and saves them as PNG files. /// class Program { /// - /// Entry point of the example. Creates the output folder, defines quiet zone - /// coefficient pairs, generates barcodes, and writes them to PNG files. + /// Entry point. Creates an output folder, iterates over quiet‑zone coefficient combinations, + /// configures a for each, and writes the resulting PNG image to disk. /// static void Main() { - // Define the output directory relative to the current working directory - string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Code16K_Output"); - if (!Directory.Exists(outputDir)) - { - Directory.CreateDirectory(outputDir); - } + // Define the output folder for generated PNG files + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Code16K_Barcodes"); + Directory.CreateDirectory(outputFolder); - // Quiet zone coefficient pairs (left, right) to be applied to each barcode - var quietZonePairs = new (int left, int right)[] - { - (10, 1), - (12, 2), - (14, 3), - (16, 4), - (18, 5) - }; + // Sample codetext for the Code16K barcode + string codeText = "123456789012"; - // Sample codetext; Code16K supports alphanumeric strings - const string codeText = "SampleCode16K123"; - - // Iterate over each coefficient pair and generate a barcode - foreach (var (leftCoef, rightCoef) in quietZonePairs) + // Iterate over a range of quiet‑zone left and right coefficient values + for (int leftCoef = 10; leftCoef <= 12; leftCoef++) // left coefficient >= 10 { - // Initialize the generator for Code16K symbology with the provided text - using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, codeText)) + for (int rightCoef = 1; rightCoef <= 3; rightCoef++) // right coefficient >= 1 { - // Set the aspect ratio (example value: 1.0) - generator.Parameters.Barcode.Code16K.AspectRatio = 1.0f; - - // Apply the quiet zone coefficients for left and right sides - generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = leftCoef; - generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = rightCoef; - - // Build a descriptive file name that includes the coefficient values - string fileName = $"Code16K_L{leftCoef}_R{rightCoef}.png"; - string filePath = Path.Combine(outputDir, fileName); - - // Save the generated barcode as a PNG image - generator.Save(filePath, BarCodeImageFormat.Png); - Console.WriteLine($"Saved: {filePath}"); + // Create a new barcode generator for the current configuration + using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, codeText)) + { + // Apply quiet‑zone coefficient settings + generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = leftCoef; + generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = rightCoef; + + // Optional: set aspect ratio (example value) + generator.Parameters.Barcode.Code16K.AspectRatio = 1.0f; + + // Build a file name that reflects the current coefficients + string fileName = $"Code16K_L{leftCoef}_R{rightCoef}.png"; + string filePath = Path.Combine(outputFolder, fileName); + + // Save the generated barcode directly as a PNG image + generator.Save(filePath, BarCodeImageFormat.Png); + } } } } diff --git a/one-dimensional-barcode-types/generate-itf-14-barcode-encoding-gtin-applying-custom-frame-thickness-save-as-png.cs b/one-dimensional-barcode-types/generate-itf-14-barcode-encoding-gtin-applying-custom-frame-thickness-save-as-png.cs index 5f4807c..bcb2fb1 100644 --- a/one-dimensional-barcode-types/generate-itf-14-barcode-encoding-gtin-applying-custom-frame-thickness-save-as-png.cs +++ b/one-dimensional-barcode-types/generate-itf-14-barcode-encoding-gtin-applying-custom-frame-thickness-save-as-png.cs @@ -1,47 +1,49 @@ -// Title: Generate ITF‑14 barcode with custom frame thickness and save as PNG -// Description: This example creates an ITF‑14 barcode encoding a GTIN, applies a custom frame border thickness, and saves the image as a PNG file. -// Category-Description: Demonstrates Aspose.BarCode barcode generation for the ITF‑14 symbology, focusing on border customization. The example uses BarcodeGenerator, EncodeTypes, and ITF14BorderType classes to illustrate typical tasks such as setting border type, thickness, colors, and exporting to PNG. Ideal for developers needing to produce packaging barcodes with specific visual requirements. +// Title: Generate ITF-14 barcode with custom frame thickness and save as PNG +// Description: Demonstrates encoding a 14‑digit GTIN into an ITF‑14 barcode, applying a custom frame border thickness, and saving the result as a PNG image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to use the BarcodeGenerator class with EncodeTypes.ITF14. It shows configuring ITF‑14 specific parameters such as border type and thickness, a common requirement for packaging and logistics applications where GTIN‑14 codes must be printed with a visible frame. Developers looking for barcode creation, format customization, and image export can reference this pattern across similar symbologies. // Prompt: Generate ITF‑14 barcode encoding GTIN, applying custom frame thickness, save as PNG. -// Tags: itf-14, barcode-generation, png, aspose.barcode, aspose.drawing +// Tags: itf-14, barcode, generation, frame thickness, png, aspose.barcode, encode-types, gtin using System; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; -/// -/// Example program that generates an ITF‑14 barcode with a custom frame border -/// and saves it as a PNG image using Aspose.BarCode. -/// -class Program +namespace BarcodeExample { /// - /// Entry point of the example. Creates the barcode, configures its appearance, - /// and writes the result to a file. + /// Entry point for the ITF‑14 barcode generation example. /// - static void Main() + class Program { - // GTIN for ITF‑14 (14 numeric characters) - const string gtin = "01234567890123"; + /// + /// Generates an ITF‑14 barcode for a given GTIN, applies a custom frame border, and saves it as a PNG file. + /// + static void Main() + { + // GTIN for ITF‑14 must be exactly 14 digits + string gtin = "12345678901231"; - // Desired frame thickness in points - const float frameThickness = 5f; + // Desired frame thickness in points + float frameThickness = 5f; - // Initialize the barcode generator for ITF‑14 with the GTIN value - using (var generator = new BarcodeGenerator(EncodeTypes.ITF14, gtin)) - { - // Set the border type to a frame around the barcode - generator.Parameters.Barcode.ITF.BorderType = ITF14BorderType.Frame; + // Output file path + string outputPath = "itf14.png"; + + // Create the barcode generator for ITF‑14 using the specified GTIN + using (var generator = new BarcodeGenerator(EncodeTypes.ITF14, gtin)) + { + // Apply custom frame thickness to the ITF‑14 border + generator.Parameters.Barcode.ITF.BorderThickness.Point = frameThickness; - // Apply the custom frame thickness - generator.Parameters.Barcode.ITF.BorderThickness.Point = frameThickness; + // Set the border type to a full frame around the barcode + generator.Parameters.Barcode.ITF.BorderType = ITF14BorderType.Frame; - // Optional: define bar and background colors (black on white) - generator.Parameters.Barcode.BarColor = Color.Black; - generator.Parameters.BackColor = Color.White; + // Save the generated barcode image as a PNG file + generator.Save(outputPath, BarCodeImageFormat.Png); + } - // Save the generated barcode as a PNG file - generator.Save("itf14.png"); + // Inform the user where the barcode image was saved + Console.WriteLine($"ITF‑14 barcode saved to {outputPath}"); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-itf-barcodes-with-alternating-frame-styles-per-row-export-multi-page-pdf-collection.cs b/one-dimensional-barcode-types/generate-itf-barcodes-with-alternating-frame-styles-per-row-export-multi-page-pdf-collection.cs index 6637a5b..41be2b9 100644 --- a/one-dimensional-barcode-types/generate-itf-barcodes-with-alternating-frame-styles-per-row-export-multi-page-pdf-collection.cs +++ b/one-dimensional-barcode-types/generate-itf-barcodes-with-alternating-frame-styles-per-row-export-multi-page-pdf-collection.cs @@ -1,29 +1,37 @@ -// Title: Generate ITF14 barcodes with alternating frame styles and export as multi‑page PDF -// Description: Demonstrates creating ITF14 barcodes with different border styles per row and compiling them into a single PDF document. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to use BarcodeGenerator with ITF14 symbology, customize border styles via ITF parameters, and combine generated images into a multi‑page PDF using Aspose.Pdf. Developers often need to produce batch barcode PDFs with varied visual styles for packaging or inventory labeling. +// Title: Generate ITF-14 Barcodes with Alternating Frame Styles and Export to Multi-Page PDF +// Description: Demonstrates creating ITF-14 barcodes with different frame styles per row, embedding each barcode into its own PDF page, and saving the result as a multi-page PDF document. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to use BarcodeGenerator with ITF-14 symbology, customize border types, and combine generated images into a PDF using Aspose.Pdf. Typical use cases include batch creation of product barcodes with varied visual frames and compiling them into a single PDF for printing or distribution. Developers often need to generate multiple barcodes, adjust appearance settings, and programmatically assemble them into documents. // Prompt: Generate ITF barcodes with alternating frame styles per row, export multi‑page PDF collection. -// Tags: itf14, barcode, generation, pdf, aspose.barcode, aspose.pdf, borderstyle, image - +// Tags: itf14, barcode generation, frame style, pdf export, aspose.barcode, aspose.pdf, multi-page pdf, barcode border, c# using System; -using System.Collections.Generic; using System.IO; +using System.Collections.Generic; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Pdf; using Aspose.Pdf.Text; /// -/// Demonstrates generating ITF14 barcodes with alternating frame styles and exporting them as a multi‑page PDF. +/// Demonstrates generating ITF‑14 barcodes with alternating frame styles and exporting them to a multi‑page PDF. /// class Program { /// - /// Entry point of the example. Generates barcode images, adds them to a PDF, and saves the document. + /// Entry point that creates barcode images, embeds them into a PDF, and saves the file. /// static void Main() { - // Define border styles to alternate per row (max 4 rows for evaluation mode) - ITF14BorderType[] borderStyles = new ITF14BorderType[] + // Prepare sample data for ITF barcodes (14‑digit numeric strings) + var codeTexts = new List + { + "12345678901231", // valid ITF14 + "98765432109876", + "11111111111111", + "22222222222222" + }; + + // Define alternating frame styles for each barcode + var borderTypes = new ITF14BorderType[] { ITF14BorderType.Frame, ITF14BorderType.Bar, @@ -31,62 +39,60 @@ static void Main() ITF14BorderType.BarOut }; - // Sample 14‑digit ITF code (ITF14 requires exactly 14 digits) - const string itfCode = "12345678901231"; + // Store generated barcode images in memory streams + var barcodeStreams = new List(); - // List to hold barcode image streams until PDF is saved - List barcodeStreams = new List(); - - // Generate barcode images with alternating border styles - for (int i = 0; i < borderStyles.Length; i++) + // Generate up to four barcodes (evaluation mode limit) + for (int i = 0; i < Math.Min(codeTexts.Count, 4); i++) { - using (var generator = new BarcodeGenerator(EncodeTypes.ITF14, itfCode)) + using (var generator = new BarcodeGenerator(EncodeTypes.ITF14, codeTexts[i])) { - // Set barcode colors + // Set common appearance options generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; generator.Parameters.BackColor = Aspose.Drawing.Color.White; + generator.Parameters.Barcode.XDimension.Point = 2f; - // Apply the specific ITF border style and a modest thickness - generator.Parameters.Barcode.ITF.BorderType = borderStyles[i]; + // Apply the alternating border style for the current barcode + generator.Parameters.Barcode.ITF.BorderType = borderTypes[i % borderTypes.Length]; generator.Parameters.Barcode.ITF.BorderThickness.Point = 2f; - // Save barcode to a memory stream (PNG format) + // Render the barcode to a PNG image stored in a memory stream var ms = new MemoryStream(); generator.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; // Reset for reading by Aspose.Pdf + ms.Position = 0; // Reset stream position for later reading barcodeStreams.Add(ms); } } - // Create a PDF document and add one page per barcode row + // Create a PDF document and embed each barcode on its own page using (var pdfDoc = new Document()) { for (int i = 0; i < barcodeStreams.Count; i++) { var page = pdfDoc.Pages.Add(); - // Add the barcode image to the page, centered - var pdfImage = new Aspose.Pdf.Image + var pdfImage = new Image { ImageStream = barcodeStreams[i], FixWidth = 200, - FixHeight = 100, + FixHeight = 200, HorizontalAlignment = HorizontalAlignment.Center, - VerticalAlignment = VerticalAlignment.Center + Margin = new MarginInfo { Top = 20 } }; + page.Paragraphs.Add(pdfImage); } - // Save the multi‑page PDF + // Save the multi‑page PDF to disk const string outputPdf = "ITF_Barcodes.pdf"; pdfDoc.Save(outputPdf); - Console.WriteLine($"PDF saved to {Path.GetFullPath(outputPdf)}"); + Console.WriteLine($"PDF saved to: {Path.GetFullPath(outputPdf)}"); } - // Dispose all memory streams after PDF is saved - foreach (var stream in barcodeStreams) + // Dispose all memory streams after the PDF has been saved + foreach (var ms in barcodeStreams) { - stream.Dispose(); + ms.Dispose(); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-itf-barcodes-with-quiet-zone-coefficient-02-embed-into-existing-pdf-report.cs b/one-dimensional-barcode-types/generate-itf-barcodes-with-quiet-zone-coefficient-02-embed-into-existing-pdf-report.cs index 397cbcd..e2e1708 100644 --- a/one-dimensional-barcode-types/generate-itf-barcodes-with-quiet-zone-coefficient-02-embed-into-existing-pdf-report.cs +++ b/one-dimensional-barcode-types/generate-itf-barcodes-with-quiet-zone-coefficient-02-embed-into-existing-pdf-report.cs @@ -1,85 +1,76 @@ // Title: Generate ITF14 barcode with custom quiet zone and embed into PDF -// Description: Demonstrates creating an ITF14 barcode with a quiet zone coefficient, then inserting it into an existing PDF report. -// Category-Description: This example belongs to the Aspose.BarCode PDF integration category, illustrating how to generate barcodes (using BarcodeGenerator, EncodeTypes) and embed them into PDF documents (using Aspose.Pdf Document). Typical use cases include adding product identifiers to reports, invoices, or shipping documents. Developers often need to customize barcode appearance such as quiet zones before placing them in PDFs. +// Description: Demonstrates creating an ITF14 barcode with a quiet‑zone coefficient of 0.2, rendering it to PNG, and inserting the image into an existing PDF document. +// Category-Description: This example belongs to the Aspose.BarCode for .NET barcode generation category, illustrating how to configure barcode parameters such as size, colors, and quiet zone, and how to combine the generated image with Aspose.Pdf to produce a combined report. Typical use cases include adding product barcodes to invoices, shipping labels, or other PDF reports where precise barcode rendering is required. Developers often need to adjust quiet‑zone settings and embed barcodes programmatically, using BarcodeGenerator, BarcodeParameters, and Aspose.Pdf Document classes. // Prompt: Generate ITF barcodes with quiet zone coefficient 0.2, embed into existing PDF report. -// Tags: itf, barcode, quietzone, pdf, aspose.barcode, aspose.pdf, generation, embedding +// Tags: itf14, barcode, quietzone, pdf, aspose.barcode, aspose.pdf, image-embedding, generation using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Pdf; /// -/// Example program that generates an ITF14 barcode with a specified quiet zone coefficient -/// and embeds the resulting image into an existing PDF document. +/// Demonstrates generating an ITF14 barcode with a custom quiet zone and embedding it into a PDF. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Creates a source PDF if missing, generates the barcode, and saves the result. /// static void Main() { - // Paths for the input PDF report and the output PDF with the embedded barcode + // Define file paths for the source PDF and the output PDF string inputPdfPath = "input.pdf"; string outputPdfPath = "output.pdf"; - // Verify that the input PDF exists before proceeding + // If the source PDF does not exist, create a simple one-page document if (!File.Exists(inputPdfPath)) { - Console.WriteLine($"Input PDF not found at path: {Path.GetFullPath(inputPdfPath)}"); - return; + var emptyDoc = new Document(); + emptyDoc.Pages.Add(); + emptyDoc.Save(inputPdfPath); } - // Sample ITF14 code text (14 digits required) - string itfCodeText = "12345678901231"; - - // Desired quiet zone coefficient (the API requires an integer >= 10) - double requestedQuietZoneCoef = 0.2; - - // Create the ITF barcode generator with the specified symbology and data - using (var generator = new BarcodeGenerator(EncodeTypes.ITF14, itfCodeText)) + // Initialize an ITF14 barcode generator with a 14‑digit value + using (var generator = new BarcodeGenerator(EncodeTypes.ITF14, "12345678901231")) { - // Set the quiet zone coefficient only if it meets the API's minimum requirement - if (requestedQuietZoneCoef >= 10) - { - generator.Parameters.Barcode.ITF.QuietZoneCoef = (int)requestedQuietZoneCoef; - } - else - { - Console.WriteLine("Quiet zone coefficient is less than the minimum allowed (10). Skipping setting this property."); - } + // Configure basic appearance settings + generator.Parameters.AutoSizeMode = AutoSizeMode.None; + generator.Parameters.Barcode.BarHeight.Point = 50f; + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; - // Generate the barcode image into a memory stream (PNG format) + // Calculate quiet zone based on the X‑dimension (0.2 * XDimension) + float quietZone = generator.Parameters.Barcode.XDimension.Point * 0.2f; + generator.Parameters.Barcode.Padding.Left.Point = quietZone; + generator.Parameters.Barcode.Padding.Right.Point = quietZone; + generator.Parameters.Barcode.Padding.Top.Point = quietZone; + generator.Parameters.Barcode.Padding.Bottom.Point = quietZone; + + // Render the barcode 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 - // Load the existing PDF document + // Load the existing PDF and embed the barcode image on the first page using (var pdfDoc = new Document(inputPdfPath)) { - // Add a new page to place the barcode (or use an existing page as needed) - var page = pdfDoc.Pages.Add(); - - // Create an Aspose.Pdf.Image from the barcode stream + var page = pdfDoc.Pages[1]; var pdfImage = new Aspose.Pdf.Image { ImageStream = barcodeStream, - FixWidth = 200.0, // Adjust width as required - FixHeight = 100.0 // Adjust height as required + FixWidth = 150, + FixHeight = 50, + HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center, + VerticalAlignment = Aspose.Pdf.VerticalAlignment.Center, + Margin = new Aspose.Pdf.MarginInfo { Top = 10 } }; - - // Add the image to the page's paragraph collection page.Paragraphs.Add(pdfImage); - - // Save the modified PDF to the output path pdfDoc.Save(outputPdfPath); } } } - - Console.WriteLine($"Barcode embedded successfully. Output saved to: {Path.GetFullPath(outputPdfPath)}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-series-of-codabar-barcodes-with-alternating-start-symbols-and-b-saving-each-as-separate-jpeg.cs b/one-dimensional-barcode-types/generate-series-of-codabar-barcodes-with-alternating-start-symbols-and-b-saving-each-as-separate-jpeg.cs index 16f8bfe..9d7ddce 100644 --- a/one-dimensional-barcode-types/generate-series-of-codabar-barcodes-with-alternating-start-symbols-and-b-saving-each-as-separate-jpeg.cs +++ b/one-dimensional-barcode-types/generate-series-of-codabar-barcodes-with-alternating-start-symbols-and-b-saving-each-as-separate-jpeg.cs @@ -1,8 +1,8 @@ -// Title: Generate Codabar barcodes with alternating start symbols -// Description: Demonstrates creating multiple Codabar barcodes using start symbols A and B, each saved as a JPEG file. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure Codabar symbology with specific start/stop symbols, set barcode data, and export images. It uses BarcodeGenerator, EncodeTypes, CodabarSymbol, and BarCodeImageFormat classes—common tasks for developers needing custom barcode creation for labeling, inventory, or point‑of‑sale systems. +// Title: Generate multiple Codabar barcodes with alternating start symbols +// Description: Demonstrates how to create a series of Codabar barcodes, alternating the start/stop symbols between A and B, and save each as a JPEG image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and Codabar parameters. Typical use cases include batch creation of barcodes for inventory, shipping, or point‑of‑sale systems where different start symbols are required. Developers often need to automate image output in common formats such as JPEG. // Prompt: Generate a series of Codabar barcodes with alternating start symbols A and B, saving each as a separate JPEG. -// Tags: codabar, barcode generation, jpeg output, aspose.barcode, encode types, startstop symbols +// Tags: codabar, generation, jpeg, aspose.barcode, barcodegenerator using System; using System.IO; @@ -10,55 +10,52 @@ using Aspose.BarCode.Generation; /// -/// Example program that generates a series of Codabar barcodes with alternating start/stop symbols -/// (A for even indices, B for odd indices) and saves each barcode as a separate JPEG image. +/// Program that generates a set of Codabar barcodes with alternating start symbols and saves them as JPEG files. /// class Program { /// - /// Entry point of the application. Creates the output directory, iterates to generate the - /// requested number of barcodes, configures the Codabar start/stop symbols, and saves each - /// image as a JPEG file. + /// Entry point. Creates the output folder, generates the barcodes, and writes status messages to the console. /// static void Main() { - // Sample data to encode (Codabar allows digits and some symbols) - const string data = "123456"; - - // Number of barcodes to generate - const int count = 5; - - // Ensure output directory exists - string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "CodabarOutputs"); - if (!Directory.Exists(outputDir)) + // Determine the folder where barcode images will be stored + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "CodabarBarcodes"); + if (!Directory.Exists(outputFolder)) { - Directory.CreateDirectory(outputDir); + // Create the folder if it does not already exist + Directory.CreateDirectory(outputFolder); } - // Generate each barcode with alternating start/stop symbols + // Define how many barcode images to generate + int count = 6; // example count + + // Loop to generate each barcode for (int i = 0; i < count; i++) { - // Choose start/stop symbol: A for even index, B for odd index - CodabarSymbol startStopSymbol = (i % 2 == 0) ? CodabarSymbol.A : CodabarSymbol.B; + // Choose start/stop symbol: A for even indexes, B for odd indexes + CodabarSymbol startSymbol = (i % 2 == 0) ? CodabarSymbol.A : CodabarSymbol.B; - // Create a generator for Codabar symbology - using (var generator = new BarcodeGenerator(EncodeTypes.Codabar)) + // Initialize a Codabar barcode generator + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Codabar)) { - // Apply the selected start and stop symbols - generator.Parameters.Barcode.Codabar.StartSymbol = startStopSymbol; - generator.Parameters.Barcode.Codabar.StopSymbol = startStopSymbol; + // Set the data to encode (digits only; start/stop symbols are set via parameters) + generator.CodeText = "123456"; - // Assign the data to encode - generator.CodeText = data; + // Apply the selected start and stop symbols + generator.Parameters.Barcode.Codabar.StartSymbol = startSymbol; + generator.Parameters.Barcode.Codabar.StopSymbol = startSymbol; - // Build the output file name (e.g., codabar_A_1.jpg) - string fileName = $"codabar_{startStopSymbol}_{i + 1}.jpg"; - string filePath = Path.Combine(outputDir, fileName); + // Build a unique file name that includes the index and start symbol + string fileName = $"codabar_{i + 1}_{startSymbol}.jpg"; + string filePath = Path.Combine(outputFolder, fileName); - // Save the barcode as a JPEG image + // Save the generated barcode as a JPEG image generator.Save(filePath, BarCodeImageFormat.Jpeg); Console.WriteLine($"Saved {filePath}"); } } + + Console.WriteLine("Barcode generation completed."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/generate-series-of-databar-expanded-stacked-barcodes-with-varying-column-counts-compile-single-pdf-document.cs b/one-dimensional-barcode-types/generate-series-of-databar-expanded-stacked-barcodes-with-varying-column-counts-compile-single-pdf-document.cs index 44e89ae..ffe3deb 100644 --- a/one-dimensional-barcode-types/generate-series-of-databar-expanded-stacked-barcodes-with-varying-column-counts-compile-single-pdf-document.cs +++ b/one-dimensional-barcode-types/generate-series-of-databar-expanded-stacked-barcodes-with-varying-column-counts-compile-single-pdf-document.cs @@ -1,19 +1,18 @@ // Title: Generate DataBar Expanded Stacked barcodes and compile into a PDF -// Description: Demonstrates creating DataBar Expanded Stacked barcodes with different column counts and placing them into a single PDF document. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure DataBar symbology, adjust column counts, render barcodes to images, and embed them into an Aspose.Pdf document. Developers often need to produce multiple barcodes in one PDF for reports, labels, or batch processing, using BarcodeGenerator, BarcodeParameters, and Pdf Document classes. +// Description: Demonstrates creating DataBar Expanded Stacked barcodes with different column counts and combining them into a single PDF document. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to configure DataBar symbology parameters, render barcodes to image streams, and embed them into an Aspose.Pdf document. Developers working with product identification, GS1 DataBar, or multi‑column stacked barcodes can use these APIs to produce printable PDFs for inventory, labeling, or reporting scenarios. // Prompt: Generate series of DataBar Expanded Stacked barcodes with varying column counts, compile single PDF document. -// Tags: databar, expandedstacked, barcode, pdf, aspnet, aspose.barcode, aspose.pdf, generation, image, columns +// Tags: databar, expandedstacked, barcode, pdf, aspnet, aspose.barcode, aspose.pdf, image, generation using System; using System.IO; using System.Collections.Generic; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Pdf; /// -/// Example program that generates a series of DataBar Expanded Stacked barcodes with varying column counts -/// and compiles them into a single PDF document. +/// Example program that generates a set of DataBar Expanded Stacked barcodes with varying column counts +/// and assembles them into a single PDF document. /// class Program { @@ -22,69 +21,58 @@ class Program /// static void Main() { - // Define the output PDF file name - string outputPdf = "DataBarExpandedStacked.pdf"; + // Prepare a collection to hold the generated barcode image streams. + List barcodeStreams = new List(); - // List of column counts to apply to each barcode instance - List columnCounts = new List { 2, 3, 4, 5 }; - - // Create a new PDF document using Aspose.Pdf - using (var pdfDoc = new Document()) + // Generate DataBar Expanded Stacked barcodes for column counts 1 through 4. + for (int columns = 1; columns <= 4; columns++) { - // Add a single page (evaluation mode permits up to 4 images) - var page = pdfDoc.Pages.Add(); - - // Determine cell dimensions for a 2x2 grid layout on the page - double pageWidth = page.PageInfo.Width; - double pageHeight = page.PageInfo.Height; - double cellWidth = pageWidth / 2; - double cellHeight = pageHeight / 2; - - int index = 0; - foreach (int cols in columnCounts) + // Initialize a barcode generator for the DatabarExpandedStacked symbology. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.DatabarExpandedStacked, "(01)12345678901231")) { - // Respect evaluation restriction: maximum of 4 barcodes per document - if (index >= 4) break; + // Configure visual appearance: black bars on a white background. + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + + // Set the specific number of columns for this barcode instance. + generator.Parameters.Barcode.DataBar.Columns = columns; - // Initialize barcode generator for DataBar Expanded Stacked symbology - using (var generator = new BarcodeGenerator(EncodeTypes.DatabarExpandedStacked, "(01)01234567890123")) - { - // Set the specific column count for the DataBar barcode - generator.Parameters.Barcode.DataBar.Columns = cols; + // Render the barcode to a memory stream in PNG format. + MemoryStream ms = new MemoryStream(); + generator.Save(ms, BarCodeImageFormat.Png); + ms.Position = 0; // Reset stream position for subsequent reading. + barcodeStreams.Add(ms); + } + } - // Optional visual customizations - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; - generator.Parameters.BackColor = Aspose.Drawing.Color.White; - generator.Parameters.Barcode.XDimension.Point = 2f; + // Create a new PDF document to hold the barcode images. + Document pdfDoc = new Document(); - // Render the barcode to a memory stream in PNG format - using (var ms = new MemoryStream()) - { - generator.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; + // Add a separate page for each barcode image (up to four pages). + for (int i = 0; i < barcodeStreams.Count; i++) + { + Page page = pdfDoc.Pages.Add(); - // Calculate the placement rectangle for the current grid cell - int row = index / 2; - int col = index % 2; - double llx = col * cellWidth; - double lly = pageHeight - ((row + 1) * cellHeight); - double urx = llx + cellWidth; - double ury = lly + cellHeight; - var rect = new Aspose.Pdf.Rectangle(llx, lly, urx, ury); + // Determine the full page dimensions. + double pageWidth = page.PageInfo.Width; + double pageHeight = page.PageInfo.Height; + Aspose.Pdf.Rectangle rect = new Aspose.Pdf.Rectangle(0, 0, pageWidth, pageHeight); - // Add the barcode image to the PDF page within the calculated rectangle - page.AddImage(ms, rect, (int)cellWidth, (int)cellHeight, true); - } - } + // Insert the barcode image onto the page. + // Width and height are set to 300x150 pixels; adjust as needed. + page.AddImage(barcodeStreams[i], rect, 300, 150, true); + } - index++; - } + // Save the assembled PDF to disk. + string outputPdfPath = "DataBarExpandedStacked.pdf"; + pdfDoc.Save(outputPdfPath); - // Save the assembled PDF document to disk - pdfDoc.Save(outputPdf); + // Clean up all memory streams to release resources. + foreach (var ms in barcodeStreams) + { + ms.Dispose(); } - // Output the full path of the generated PDF for user reference - Console.WriteLine($"PDF generated: {Path.GetFullPath(outputPdf)}"); + Console.WriteLine("PDF generated: " + Path.GetFullPath(outputPdfPath)); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/implement-caching-for-generated-databar-barcode-images-to-improve-high-traffic-web-performance.cs b/one-dimensional-barcode-types/implement-caching-for-generated-databar-barcode-images-to-improve-high-traffic-web-performance.cs index 356d09b..85ac80b 100644 --- a/one-dimensional-barcode-types/implement-caching-for-generated-databar-barcode-images-to-improve-high-traffic-web-performance.cs +++ b/one-dimensional-barcode-types/implement-caching-for-generated-databar-barcode-images-to-improve-high-traffic-web-performance.cs @@ -1,99 +1,95 @@ // Title: DataBar Barcode Image Caching Example -// Description: Demonstrates generating DataBar barcodes with in‑memory caching to reduce redundant image creation in high‑traffic scenarios. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on DataBar symbologies. It showcases the use of BarcodeGenerator, encoding types, and image saving APIs, illustrating typical patterns for developers who need to generate barcode images repeatedly while optimizing performance through caching. Suitable for web services, batch processing, or any application requiring fast repeated barcode rendering. +// Description: Demonstrates generating DataBar Expanded and Limited barcodes and caching the resulting PNG images in memory to avoid redundant generation. +// Category-Description: Shows how to use Aspose.BarCode's BarcodeGenerator with EncodeTypes to create DataBar symbologies, configure barcode parameters, and implement a simple in‑memory cache for high‑traffic scenarios. This example belongs to the barcode generation and image handling category, illustrating typical use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat for web applications that need fast repeated barcode rendering. // Prompt: Implement caching for generated DataBar barcode images to improve high‑traffic web performance. -// Tags: databar, barcode, caching, image generation, aspnet, aspose.barcode, png +// Tags: databar, barcode generation, caching, png, aspose.barcode, encode types, web performance using System; -using System.Collections.Generic; using System.IO; +using System.Collections.Generic; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Provides an example of generating DataBar barcode images with in‑memory caching to improve performance. +/// Demonstrates generating DataBar barcodes and caching the PNG image bytes in memory. /// class Program { - // Simple in‑memory cache: key = "EncodeType|CodeText", value = PNG bytes - private static readonly Dictionary _cache = new Dictionary(); + // Simple in‑memory cache: key = symbology|codetext, value = PNG bytes + private static readonly Dictionary _cache = new Dictionary(StringComparer.OrdinalIgnoreCase); /// - /// Generates a DataBar barcode image or returns a cached image if it already exists. + /// Entry point of the example. Generates barcodes for a set of symbologies and code texts, + /// writes image sizes to the console, and saves the PNG files to disk. /// - /// The text to encode in the barcode. - /// The DataBar symbology to use. - /// Byte array containing the PNG image. - private static byte[] GetBarcodeImage(string codeText, BaseEncodeType encodeType) + static void Main() { - // Build a unique cache key based on symbology and text - string key = $"{encodeType}|{codeText}"; - - // Return cached bytes if present - if (_cache.TryGetValue(key, out byte[] cachedBytes)) - { - Console.WriteLine($"Cache hit for {key}"); - return cachedBytes; - } + // Example usage: generate DataBar Expanded and Limited barcodes + string[] symbologies = { "DatabarExpanded", "DatabarLimited" }; + string[] codeTexts = { "(01)12345678901231", "(01)08888888888888" }; - // Cache miss – generate a new barcode image - Console.WriteLine($"Cache miss for {key}, generating image..."); - using (var generator = new BarcodeGenerator(encodeType, codeText)) + foreach (var sym in symbologies) { - // Use interpolation auto‑size mode for consistent image dimensions - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; - - // Save the generated image into a memory stream - using (var ms = new MemoryStream()) + foreach (var text in codeTexts) { - generator.Save(ms, BarCodeImageFormat.Png); - byte[] imageBytes = ms.ToArray(); + // Retrieve barcode image bytes, using cache when possible + byte[] imageBytes = GetBarcodeImage(sym, text); - // Store the generated bytes in the cache for future reuse - _cache[key] = imageBytes; - return imageBytes; + // Output image size for demonstration purposes + Console.WriteLine($"{sym} | {text} => Image bytes: {imageBytes.Length}"); + + // Save the image to a file (in a real web app this would be sent to the client) + string fileName = $"{sym}_{text.Replace('(', '_').Replace(')', '_')}.png"; + File.WriteAllBytes(fileName, imageBytes); } } } - /// - /// Entry point. Generates sample DataBar barcodes, saves them, and demonstrates cache reuse. - /// - static void Main() + // Returns PNG image bytes for the requested barcode, using cache when possible + private static byte[] GetBarcodeImage(string symbologyName, string codeText) { - // Define sample DataBar types with appropriate code texts - var samples = new List<(BaseEncodeType type, string text)> - { - (EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"), - (EncodeTypes.DatabarLimited, "(01)08888888888888"), - (EncodeTypes.DatabarStacked, "(01)12345678901231"), - (EncodeTypes.DatabarExpanded, "(01)12345678901231"), - (EncodeTypes.DatabarStackedOmniDirectional, "(01)12345678901231") - }; + string cacheKey = $"{symbologyName}|{codeText}"; - // Ensure the output directory exists - string outputDir = "Barcodes"; - if (!Directory.Exists(outputDir)) + // Check if the image is already cached + if (_cache.TryGetValue(cacheKey, out byte[] cachedBytes)) { - Directory.CreateDirectory(outputDir); + // Cache hit + Console.WriteLine($"Cache hit for key: {cacheKey}"); + return cachedBytes; } - // Generate each barcode, save to file, and output status - foreach (var (type, text) in samples) + // Resolve symbology name to BaseEncodeType via reflection + var field = typeof(EncodeTypes).GetField(symbologyName); + if (field == null) { - byte[] pngBytes = GetBarcodeImage(text, type); - string fileName = $"{type}_{text.Replace('(', '_').Replace(')', '_').Replace(' ', '_')}.png"; - string filePath = Path.Combine(outputDir, fileName); - File.WriteAllBytes(filePath, pngBytes); - Console.WriteLine($"Saved barcode to {filePath}"); + Console.WriteLine($"Unknown symbology: {symbologyName}"); + return Array.Empty(); } + BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null); - // Demonstrate cache reuse by requesting the first barcode again - byte[] cachedBytes = GetBarcodeImage(samples[0].text, samples[0].type); - Console.WriteLine($"Retrieved cached image of size {cachedBytes.Length} bytes."); + // Create generator and configure basic parameters + using (var generator = new BarcodeGenerator(encodeType, codeText)) + { + // Set XDimension and padding for consistent size + 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; + + // Generate image into a memory stream as PNG + using (var ms = new MemoryStream()) + { + generator.Save(ms, BarCodeImageFormat.Png); + byte[] imageBytes = ms.ToArray(); + + // Store in cache for future requests + _cache[cacheKey] = imageBytes; + Console.WriteLine($"Cache miss – generated and cached key: {cacheKey}"); + return imageBytes; + } + } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/implement-error-handling-for-code-16k-aspect-ratios-below-eight-log-descriptive-messages.cs b/one-dimensional-barcode-types/implement-error-handling-for-code-16k-aspect-ratios-below-eight-log-descriptive-messages.cs index 1ddab93..a7bfb93 100644 --- a/one-dimensional-barcode-types/implement-error-handling-for-code-16k-aspect-ratios-below-eight-log-descriptive-messages.cs +++ b/one-dimensional-barcode-types/implement-error-handling-for-code-16k-aspect-ratios-below-eight-log-descriptive-messages.cs @@ -1,69 +1,61 @@ -// Title: Code16K Barcode Generation with Aspect Ratio Validation -// Description: Demonstrates generating Code 16K barcodes while validating that the aspect ratio meets the minimum requirement of eight. -// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use the BarcodeGenerator class with EncodeTypes.Code16K. It illustrates typical use cases such as setting barcode parameters, handling invalid input values, and saving the output as PNG images. Developers working with barcode creation often need to enforce symbology‑specific constraints and log informative messages for troubleshooting. -/// Prompt: Implement error handling for Code 16K aspect ratios below eight, log descriptive messages. -/// Tags: barcode symbology, generation, png, code16k, aspose.barcode +// Title: Generate Code 16K barcode with aspect‑ratio validation and error handling +// Description: This example creates a Code 16K barcode, ensures the aspect ratio meets the minimum requirement, and saves the image as PNG. +// Category-Description: Demonstrates Aspose.BarCode barcode generation focusing on Code16K symbology. It covers using BarcodeGenerator, setting symbology‑specific parameters (AspectRatio), handling invalid input, and catching BarCodeException. Ideal for developers needing to produce high‑density linear barcodes with proper validation and logging. +// Prompt: Implement error handling for Code 16K aspect ratios below eight, log descriptive messages. +// Tags: barcode, code16k, aspectratio, errorhandling, generation, png, aspose.barcode, aspnet using System; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Generates Code16K barcodes for a set of aspect ratios, skipping those below the allowed minimum -/// and logging appropriate messages. Demonstrates error handling and parameter configuration using -/// Aspose.BarCode's . +/// Demonstrates generating a Code 16K barcode with aspect‑ratio validation and error handling. /// class Program { /// - /// Entry point of the example. Iterates over predefined aspect ratios, validates them, - /// generates barcodes when valid, and logs the process. + /// Entry point of the example. Validates aspect ratio, generates the barcode, and saves it as PNG. /// static void Main() { - // Sample aspect ratios to test, including values below and above the threshold of 8 - float[] aspectRatios = { 5.5f, 7.9f, 8.0f, 10.2f }; + // Desired aspect ratio (example value). Change this value to test different scenarios. + float requestedAspectRatio = 5.5f; - // Process each aspect ratio individually - foreach (float ratio in aspectRatios) + // Validate aspect ratio for Code16K (minimum allowed is 8). Adjust if below the threshold. + if (requestedAspectRatio < 8f) { - // Validate aspect ratio for Code16K; values below 8 are considered invalid - if (ratio < 8f) - { - Console.WriteLine($"[Warning] Aspect ratio {ratio} is below the minimum allowed (8). Skipping barcode generation."); - continue; // Skip to the next ratio - } + Console.WriteLine($"[Warning] Code16K aspect ratio {requestedAspectRatio} is below the minimum of 8. Adjusting to 8."); + requestedAspectRatio = 8f; + } - // Create and configure the barcode generator inside a using block to ensure disposal - using (var generator = new BarcodeGenerator(EncodeTypes.Code16K)) + try + { + // Create a Code16K barcode generator with sample code text. + using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, "1234567890")) { - try - { - // Set a sample codetext; Code16K accepts any string - generator.CodeText = "SampleCode16K"; - - // Apply the validated aspect ratio - generator.Parameters.Barcode.Code16K.AspectRatio = ratio; - - // Optional: set image size for consistency - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; + // Apply the (validated) aspect ratio to the Code16K parameters. + generator.Parameters.Barcode.Code16K.AspectRatio = requestedAspectRatio; - // Save the barcode image to a file named with the current aspect ratio - string fileName = $"Code16K_Aspect_{ratio}.png"; - generator.Save(fileName); - - Console.WriteLine($"[Info] Generated Code16K barcode with aspect ratio {ratio} saved as '{fileName}'."); - } - catch (Exception ex) + // Generate the barcode image. + using (Aspose.Drawing.Bitmap image = generator.GenerateBarCodeImage()) { - // Log any unexpected errors during generation - Console.WriteLine($"[Error] Failed to generate barcode with aspect ratio {ratio}: {ex.Message}"); + // Define the output file path and save the image as PNG. + string outputPath = "code16k.png"; + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode image saved to '{outputPath}'."); } } } - - // Indicate completion of the processing loop - Console.WriteLine("Barcode processing completed."); + catch (BarCodeException ex) + { + // Handle barcode‑specific errors. + Console.WriteLine($"[Error] Barcode generation failed: {ex.Message}"); + } + catch (Exception ex) + { + // Handle any other unexpected errors. + Console.WriteLine($"[Error] Unexpected exception: {ex.Message}"); + } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/implement-feature-rotating-generated-databar-barcodes-90-degrees-before-exporting-png.cs b/one-dimensional-barcode-types/implement-feature-rotating-generated-databar-barcodes-90-degrees-before-exporting-png.cs index cfb9df4..e4cfdb5 100644 --- a/one-dimensional-barcode-types/implement-feature-rotating-generated-databar-barcodes-90-degrees-before-exporting-png.cs +++ b/one-dimensional-barcode-types/implement-feature-rotating-generated-databar-barcodes-90-degrees-before-exporting-png.cs @@ -1,48 +1,62 @@ -// Title: Rotate DataBar barcodes 90 degrees and export as PNG -// Description: Demonstrates generating DataBar barcodes, rotating them 90° clockwise, and saving the images as PNG files. -// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to create DataBar symbologies, apply rotation via Parameters.RotationAngle, and export to common image formats. Developers often need to adjust barcode orientation for label layouts or scanning requirements, making this pattern useful for printing and UI scenarios. +// Title: Rotating DataBar Barcodes 90 Degrees and Exporting as PNG +// Description: Demonstrates how to generate various DataBar symbologies, rotate each barcode image by 90 degrees, and save them as PNG files. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to create and manipulate barcode images. Typical use cases include preparing rotated barcodes for label layouts or printing requirements. Developers often need to adjust orientation before exporting to image formats. // Prompt: Implement feature rotating generated DataBar barcodes 90 degrees before exporting PNG. -// Tags: databar, rotation, png, barcode generation, aspose.barcode, aspose.drawing, image export +// Tags: databar, rotation, png, aspose.barcode, generation using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Generates a set of DataBar barcodes, rotates each 90 degrees, and saves them as PNG images. +/// Generates DataBar barcodes, rotates them 90 degrees, and saves them as PNG files. /// class Program { /// - /// Entry point of the example. Creates, rotates, and saves DataBar barcodes. + /// Entry point that creates the output folder, generates rotated DataBar barcodes, and writes them to disk. /// static void Main() { - // Define an array of barcode configurations: type, data, and output file name. - var barcodes = new (BaseEncodeType type, string codeText, string fileName)[] + // Determine the output folder path relative to the current directory + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "DataBarOutputs"); + + // Ensure the output directory exists + if (!Directory.Exists(outputFolder)) + { + Directory.CreateDirectory(outputFolder); + } + + // Define a collection of DataBar symbologies with sample code texts and target file names + var dataBarSamples = new (BaseEncodeType type, string codeText, string fileName)[] { - (EncodeTypes.DatabarOmniDirectional, "(01)12345678901231", "DatabarOmniDirectional.png"), (EncodeTypes.DatabarLimited, "(01)08888888888888", "DatabarLimited.png"), - (EncodeTypes.DatabarExpanded, "(01)12345678901231(10)ABCD", "DatabarExpanded.png") + (EncodeTypes.DatabarOmniDirectional, "(01)12345678901231", "DatabarOmniDirectional.png"), + (EncodeTypes.DatabarExpanded, "(01)12345678901231(21)12345", "DatabarExpanded.png"), + (EncodeTypes.DatabarStacked, "(01)12345678901231", "DatabarStacked.png"), + (EncodeTypes.DatabarStackedOmniDirectional, "(01)12345678901231", "DatabarStackedOmniDirectional.png") }; - // Iterate over each configuration, generate the barcode, rotate it, and save as PNG. - foreach (var (type, codeText, fileName) in barcodes) + // Iterate over each sample, generate, rotate, and save the barcode + foreach (var sample in dataBarSamples) { - // Create a BarcodeGenerator for the specified DataBar type and data. - using (var generator = new BarcodeGenerator(type, codeText)) + // Create a BarcodeGenerator for the specific DataBar type and code text + using (var generator = new BarcodeGenerator(sample.type, sample.codeText)) { - // Apply a 90-degree rotation to the generated barcode image. + // Set rotation angle to 90 degrees (clockwise) generator.Parameters.RotationAngle = 90f; - // Export the rotated barcode to a PNG file. - generator.Save(fileName, BarCodeImageFormat.Png); + // Build the full output file path + string outputPath = Path.Combine(outputFolder, sample.fileName); - // Inform the user that the file has been saved. - Console.WriteLine($"Saved rotated barcode to {fileName}"); + // Save the rotated barcode image as a PNG file + generator.Save(outputPath, BarCodeImageFormat.Png); } } + + // Inform the user that processing is complete + Console.WriteLine("DataBar barcodes generated and rotated successfully."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/implement-ui-allowing-users-to-set-quiet-zone-left-and-right-coefficients-preview-barcode.cs b/one-dimensional-barcode-types/implement-ui-allowing-users-to-set-quiet-zone-left-and-right-coefficients-preview-barcode.cs index 4a73e23..c1d6711 100644 --- a/one-dimensional-barcode-types/implement-ui-allowing-users-to-set-quiet-zone-left-and-right-coefficients-preview-barcode.cs +++ b/one-dimensional-barcode-types/implement-ui-allowing-users-to-set-quiet-zone-left-and-right-coefficients-preview-barcode.cs @@ -1,61 +1,80 @@ -// Title: Code16K Barcode Quiet Zone Coefficients Demo -// Description: Demonstrates setting left and right quiet zone coefficients for a Code16K barcode and generating a PNG preview. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to customize barcode parameters such as quiet zone coefficients using the BarcodeGenerator class. Typical use cases include fine‑tuning barcode appearance for scanning reliability and layout requirements. Developers often need to adjust these settings when integrating barcodes into UI applications or printed materials. +// Title: Generate Code16K Barcode with Configurable Quiet Zone Coefficients +// Description: Demonstrates how to create a Code16K barcode using Aspose.BarCode, allowing the left and right quiet zone coefficients to be set via command‑line arguments. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category. It shows how to configure barcode parameters such as quiet zone coefficients and X‑dimension using the BarcodeGenerator class. Typical use cases include customizing barcode appearance for printing or display, where developers need to control margins and module size. // Prompt: Implement UI allowing users to set quiet zone left and right coefficients, preview barcode. -// Tags: code16k, quietzone, barcode, generation, png, aspose.barcode, ui +// Tags: barcode, code16k, quiet zone, generation, aspose.barcode, aspose.drawing, console, command-line using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Demonstrates how to configure quiet zone coefficients for a Code16K barcode -/// and generate a preview image using Aspose.BarCode. +/// Program demonstrating generation of a Code16K barcode with adjustable quiet zone coefficients. /// class Program { /// - /// Entry point of the console application. - /// Accepts optional command‑line arguments for left and right quiet zone coefficients, - /// applies them to the barcode generator, and saves the resulting PNG image. + /// Entry point. Parses optional command‑line arguments for quiet zone left and right coefficients, + /// generates the barcode, and saves it as a PNG file. /// - /// - /// Optional arguments: args[0] = left quiet zone coefficient, - /// args[1] = right quiet zone coefficient. - /// - static void Main(string[] args) + static void Main() { - // Default quiet zone coefficients (match Aspose defaults) - int leftCoef = 10; // left quiet zone coefficient - int rightCoef = 1; // right quiet zone coefficient + // Simulate a UI by accepting optional command‑line arguments. + // If not provided, default safe values are used. + int quietZoneLeft = 10; // minimum allowed value for left quiet zone + int quietZoneRight = 1; // minimum allowed value for right quiet zone - // Parse optional command‑line arguments: first = left, second = right - if (args.Length > 0 && int.TryParse(args[0], out int parsedLeft) && parsedLeft >= 0) - leftCoef = parsedLeft; - if (args.Length > 1 && int.TryParse(args[1], out int parsedRight) && parsedRight >= 0) - rightCoef = parsedRight; + // Parse command‑line arguments: first = left coefficient, second = right coefficient + string[] args = Environment.GetCommandLineArgs(); + if (args.Length > 1 && int.TryParse(args[1], out int left) && left >= 10) + quietZoneLeft = left; + if (args.Length > 2 && int.TryParse(args[2], out int right) && right >= 1) + quietZoneRight = right; - // Define output file path for the generated barcode image - string outputPath = "code16k.png"; + // Determine output file path in the current directory + string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "code16k.png"); - // Create a BarcodeGenerator for the Code16K symbology with sample data - using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, "1234567890")) + try { - // Apply the user‑specified quiet zone coefficients - generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = leftCoef; - generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = rightCoef; + // Create a barcode generator for Code16K symbology + using (var generator = new BarcodeGenerator(EncodeTypes.Code16K)) + { + // Set the data to encode + generator.CodeText = "12345678901234567890"; - // Let Aspose calculate optimal image dimensions - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; + // Apply quiet zone coefficients (must satisfy minimum constraints) + generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = quietZoneLeft; + generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = quietZoneRight; - // Save the generated barcode as a PNG file - generator.Save(outputPath, BarCodeImageFormat.Png); - } + // Optionally adjust module size for better visibility + generator.Parameters.Barcode.XDimension.Point = 2f; // 2 points per module + + // Generate the barcode image (Aspose.Drawing.Bitmap) + using (Bitmap bitmap = generator.GenerateBarCodeImage()) + { + // Save the bitmap to a PNG file using Aspose.Drawing.Imaging.ImageFormat + bitmap.Save(outputPath, ImageFormat.Png); + } + } - // Inform the user about the generated barcode and its location - Console.WriteLine($"Code16K barcode generated with QuietZoneLeftCoef={leftCoef}, QuietZoneRightCoef={rightCoef}"); - Console.WriteLine($"Image saved to: {Path.GetFullPath(outputPath)}"); + // Inform the user about successful generation + Console.WriteLine("Barcode generated successfully:"); + Console.WriteLine($" QuietZoneLeftCoef = {quietZoneLeft}"); + Console.WriteLine($" QuietZoneRightCoef = {quietZoneRight}"); + Console.WriteLine($" Saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + // Handles cases where quiet zone values are out of allowed range + Console.WriteLine($"Error: {ex.Message}"); + } + catch (Exception ex) + { + // General error handling + Console.WriteLine($"Unexpected error: {ex.Message}"); + } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/instantiate-barcodebuilder-set-codetext-select-codabar-symbology-and-render-to-png-file.cs b/one-dimensional-barcode-types/instantiate-barcodebuilder-set-codetext-select-codabar-symbology-and-render-to-png-file.cs index e038504..f8ad921 100644 --- a/one-dimensional-barcode-types/instantiate-barcodebuilder-set-codetext-select-codabar-symbology-and-render-to-png-file.cs +++ b/one-dimensional-barcode-types/instantiate-barcodebuilder-set-codetext-select-codabar-symbology-and-render-to-png-file.cs @@ -1,40 +1,36 @@ -// Title: Generate Codabar barcode and save as PNG -// Description: Demonstrates creating a Codabar barcode using Aspose.BarCode, setting the code text, and saving it as a PNG image. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator with EncodeTypes.Codabar. It shows typical steps such as initializing the generator, configuring CodeText, and exporting the barcode to a common image format. Developers working with barcode creation, especially for Codabar symbology in retail or logistics, can reference this pattern for quick implementation. +// Title: Generate Codabar Barcode and Save as PNG +// Description: Demonstrates how to create a Codabar barcode using Aspose.BarCode, set the code text, and save the image as a PNG file. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of the BarcodeGenerator class with EncodeTypes to produce barcodes. Typical scenarios include creating shipping labels, inventory tags, or any application requiring Codabar symbology. Developers often need to set the encoded text, choose a symbology, and export the result to common image formats such as PNG. // Prompt: Instantiate BarCodeBuilder, set CodeText, select Codabar symbology, and render to PNG file. -// Tags: barcode, codabar, generation, png, aspose.barcode, encode types +// Tags: barcode, codabar, generation, png, aspose.barcode, barcodegenerator, encodetypes using System; -using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Example program that generates a Codabar barcode and saves it as a PNG file. +/// Example program that generates a Codabar barcode and saves it as a PNG image. /// class Program { /// - /// Entry point of the application. Creates a BarcodeGenerator for Codabar, - /// sets the encoded text, and writes the barcode image to disk. + /// Entry point of the application. Creates a BarcodeGenerator, configures it, and writes the barcode to disk. /// static void Main() { - // Define the output file path for the generated barcode image. + // Define the output file path for the generated PNG image string outputPath = "codabar.png"; - // Initialize a BarcodeGenerator for the Codabar symbology. - // The using statement ensures proper disposal of resources. - using (var generator = new BarcodeGenerator(EncodeTypes.Codabar)) + // Initialize the barcode generator with the Codabar symbology + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Codabar)) { - // Set the text to be encoded. - // Codabar requires start/stop symbols (e.g., 'A' and 'A') surrounding the data. + // Assign the text that will be encoded in the barcode generator.CodeText = "A123456A"; - // Save the generated barcode as a PNG file at the specified path. + // Save the generated barcode image to the specified path in PNG format generator.Save(outputPath); } - // Inform the user that the barcode has been saved. - Console.WriteLine($"Codabar barcode saved to {outputPath}"); + // Inform the user that the barcode has been successfully saved + Console.WriteLine($"Barcode saved to {outputPath}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/iterate-through-list-of-product-codes-generate-codabar-barcodes-and-store-each-in-zip-archive.cs b/one-dimensional-barcode-types/iterate-through-list-of-product-codes-generate-codabar-barcodes-and-store-each-in-zip-archive.cs index d7e092b..672583f 100644 --- a/one-dimensional-barcode-types/iterate-through-list-of-product-codes-generate-codabar-barcodes-and-store-each-in-zip-archive.cs +++ b/one-dimensional-barcode-types/iterate-through-list-of-product-codes-generate-codabar-barcodes-and-store-each-in-zip-archive.cs @@ -1,73 +1,81 @@ -// Title: Generate Codabar barcodes and package them into a ZIP archive -// Description: Demonstrates iterating over product codes, creating Codabar barcode images, and storing each image in a zip file. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, showcasing the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to produce images. Typical use cases include batch barcode creation for inventory, shipping labels, or product catalogs, where developers need to automate image output and archive results. The example also illustrates using System.IO.Compression to bundle generated files, a common requirement in bulk processing scenarios. +// Title: Generate Codabar Barcodes and Package into a ZIP Archive +// Description: Demonstrates iterating over product codes, creating Codabar barcode images with Aspose.BarCode, and storing each PNG in a ZIP file. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of BarcodeGenerator, EncodeTypes, and barcode parameters to produce images. Typical use cases include batch barcode creation for inventory, shipping labels, or product catalogs, where developers need to automate image generation and archive the results. The code also illustrates combining .NET's System.IO.Compression to create ZIP archives of the generated files. // Prompt: Iterate through a list of product codes, generate Codabar barcodes, and store each in a zip archive. -// Tags: codabar, barcode generation, zip archive, batch processing, aspose.barcode, image output +// Tags: codabar, barcode generation, zip archive, png, aspose.barcode, csharp using System; -using System.Collections.Generic; using System.IO; using System.IO.Compression; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Program that generates Codabar barcodes for a list of product codes and saves them into a zip archive. +/// Example program that creates Codabar barcode images for a set of product codes +/// and packages the resulting PNG files into a ZIP archive. /// class Program { /// - /// Entry point. Generates barcodes, writes them to a zip file, and reports the result. + /// Entry point of the application. + /// Generates barcodes, saves them to memory streams, and adds them to a ZIP file. /// static void Main() { - // Define a sample list of product codes (replace with actual data as needed) - List productCodes = new List + // Define a sample list of product codes to encode as Codabar barcodes + string[] productCodes = new string[] { - "A12345B", - "C67890D", - "E11223F", - "G44556H", - "I77889J" + "A12345", + "B67890", + "C24680", + "D13579", + "E11223" }; - // Path for the output ZIP archive + // Target ZIP file name string zipPath = "CodabarBarcodes.zip"; - // Create the ZIP archive file stream + // Remove any existing ZIP file to ensure a fresh archive + if (File.Exists(zipPath)) + { + File.Delete(zipPath); + } + + // Create a new ZIP archive and add each generated barcode image as an entry using (FileStream zipFileStream = new FileStream(zipPath, FileMode.Create)) + using (ZipArchive archive = new ZipArchive(zipFileStream, ZipArchiveMode.Create)) { - // Initialize the ZIP archive in create mode - using (ZipArchive zipArchive = new ZipArchive(zipFileStream, ZipArchiveMode.Create, leaveOpen: true)) + // Iterate through each product code + foreach (string code in productCodes) { - // Iterate over each product code to generate its barcode - foreach (string code in productCodes) + // Generate a Codabar barcode for the current product code + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Codabar, code)) { - // Initialize the barcode generator for Codabar symbology - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Codabar, code)) + // Configure Codabar-specific parameters + generator.Parameters.Barcode.Codabar.StartSymbol = CodabarSymbol.A; + generator.Parameters.Barcode.Codabar.StopSymbol = CodabarSymbol.A; + generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; + generator.Parameters.Barcode.FilledBars = false; + + // Save the barcode image to a memory stream in PNG format + using (MemoryStream imageStream = new MemoryStream()) { - // Save the generated barcode image to a memory stream in PNG format - using (MemoryStream imageStream = new MemoryStream()) - { - generator.Save(imageStream, BarCodeImageFormat.Png); - imageStream.Position = 0; // Reset stream position for reading + generator.Save(imageStream, BarCodeImageFormat.Png); + imageStream.Position = 0; // Reset stream position for reading - // Create a new entry in the ZIP archive for this barcode image - ZipArchiveEntry entry = zipArchive.CreateEntry($"{code}.png"); - using (Stream entryStream = entry.Open()) - { - // Copy the image data into the ZIP entry - imageStream.CopyTo(entryStream); - } + // Create a new entry in the ZIP archive for this barcode image + ZipArchiveEntry entry = archive.CreateEntry($"{code}.png"); + using (Stream entryStream = entry.Open()) + { + // Copy the image data into the ZIP entry + imageStream.CopyTo(entryStream); } } } } } - // Inform the user about the successful generation - Console.WriteLine($"Generated {productCodes.Count} Codabar barcodes and saved to '{zipPath}'."); + Console.WriteLine($"Barcode images have been saved to '{zipPath}'."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/load-barcode-settings-from-xml-file-modify-xdimension-and-re-save-updated-xml.cs b/one-dimensional-barcode-types/load-barcode-settings-from-xml-file-modify-xdimension-and-re-save-updated-xml.cs index b0948a2..9ead484 100644 --- a/one-dimensional-barcode-types/load-barcode-settings-from-xml-file-modify-xdimension-and-re-save-updated-xml.cs +++ b/one-dimensional-barcode-types/load-barcode-settings-from-xml-file-modify-xdimension-and-re-save-updated-xml.cs @@ -1,46 +1,68 @@ -// Title: Load and modify barcode settings from XML -// Description: Demonstrates loading barcode generation settings from an XML file, adjusting the XDimension (module size), and saving the updated configuration. -// Category-Description: This example belongs to the Aspose.BarCode settings management category, showcasing how to import and export barcode configuration using the BarcodeGenerator class. Typical use cases include batch updating of barcode parameters, integration with external configuration files, and automating barcode generation workflows. Developers often need to programmatically adjust settings like XDimension, margins, or symbology before rendering barcodes. +// Title: Load and Modify Barcode Settings XML – XDimension Update +// Description: Demonstrates loading barcode generation settings from an XML file, changing the XDimension (module size) and exporting the updated configuration. +// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on importing and exporting barcode settings via XML. It showcases the use of BarcodeGenerator, EncodeTypes, and the Parameters.Barcode.XDimension property. Typical scenarios include persisting barcode configurations, batch updates, and integrating barcode settings with external configuration files. // Prompt: Load barcode settings from an XML file, modify XDimension, and re‑save the updated XML. -// Tags: barcode, load, modify, export, xml, barcodgenerator +// Tags: barcode, xml, xdimension, settings, export, import, aspose.barcode, generation using System; using System.IO; using Aspose.BarCode.Generation; /// -/// Example program that loads barcode generation settings from an XML file, -/// updates the XDimension (module size), and saves the modified settings back to XML. +/// Example program that loads barcode settings from an XML file, +/// updates the XDimension (module size), and saves the modified settings +/// back to a new XML file. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Performs the load‑modify‑save workflow. /// static void Main() { - // Define input and output XML file paths - string inputXml = "barcode_settings.xml"; - string outputXml = "updated_barcode_settings.xml"; + // Define file paths for the source and destination XML files + string inputXml = "barcodeSettings.xml"; + string outputXml = "barcodeSettings_updated.xml"; - // Ensure the input XML file exists before attempting to load it + // -------------------------------------------------------------------- + // Create a sample XML file if the expected input does not exist. + // This ensures the example can run standalone. + // -------------------------------------------------------------------- if (!File.Exists(inputXml)) { - Console.WriteLine($"Input file not found: {inputXml}"); + using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) + { + // Initialise XDimension to 1 point (default module size) + generator.Parameters.Barcode.XDimension.Point = 1f; + + // Export the initial settings to an XML file + generator.ExportToXml(inputXml); + Console.WriteLine($"Sample XML created at '{inputXml}'."); + } + } + + // -------------------------------------------------------------------- + // Verify that the input XML file is present before attempting import. + // -------------------------------------------------------------------- + if (!File.Exists(inputXml)) + { + Console.WriteLine($"Input XML file '{inputXml}' not found."); return; } - // Import barcode settings from the existing XML file using BarcodeGenerator + // -------------------------------------------------------------------- + // Import barcode settings from the XML, modify XDimension, and export. + // -------------------------------------------------------------------- using (var generator = BarcodeGenerator.ImportFromXml(inputXml)) { - // Update the XDimension (module size) to 2.5 points - generator.Parameters.Barcode.XDimension.Point = 2.5f; + // Update the XDimension to 2 points (increase module size) + generator.Parameters.Barcode.XDimension.Point = 2f; - // Export the modified settings to a new XML file - generator.ExportToXml(outputXml); + // Save the updated configuration to a new XML file + bool saved = generator.ExportToXml(outputXml); + Console.WriteLine(saved + ? $"Updated XML saved to '{outputXml}'." + : $"Failed to save updated XML to '{outputXml}'."); } - - // Inform the user that the operation completed successfully - Console.WriteLine($"Barcode settings updated and saved to: {outputXml}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/produce-continuous-databar-omnidirectional-barcodes-with-bar-height-50-pixels-output-jpeg.cs b/one-dimensional-barcode-types/produce-continuous-databar-omnidirectional-barcodes-with-bar-height-50-pixels-output-jpeg.cs index 6c506a5..774dffd 100644 --- a/one-dimensional-barcode-types/produce-continuous-databar-omnidirectional-barcodes-with-bar-height-50-pixels-output-jpeg.cs +++ b/one-dimensional-barcode-types/produce-continuous-databar-omnidirectional-barcodes-with-bar-height-50-pixels-output-jpeg.cs @@ -1,60 +1,60 @@ -// Title: Generate DataBar Omnidirectional barcodes with custom height and JPEG output -// Description: Demonstrates creating continuous DataBar Omnidirectional barcodes using Aspose.BarCode, setting a fixed bar height of 50 pixels, and saving each barcode as a JPEG image. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to work with the BarcodeGenerator class, configure encoding parameters such as AutoSizeMode and BarHeight, and export images in common formats. Developers creating retail or logistics solutions often need to generate DataBar OmniDirectional symbols for GTIN encoding, and this snippet shows the typical steps required. +// Title: Generate Continuous DataBar Omnidirectional Barcodes as JPEG Images +// Description: Demonstrates how to create multiple DataBar Omnidirectional barcodes with a fixed bar height and save them as JPEG files using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of the BarcodeGenerator class with EncodeTypes.DatabarOmniDirectional. Developers commonly generate DataBar symbols for retail and inventory applications, adjusting parameters such as bar height, X‑dimension, and output image format. The snippet shows typical steps: setting up the generator, configuring barcode parameters, and saving the image. // Prompt: Produce continuous DataBar Omnidirectional barcodes with bar height 50 pixels, output JPEG. -// Tags: databar omnidirectional barcode generation jpeg aspose.barcode +// Tags: databar, omnidirectional, barcode, generation, jpeg, aspose.barcode, c# using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Demonstrates generation of DataBar Omnidirectional barcodes with a fixed bar height and JPEG output. +/// Example program that generates a series of DataBar Omnidirectional barcodes +/// and saves each as a JPEG image. /// class Program { /// - /// Entry point. Generates a set of barcodes from sample GTIN values and saves them as JPEG files. + /// Entry point of the application. Creates an output folder, generates five + /// barcodes with a fixed height, and writes them to JPEG files. /// static void Main() { + // Define the output directory for generated barcode images + string outputDir = "Barcodes"; + // Ensure the output directory exists - string outputDir = "Output"; if (!Directory.Exists(outputDir)) { Directory.CreateDirectory(outputDir); } - // Sample GTIN values for DataBar OmniDirectional encoding - string[] gtinValues = new[] - { - "(01)12345678901231", - "(01)12345678901232", - "(01)12345678901233", - "(01)12345678901234", - "(01)12345678901235" - }; - - // Iterate over each GTIN value and generate a barcode - for (int i = 0; i < gtinValues.Length; i++) + // Loop to generate 5 distinct DataBar Omnidirectional barcodes + for (int i = 0; i < 5; i++) { - // Initialize the generator with the OmniDirectional symbology and current GTIN - using (var generator = new BarcodeGenerator(EncodeTypes.DatabarOmniDirectional, gtinValues[i])) - { - // Disable automatic sizing to use explicit dimensions - generator.Parameters.AutoSizeMode = AutoSizeMode.None; + // Sample GTIN code text for DataBar symbology; the last digit varies per iteration + string codeText = $"(01)1234567890123{i}"; - // Set the bar height to 50 pixels + // Initialize the barcode generator with the desired symbology and text + using (var generator = new BarcodeGenerator(EncodeTypes.DatabarOmniDirectional, codeText)) + { + // Set the bar height to 50 pixels (AutoSizeMode is None by default) generator.Parameters.Barcode.BarHeight.Pixels = 50f; - // Define the output file path - string filePath = Path.Combine(outputDir, $"databar_omni_{i + 1}.jpg"); + // Optionally adjust the X-dimension for better visual scaling + generator.Parameters.Barcode.XDimension.Pixels = 2f; + + // Build the full file path for the JPEG output + string filePath = Path.Combine(outputDir, $"databar_omni_{i}.jpg"); - // Save the barcode as a JPEG image + // Save the generated barcode image as a JPEG file generator.Save(filePath, BarCodeImageFormat.Jpeg); } } + + // Inform the user that the process completed successfully + Console.WriteLine("Barcode images generated successfully."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/render-barcode-directly-to-file-stream-using-save-method-then-close-stream-to-release-resources.cs b/one-dimensional-barcode-types/render-barcode-directly-to-file-stream-using-save-method-then-close-stream-to-release-resources.cs index 55ea4e3..d5e8474 100644 --- a/one-dimensional-barcode-types/render-barcode-directly-to-file-stream-using-save-method-then-close-stream-to-release-resources.cs +++ b/one-dimensional-barcode-types/render-barcode-directly-to-file-stream-using-save-method-then-close-stream-to-release-resources.cs @@ -1,44 +1,41 @@ -// Title: Render barcode to file stream using Save method -// Description: Demonstrates generating a Code128 barcode and saving it directly to a file stream in PNG format. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator with EncodeTypes and BarCodeImageFormat to create barcodes. Typical use cases include creating barcode images for inventory, shipping labels, or product packaging, where developers need to write the output directly to a stream for further processing or storage. +// Title: Render Barcode to File Stream Using Aspose.BarCode +// Description: Demonstrates how to generate a Code128 barcode and save it directly to a file stream in PNG format. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to create barcode images. Typical use cases include generating barcodes on the fly for reports, labels, or web applications, where developers need to write the image to a stream for further processing or storage. // Prompt: Render barcode directly to a file stream using Save method, then close the stream to release resources. -// Tags: code128, barcode generation, save to stream, png, aspose.barcode +// Tags: code128, barcode generation, file stream, png, aspose.barcode, save method using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; -/// -/// Demonstrates rendering a barcode directly to a file stream and saving it as a PNG image. -/// -class Program +namespace BarcodeStreamExample { /// - /// Entry point of the example. Generates a Code128 barcode, writes it to a file stream, and outputs the saved file path. + /// Provides an entry point that generates a Code128 barcode and writes it to a PNG file via a stream. /// - static void Main() + class Program { - // Define the output file path for the barcode image - string outputPath = "barcode.png"; - - // Create a FileStream for writing the barcode image to disk - using (FileStream stream = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) + /// + /// Generates a barcode image and saves it directly to a file stream. + /// + static void Main() { - // Initialize the barcode generator with Code128 symbology - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128)) - { - // Set the text that will be encoded into the barcode - generator.CodeText = "123456"; + // Define the output file path for the generated barcode image. + string outputPath = "barcode.png"; - // Save the generated barcode directly to the stream in PNG format - generator.Save(stream, BarCodeImageFormat.Png); - } // BarcodeGenerator disposed here - - // The FileStream will be closed automatically when exiting the using block - } // FileStream disposed here + // Initialize a BarcodeGenerator with Code128 symbology and sample text. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) + { + // Create a FileStream for writing the barcode image to the specified file. + using (var fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) + { + // Save the barcode directly to the stream in PNG format. + generator.Save(fileStream, BarCodeImageFormat.Png); + } // The FileStream is disposed and closed here. + } // The BarcodeGenerator is disposed here. - // Inform the user where the barcode image has been saved - Console.WriteLine($"Barcode saved to {Path.GetFullPath(outputPath)}"); + // Output the full path of the saved barcode image for verification. + Console.WriteLine($"Barcode image saved to: {Path.GetFullPath(outputPath)}"); + } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/render-barcode-directly-to-systemdrawingbitmap-object-for-further-gdi-manipulation.cs b/one-dimensional-barcode-types/render-barcode-directly-to-systemdrawingbitmap-object-for-further-gdi-manipulation.cs index 4fb013e..db2d5f4 100644 --- a/one-dimensional-barcode-types/render-barcode-directly-to-systemdrawingbitmap-object-for-further-gdi-manipulation.cs +++ b/one-dimensional-barcode-types/render-barcode-directly-to-systemdrawingbitmap-object-for-further-gdi-manipulation.cs @@ -1,51 +1,54 @@ -// Title: Render Barcode to Bitmap for GDI+ Manipulation -// Description: Demonstrates generating a Code128 barcode and rendering it directly to a System.Drawing.Bitmap for further GDI+ operations. -// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator, BarcodeParameters, and Aspose.Drawing classes to create, customize, and manipulate barcode images. Typical use cases include on‑the‑fly image processing, overlaying graphics, or integrating barcodes into custom UI components. Developers often need to render barcodes to Bitmap objects for GDI+ drawing, resizing, or compositing with other graphics. +// Title: Render Barcode to System.Drawing.Bitmap and Apply GDI+ Manipulation +// Description: Demonstrates generating a Code128 barcode, rendering it directly to an Aspose.Drawing.Bitmap, drawing a red border using GDI+, and saving the result as a PNG file. +// Category-Description: This example belongs to the Aspose.BarCode generation and rendering category, illustrating how to use BarcodeGenerator to create barcodes, obtain a Bitmap for further GDI+ processing, and save the image. Typical use cases include custom graphics overlays, watermarking, or integrating barcodes into existing .NET drawing workflows. Developers often work with BarcodeGenerator, Bitmap, Graphics, Pen, and ImageFormat classes to achieve these tasks. // Prompt: Render barcode directly to a System.Drawing.Bitmap object for further GDI+ manipulation. -// Tags: code128, barcode generation, bitmap, gdi+, aspose.barcode, aspose.drawing +// Tags: barcode, code128, generation, bitmap, gdi+, png, aspose.barcode, aspose.drawing using System; +using System.IO; using Aspose.BarCode.Generation; using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Example program that generates a Code128 barcode, renders it to a Bitmap, -/// applies GDI+ drawing operations, and saves the result as a PNG file. +/// Entry point for the barcode rendering example. /// class Program { /// - /// Entry point of the example. Generates and manipulates a barcode image. + /// Generates a Code128 barcode, draws a red rectangle around it using GDI+, and saves the image as PNG. /// static void Main() { - // Initialize a barcode generator for Code128 with sample text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) - { - // Optional: customize barcode appearance (color and font). - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue; - generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Arial"; - generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 12f; + // Define the output file path for the final PNG image + string outputPath = "barcode.png"; - // Generate the barcode as an Aspose.Drawing.Bitmap. + // Initialize a BarcodeGenerator for Code128 symbology with sample text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) + { + // Generate the barcode as an Aspose.Drawing.Bitmap for direct GDI+ manipulation using (Bitmap barcodeBitmap = generator.GenerateBarCodeImage()) { - // Perform GDI+ manipulation: draw a red rectangle around the barcode. + // Perform GDI+ drawing: add a red border around the entire barcode image using (Graphics graphics = Graphics.FromImage(barcodeBitmap)) { - using (Pen redPen = new Pen(Aspose.Drawing.Color.Red, 2f)) + // Create a red pen with a thickness of 3 pixels + using (Pen redPen = new Pen(Color.Red, 3f)) { - // Draw rectangle covering the entire image. + // Draw the rectangle; subtract 1 to stay within image bounds graphics.DrawRectangle(redPen, 0, 0, barcodeBitmap.Width - 1, barcodeBitmap.Height - 1); } } - // Save the manipulated bitmap to a PNG file. - barcodeBitmap.Save("barcode.png", ImageFormat.Png); + // Save the manipulated bitmap to a PNG file using a FileStream + using (FileStream fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) + { + barcodeBitmap.Save(fileStream, ImageFormat.Png); + } + + // Inform the user where the file was saved + Console.WriteLine($"Barcode image saved to '{Path.GetFullPath(outputPath)}'."); } } - - Console.WriteLine("Barcode image generated and saved as 'barcode.png'."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/render-barcode-to-memorystream-convert-stream-to-base64-string-for-json-api-response.cs b/one-dimensional-barcode-types/render-barcode-to-memorystream-convert-stream-to-base64-string-for-json-api-response.cs index cc3b850..e28456a 100644 --- a/one-dimensional-barcode-types/render-barcode-to-memorystream-convert-stream-to-base64-string-for-json-api-response.cs +++ b/one-dimensional-barcode-types/render-barcode-to-memorystream-convert-stream-to-base64-string-for-json-api-response.cs @@ -1,51 +1,43 @@ -// Title: Render Code128 barcode to Base64 string -// Description: Demonstrates generating a Code128 barcode, rendering it to a PNG image in memory, and converting the image to a Base64 string suitable for JSON responses. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class to create barcodes, save them to a MemoryStream with BarCodeImageFormat, and obtain a Base64 representation for web APIs. Developers often need to embed barcode images directly in JSON payloads without writing files to disk. +// Title: Render Code128 barcode to Base64 string using Aspose.BarCode +// Description: Demonstrates generating a Code128 barcode, rendering it to a PNG image in memory, and converting the image to a Base64 string suitable for inclusion in a JSON API response. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to use the BarcodeGenerator class with EncodeTypes and BarCodeImageFormat to create barcodes, render them to streams, and obtain binary data. Typical use cases include server‑side barcode creation for web services, mobile apps, or document automation where the image must be transmitted as text (e.g., Base64) in JSON payloads. Developers often need to embed barcodes directly into API responses without writing temporary files. // Prompt: Render barcode to a MemoryStream, convert the stream to a Base64 string for JSON API response. -// Tags: code128, barcode generation, png, base64, memorystream, aspose.barcode, aspose.drawing, json response +// Tags: code128, barcode, generation, base64, json, memorystream, aspose.barcode, png using System; using System.IO; +using System.Text; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing.Imaging; /// -/// Example program that generates a Code128 barcode, encodes it as PNG in memory, -/// and returns the image as a Base64 string for inclusion in JSON responses. +/// Example program that generates a Code128 barcode, saves it to a memory stream as PNG, +/// and outputs the image as a Base64 string for use in JSON responses. /// class Program { /// - /// Entry point of the application. Generates the Base64 barcode string and writes it to the console. + /// Entry point. Creates a BarcodeGenerator, encodes text, saves to MemoryStream, + /// converts to Base64, and writes the result to the console. /// static void Main() { - // Generate the barcode and obtain its Base64 representation - string base64Barcode = GenerateBarcodeBase64(); - - // Output the Base64 string (e.g., to be captured by a calling process or API) - Console.WriteLine(base64Barcode); - } - - /// - /// Creates a Code128 barcode, saves it as a PNG image into a memory stream, - /// and converts the resulting byte array to a Base64 string. - /// - /// Base64-encoded PNG image of the generated barcode. - static string GenerateBarcodeBase64() - { - // Initialize the barcode generator with the desired symbology and data - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Create a barcode generator for Code128 symbology + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128)) { - // Prepare a memory stream to hold the PNG image data - using (var memoryStream = new MemoryStream()) + // Set the text to encode + generator.CodeText = "123ABC"; + + // Render the barcode to a memory stream in PNG format + using (MemoryStream ms = new MemoryStream()) { - // Render the barcode into the memory stream in PNG format - generator.Save(memoryStream, BarCodeImageFormat.Png); + generator.Save(ms, BarCodeImageFormat.Png); + + // Convert the image bytes to a Base64 string + string base64 = Convert.ToBase64String(ms.ToArray()); - // Convert the image bytes from the stream to a Base64 string - return Convert.ToBase64String(memoryStream.ToArray()); + // Output the Base64 string (simulating JSON API response) + Console.WriteLine(base64); } } } diff --git a/one-dimensional-barcode-types/render-barcode-to-png-stream-and-upload-directly-to-azure-blob-storage-container.cs b/one-dimensional-barcode-types/render-barcode-to-png-stream-and-upload-directly-to-azure-blob-storage-container.cs index bfc01e8..9a75099 100644 --- a/one-dimensional-barcode-types/render-barcode-to-png-stream-and-upload-directly-to-azure-blob-storage-container.cs +++ b/one-dimensional-barcode-types/render-barcode-to-png-stream-and-upload-directly-to-azure-blob-storage-container.cs @@ -1,70 +1,80 @@ -// Title: Render Barcode to PNG Stream and Upload to Azure Blob -// Description: Demonstrates generating a Code128 barcode, saving it as a PNG in memory, optionally persisting locally, and uploading directly to an Azure Blob storage container. -// Category-Description: This example belongs to the Aspose.BarCode image generation and cloud storage integration category. It shows how to use BarcodeGenerator, BarCodeImageFormat, and Azure.Storage.Blobs to create barcodes, work with streams, and store them in Azure Blob containers—common tasks for developers building automated labeling or inventory systems. +// Title: Render barcode to PNG stream and upload to Azure Blob storage +// Description: Demonstrates generating a Code128 barcode, saving it to a PNG memory stream, and showing how to upload the stream to Azure Blob storage. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator to create barcodes and output them in image formats. It covers saving to streams, optional appearance customization, and integrating with Azure.Storage.Blobs for direct cloud uploads—common tasks for developers building automated labeling or inventory systems. // Prompt: Render barcode to a PNG stream and upload directly to an Azure Blob storage container. -// Tags: barcode symbology, generation, png, azure blob storage, aspose.barcode, stream +// Tags: barcode, code128, png, stream, azure blob, upload, aspose.barcode, generation using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing.Imaging; +using Aspose.Drawing; -namespace BarcodeToAzureBlob +/// +/// Demonstrates barcode generation to a PNG stream and outlines Azure Blob upload. +/// +class Program { /// - /// Generates a Code128 barcode, saves it as PNG, and uploads it to Azure Blob storage. + /// Generates a Code128 barcode, saves it to a PNG memory stream, writes it to a local file, + /// and provides sample code for uploading the stream to Azure Blob storage. /// - class Program + static void Main() { - /// - /// Entry point of the example. Creates a barcode, writes it to a memory stream, - /// optionally saves it locally, and demonstrates how to upload it to Azure Blob storage. - /// - static void Main() + // Define barcode parameters + const string codeText = "1234567890"; + const string localFilePath = "barcode.png"; + + // Create a memory stream to hold the PNG image + using (var pngStream = new MemoryStream()) { - // Initialize a barcode generator for Code128 and set the text to encode. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) + // Generate the barcode and save it directly to the PNG stream + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - generator.CodeText = "Sample123"; + // Optional: customize barcode appearance here + // generator.Parameters.Barcode.XDimension.Point = 2f; + // generator.Parameters.Barcode.FilledBars = false; + // generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; - // Render the barcode to a PNG image stored in a memory stream. - using (var stream = new MemoryStream()) - { - generator.Save(stream, BarCodeImageFormat.Png); - // Reset stream position to the beginning for subsequent reads. - stream.Position = 0; + generator.Save(pngStream, BarCodeImageFormat.Png); + } - // Optional: save the generated image to a local file for verification. - const string localPath = "barcode.png"; - using (var fileStream = new FileStream(localPath, FileMode.Create, FileAccess.Write)) - { - stream.CopyTo(fileStream); - } + // Reset the stream position before reading/writing + pngStream.Position = 0; - // ----------------------------------------------------------------- - // Azure Blob Storage upload (requires Azure.Storage.Blobs package) - // ----------------------------------------------------------------- - /* - string connectionString = ""; - string containerName = ""; - string blobName = "barcode.png"; + // Write the PNG stream to a local file (placeholder for Azure Blob upload) + using (var fileStream = new FileStream(localFilePath, FileMode.Create, FileAccess.Write)) + { + pngStream.CopyTo(fileStream); + } - var blobServiceClient = new Azure.Storage.Blobs.BlobServiceClient(connectionString); - var containerClient = blobServiceClient.GetBlobContainerClient(containerName); - var blobClient = containerClient.GetBlobClient(blobName); + Console.WriteLine($"Barcode image saved locally to '{localFilePath}'."); + } - // Ensure the container exists. - containerClient.CreateIfNotExists(); + // ----------------------------------------------------------------- + // Azure Blob Storage upload (commented out – Azure SDK not available in the runner) + // ----------------------------------------------------------------- + // The following code demonstrates how you would upload the PNG stream + // directly to an Azure Blob container using Azure.Storage.Blobs. + // Uncomment and add the required NuGet package (Azure.Storage.Blobs) in a real environment. + /* + // using Azure.Storage.Blobs; + // const string connectionString = ""; + // const string containerName = ""; + // const string blobName = "barcode.png"; - // Reset stream position before uploading. - stream.Position = 0; - blobClient.Upload(stream, overwrite: true); - */ - } - } + // using (var pngStream = new MemoryStream()) + // { + // using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // { + // generator.Save(pngStream, BarCodeImageFormat.Png); + // } + // pngStream.Position = 0; - Console.WriteLine("Barcode generated and saved locally."); - } + // var blobClient = new BlobClient(connectionString, containerName, blobName); + // blobClient.Upload(pngStream, overwrite: true); + // Console.WriteLine($"Barcode image uploaded to Azure Blob storage as '{blobName}'."); + // } + */ } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/render-databar-stacked-barcodes-with-custom-column-counts-export-each-to-separate-pdf-pages.cs b/one-dimensional-barcode-types/render-databar-stacked-barcodes-with-custom-column-counts-export-each-to-separate-pdf-pages.cs index d16ed0a..64bc8b3 100644 --- a/one-dimensional-barcode-types/render-databar-stacked-barcodes-with-custom-column-counts-export-each-to-separate-pdf-pages.cs +++ b/one-dimensional-barcode-types/render-databar-stacked-barcodes-with-custom-column-counts-export-each-to-separate-pdf-pages.cs @@ -1,108 +1,93 @@ -// Title: Render DataBar Stacked Barcodes with Custom Column Counts to PDF -// Description: Demonstrates generating stacked DataBar barcodes with custom column counts and exporting each barcode to a separate page in a PDF document. -// Category-Description: This example belongs to the Aspose.BarCode generation and export category, showcasing how to use BarcodeGenerator, set DataBar specific parameters (such as column count), and combine generated images into a multi‑page PDF using Aspose.Pdf. Typical use cases include retail product labeling, inventory management, and any scenario requiring stacked DataBar symbologies with precise layout control. Developers often need to customize barcode dimensions, appearance, and then embed them into documents for printing or distribution. +// Title: Render DataBar Stacked Barcodes to PDF with Custom Column Counts +// Description: Demonstrates generating DataBar stacked barcodes with varying column counts and exporting each barcode to a separate page in a PDF document. +// Category-Description: Shows how to use Aspose.BarCode to create DataBar stacked symbology, customize its column count, and embed the generated images into an Aspose.Pdf document. This example belongs to the barcode generation and PDF export category, where developers commonly need to produce multiple barcodes and combine them into a single PDF for reporting or printing. // Prompt: Render DataBar stacked barcodes with custom column counts, export each to separate PDF pages. -// Tags: databar, stacked, barcode, pdf, aspose.barcode, image generation, aspose.pdf +// Tags: databar, stacked, barcode generation, pdf export, aspose.barcode, aspose.pdf using System; using System.IO; using System.Collections.Generic; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; using Aspose.Pdf; +using Aspose.Pdf.Text; /// -/// Generates stacked DataBar barcodes with custom column counts and saves each barcode on a separate PDF page. +/// Generates DataBar stacked barcodes with custom column counts and saves them to a multi‑page PDF. /// class Program { /// - /// Entry point of the example. Creates barcode images, adds them to a PDF, and saves the document. + /// Entry point of the example. Creates barcode images, adds each to a separate PDF page, and saves the document. /// static void Main() { - // Define the DataBar stacked symbologies and their corresponding code texts. - BaseEncodeType[] dataBarTypes = new BaseEncodeType[] - { - EncodeTypes.DatabarStacked, - EncodeTypes.DatabarStackedOmniDirectional, - EncodeTypes.DatabarLimited, - EncodeTypes.DatabarExpandedStacked - }; - - string[] codeTexts = new string[] - { - "(01)12345678901231", // for DatabarStacked - "(01)12345678901231", // for DatabarStackedOmniDirectional - "(01)08888888888888", // for DatabarLimited (requires GTIN‑style value) - "(01)12345678901231" // for DatabarExpandedStacked - }; + // Define the output PDF file name. + string pdfPath = "DataBarStacked.pdf"; - // Custom column counts for each barcode (example values). - int[] columnCounts = new int[] { 2, 3, 4, 5 }; + // Column counts to apply to each generated DataBar stacked barcode. + int[] columnCounts = { 2, 3, 4, 5 }; + // Limit the number of barcodes for evaluation mode (max 4). + int maxCount = Math.Min(columnCounts.Length, 4); - // List to hold the generated barcode image streams. + // Collect generated barcode images in memory streams. List barcodeStreams = new List(); - // Generate each barcode and store its PNG image in a memory stream. - for (int i = 0; i < dataBarTypes.Length && i < 4; i++) // limit to 4 items per evaluation rules + // Generate a barcode for each column count. + for (int i = 0; i < maxCount; i++) { - BaseEncodeType type = dataBarTypes[i]; - string codeText = codeTexts[i]; - int columns = columnCounts[i]; - - using (var generator = new BarcodeGenerator(type, codeText)) + // Initialize a DataBar stacked barcode generator with a sample GTIN. + using (var generator = new BarcodeGenerator(EncodeTypes.DatabarStacked, "(01)01234567890123")) { - // Set basic appearance. + // Apply the custom column count. + generator.Parameters.Barcode.DataBar.Columns = columnCounts[i]; + + // Optional visual settings: black bars on white background. generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; generator.Parameters.BackColor = Aspose.Drawing.Color.White; - // Define explicit image size (required for stacked DataBar). - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; - - // Disable auto‑size to allow manual BarHeight. - generator.Parameters.AutoSizeMode = AutoSizeMode.None; - generator.Parameters.Barcode.BarHeight.Point = 50f; - - // Apply custom column count. - generator.Parameters.Barcode.DataBar.Columns = columns; - - // Save barcode to a memory stream as PNG. + // Save the barcode image to a memory stream in PNG format. var ms = new MemoryStream(); generator.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; // Reset for later reading. + ms.Position = 0; // Reset stream position for later reading. barcodeStreams.Add(ms); } } - // Create a PDF document and add each barcode image on a separate page. + // Create a new PDF document and add each barcode image to its own page. using (var pdfDoc = new Document()) { - for (int i = 0; i < barcodeStreams.Count; i++) + foreach (var stream in barcodeStreams) { + // Add a new page to the PDF. var page = pdfDoc.Pages.Add(); - // Define rectangle where the image will be placed (matches image size). - var rect = new Aspose.Pdf.Rectangle(0, 0, 300, 150); - - // Add image from the corresponding stream. - var stream = barcodeStreams[i]; - stream.Position = 0; - page.AddImage(stream, rect); + // Configure the image to be placed on the page. + var pdfImage = new Image + { + ImageStream = stream, + FixWidth = 200, + FixHeight = 200, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + Margin = new MarginInfo { Top = 20 } + }; + + // Add the image to the page's paragraph collection. + page.Paragraphs.Add(pdfImage); } - // Save the PDF document to the current directory. - string outputPdf = Path.Combine(Environment.CurrentDirectory, "DataBarStacked.pdf"); - pdfDoc.Save(outputPdf); - Console.WriteLine($"PDF saved to: {outputPdf}"); + // Save the assembled PDF to disk. + pdfDoc.Save(pdfPath); } - // Dispose all memory streams. + // Release all memory streams used for barcode images. foreach (var ms in barcodeStreams) { ms.Dispose(); } + + // Inform the user where the PDF was saved. + Console.WriteLine($"PDF with DataBar stacked barcodes saved to: {Path.GetFullPath(pdfPath)}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-barcode-background-to-transparent-then-composite-generated-png-onto-background-image-for-ui-display.cs b/one-dimensional-barcode-types/set-barcode-background-to-transparent-then-composite-generated-png-onto-background-image-for-ui-display.cs index 5da6393..d47dc30 100644 --- a/one-dimensional-barcode-types/set-barcode-background-to-transparent-then-composite-generated-png-onto-background-image-for-ui-display.cs +++ b/one-dimensional-barcode-types/set-barcode-background-to-transparent-then-composite-generated-png-onto-background-image-for-ui-display.cs @@ -1,68 +1,74 @@ -// Title: Transparent barcode compositing onto background image -// Description: Demonstrates generating a Code128 barcode with a transparent background and overlaying it onto a background PNG for UI display. -// Category-Description: This example belongs to the Aspose.BarCode image generation and manipulation category. It showcases using BarcodeGenerator, setting BackColor to Transparent, adjusting size with AutoSizeMode, and compositing the resulting bitmap with Aspose.Drawing graphics. Developers often need to create barcodes that blend seamlessly into UI designs, requiring transparent backgrounds and custom image composition. +// Title: Generate a transparent Code128 barcode and overlay it on a background image +// Description: Demonstrates how to create a barcode with a transparent background, then composite it onto a PNG background for UI display. +// Category-Description: This example belongs to the Aspose.BarCode image generation and manipulation category. It showcases the use of BarcodeGenerator, BarcodeParameters, and Aspose.Drawing classes to produce a barcode image, adjust its background transparency, and combine it with another image. Developers often need to embed barcodes into UI graphics or reports where the barcode must blend seamlessly with existing visuals. // Prompt: Set barcode background to transparent, then composite the generated PNG onto a background image for UI display. -// Tags: code128, transparent background, image compositing, png, aspose.barcode, aspose.drawing +// Tags: code128, barcode, transparent background, image compositing, png, aspose.barcode, aspose.drawing, generation using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Generates a Code128 barcode with a transparent background, -/// then composites it onto an existing background image and saves the result. +/// Demonstrates generating a transparent Code128 barcode and compositing it onto a background image. /// class Program { /// - /// Entry point of the example. Creates the barcode, composites it, and writes the output file. + /// Entry point of the example. Creates placeholder background if missing, generates barcode, and saves the final composited image. /// static void Main() { - // Paths for the generated barcode, background image and final composite image - const string barcodePath = "barcode.png"; - const string backgroundPath = "background.png"; - const string outputPath = "composite.png"; + // Define file paths for the background, barcode, and final composited image + string backgroundPath = "background.png"; + string barcodePath = "barcode.png"; + string finalPath = "final.png"; - // Verify that the background image exists before proceeding + // Ensure a background image exists; create a simple placeholder if it does not if (!File.Exists(backgroundPath)) { - Console.WriteLine($"Background image not found: {backgroundPath}"); - return; + using (var placeholder = new Bitmap(400, 200)) + { + using (var g = Graphics.FromImage(placeholder)) + { + // Fill the placeholder with a light gray color + g.Clear(Aspose.Drawing.Color.LightGray); + } + // Save the placeholder as a PNG file + placeholder.Save(backgroundPath, ImageFormat.Png); + } } - // Create a barcode generator configured for Code128 and set a transparent background - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) + // Generate a Code128 barcode with a transparent background + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Make the barcode background transparent + // Set the barcode's background to transparent generator.Parameters.BackColor = Aspose.Drawing.Color.Transparent; - // Use interpolation mode to control the exact size via ImageWidth/ImageHeight - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; - - // Generate the barcode image as a bitmap - using (Bitmap barcodeBitmap = generator.GenerateBarCodeImage()) + using (Bitmap barcodeBmp = generator.GenerateBarCodeImage()) { + // Optionally save the standalone barcode image + barcodeBmp.Save(barcodePath, ImageFormat.Png); + // Load the background image onto which the barcode will be drawn - using (Image backgroundImage = Image.FromFile(backgroundPath)) + using (Bitmap backgroundBmp = (Bitmap)Image.FromFile(backgroundPath)) { - // Obtain a graphics object for drawing onto the background - using (Graphics graphics = Graphics.FromImage(backgroundImage)) + // Compute coordinates to center the barcode on the background + int posX = (backgroundBmp.Width - barcodeBmp.Width) / 2; + int posY = (backgroundBmp.Height - barcodeBmp.Height) / 2; + + // Draw the barcode onto the background at the calculated position + using (Graphics graphics = Graphics.FromImage(backgroundBmp)) { - // Draw the barcode at the top‑left corner (0,0) with its original dimensions - graphics.DrawImage(barcodeBitmap, 0, 0, barcodeBitmap.Width, barcodeBitmap.Height); + graphics.DrawImage(barcodeBmp, posX, posY, barcodeBmp.Width, barcodeBmp.Height); } - // Save the composited image as PNG to preserve transparency where applicable - backgroundImage.Save(outputPath, ImageFormat.Png); + // Save the final composited image as a PNG file + backgroundBmp.Save(finalPath, ImageFormat.Png); } } } - - Console.WriteLine($"Composite image saved to: {outputPath}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-barcode-background-to-white-and-foreground-to-black-for-maximum-contrast-in-scanned-documents.cs b/one-dimensional-barcode-types/set-barcode-background-to-white-and-foreground-to-black-for-maximum-contrast-in-scanned-documents.cs index f29b343..e9be840 100644 --- a/one-dimensional-barcode-types/set-barcode-background-to-white-and-foreground-to-black-for-maximum-contrast-in-scanned-documents.cs +++ b/one-dimensional-barcode-types/set-barcode-background-to-white-and-foreground-to-black-for-maximum-contrast-in-scanned-documents.cs @@ -1,41 +1,49 @@ -// Title: Generate high-contrast Code128 barcode image -// Description: Demonstrates setting barcode foreground to black and background to white for optimal scanning contrast. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to customize visual appearance using BarcodeGenerator, EncodeTypes, and BarCodeImageFormat. Typical use cases include creating printable barcodes with maximum readability in scanned documents. Developers often need to adjust colors, sizes, and formats to meet printing and scanning requirements. +// Title: Generate a high‑contrast Code128 barcode image +// Description: Demonstrates how to create a Code128 barcode with a white background and black foreground for optimal scanning contrast. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to customize barcode appearance. Developers often need to adjust colors for readability in printed or scanned documents, and this snippet shows the typical steps for setting bar and background colors before saving the image. // Prompt: Set barcode background to white and foreground to black for maximum contrast in scanned documents. -// Tags: code128, color, contrast, png, generation, aspose.barcode, barcodegenerator +// Tags: barcode, code128, color, png, aspose.barcode, generation using System; +using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; /// -/// Shows how to generate a Code128 barcode with a white background and black foreground, -/// ensuring maximum contrast for scanned documents. +/// Demonstrates generating a Code128 barcode with high contrast colors and saving it as a PNG file. /// class Program { /// - /// Entry point of the example. Generates the barcode image and saves it to disk. + /// Entry point. Creates the barcode, configures colors, ensures output directory exists, and saves the image. /// static void Main() { - // Define the output file path for the generated barcode image. + // Define the output file path for the generated barcode image string outputPath = "barcode.png"; - // Initialize a BarcodeGenerator for Code128 symbology with sample data. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Ensure the target directory exists; create it if necessary + string directory = Path.GetDirectoryName(outputPath); + if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) { - // Set the barcode bars (foreground) to black for high contrast. + Directory.CreateDirectory(directory); + } + + // Initialize a BarcodeGenerator for Code128 with the sample text "123456" + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + { + // Set the barcode (bars) color to black for maximum foreground contrast generator.Parameters.Barcode.BarColor = Color.Black; - // Set the image background to white. + // Set the image background color to white for maximum background contrast generator.Parameters.BackColor = Color.White; - // Save the generated barcode as a PNG file. + // Save the configured barcode as a PNG image to the specified path generator.Save(outputPath, BarCodeImageFormat.Png); } - // Inform the user where the barcode image was saved. - Console.WriteLine($"Barcode saved to {outputPath}"); + // Output the full path of the saved barcode image for verification + Console.WriteLine($"Barcode saved to: {Path.GetFullPath(outputPath)}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-barcode-background-to-white-foreground-to-black-and-generate-image-for-high-contrast-scanning-environments.cs b/one-dimensional-barcode-types/set-barcode-background-to-white-foreground-to-black-and-generate-image-for-high-contrast-scanning-environments.cs index 602f9cc..1aa2fe6 100644 --- a/one-dimensional-barcode-types/set-barcode-background-to-white-foreground-to-black-and-generate-image-for-high-contrast-scanning-environments.cs +++ b/one-dimensional-barcode-types/set-barcode-background-to-white-foreground-to-black-and-generate-image-for-high-contrast-scanning-environments.cs @@ -1,48 +1,39 @@ -// Title: Generate high‑contrast barcode image (white background, black foreground) -// Description: Demonstrates setting barcode colors for optimal scanning and saving as PNG. -// Category-Description: This example belongs to Aspose.BarCode generation examples, showing how to configure visual properties such as BarColor and BackColor using BarcodeGenerator. Typical use cases include creating high‑contrast barcodes for industrial scanners. Developers often need to adjust colors, size, and output format when integrating barcode generation into .NET applications. +// Title: Generate high‑contrast barcode image with white background and black bars +// Description: Demonstrates how to configure Aspose.BarCode to produce a barcode with a white background and black foreground, suitable for high‑contrast scanning environments. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to customize barcode appearance. Developers often need to adjust colors for readability, export barcodes to common image formats, and integrate them into applications that require optimal scan performance. The snippet shows typical steps for setting background and bar colors before saving the image. // Prompt: Set barcode background to white, foreground to black, and generate image for high‑contrast scanning environments. -// Tags: barcode, generation, high-contrast, png, code128, aspnet, aspose.barcode, color +// Tags: barcode, high-contrast, background-color, foreground-color, png, aspose.barcode, generation using System; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; -namespace BarcodeExample +/// +/// Provides an entry point that generates a high‑contrast barcode image. +/// +class Program { /// - /// Demonstrates generating a Code128 barcode with white background and black foreground, - /// suitable for high‑contrast scanning environments. + /// Generates a Code128 barcode with white background and black bars, then saves it as a PNG file. /// - class Program + static void Main() { - /// - /// Entry point. Generates the barcode image and saves it to disk. - /// - static void Main() - { - // Define the output file path for the generated PNG image - string outputPath = "high_contrast_barcode.png"; - - // Initialize a BarcodeGenerator for Code128 symbology with sample data - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) - { - // Set the barcode (bars) color to black for maximum contrast - generator.Parameters.Barcode.BarColor = Color.Black; - - // Set the image background color to white - generator.Parameters.BackColor = Color.White; + // Define the output file path for the generated barcode image + string outputPath = "high_contrast_barcode.png"; - // Optionally specify the image dimensions (width and height in points) - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; - - // Save the generated barcode as a PNG file at the specified path - generator.Save(outputPath, BarCodeImageFormat.Png); - } + // Create a barcode generator for Code128 symbology with sample text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + { + // Set high‑contrast colors: white background and black bars + generator.Parameters.BackColor = Color.White; + generator.Parameters.Barcode.BarColor = Color.Black; - // Inform the user where the image has been saved - Console.WriteLine($"Barcode image saved to {outputPath}"); + // Save the barcode image in PNG format to the specified path + generator.Save(outputPath, BarCodeImageFormat.Png); } + + // 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/one-dimensional-barcode-types/set-barcode-height-for-continuous-databar-types-to-70-pixels-compare-jpeg-and-png-outputs.cs b/one-dimensional-barcode-types/set-barcode-height-for-continuous-databar-types-to-70-pixels-compare-jpeg-and-png-outputs.cs index 0c15ce2..84499c2 100644 --- a/one-dimensional-barcode-types/set-barcode-height-for-continuous-databar-types-to-70-pixels-compare-jpeg-and-png-outputs.cs +++ b/one-dimensional-barcode-types/set-barcode-height-for-continuous-databar-types-to-70-pixels-compare-jpeg-and-png-outputs.cs @@ -1,73 +1,79 @@ -// Title: Set DataBar barcode height and compare PNG vs JPEG outputs -// Description: Demonstrates setting the bar height for continuous DataBar symbologies to 70 pixels and saving the barcodes as PNG and JPEG to compare file sizes. -// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to configure barcode dimensions using the BarcodeGenerator class. It covers typical use cases such as customizing bar height for DataBar symbologies and exporting images in different formats. Developers often need to adjust visual properties and evaluate output size for web or print scenarios. +// Title: Set DataBar barcode height to 70px and compare JPEG vs PNG output sizes +// Description: Demonstrates how to set the bar height for continuous DataBar symbologies to 70 pixels, generate barcodes, and compare the file sizes of JPEG and PNG images. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on barcode appearance customization and image format handling. It uses BarcodeGenerator, BarCodeImageFormat, and related parameter classes to adjust dimensions and export images. Developers often need to control bar height, X‑dimension, and compare output formats for storage or printing requirements. // Prompt: Set barcode height for continuous DataBar types to 70 pixels, compare JPEG and PNG outputs. -// Tags: databar, barcode, height, image, png, jpeg, generation +// Tags: databar, barcode height, image format comparison, jpeg, png, aspose.barcode, barcode generation using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing.Imaging; /// -/// Generates continuous DataBar barcodes with a custom height and saves them as PNG and JPEG -/// to illustrate size differences between the two image formats. +/// Generates DataBar barcodes with a fixed height of 70 pixels and saves them as JPEG and PNG +/// to compare resulting file sizes. /// class Program { /// - /// Entry point of the example. Creates barcodes for various DataBar symbologies, - /// sets a fixed bar height, saves each barcode in PNG and JPEG formats, - /// and writes the resulting file sizes to the console. + /// Entry point that creates barcodes for each DataBar symbology, configures dimensions, + /// saves images in two formats, and outputs size information to the console. /// static void Main() { - // Define the continuous DataBar symbologies and their associated code text. - var dataBarTypes = new (BaseEncodeType type, string codeText)[] - { - (EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"), - (EncodeTypes.DatabarStacked, "(01)12345678901231"), - (EncodeTypes.DatabarStackedOmniDirectional, "(01)12345678901231"), - (EncodeTypes.DatabarExpanded, "(01)12345678901231"), - (EncodeTypes.DatabarExpandedStacked, "(01)12345678901231") - }; - - // Ensure the output directory exists. - string outputDir = "Output"; + // Define output directory and ensure it exists + string outputDir = "output"; if (!Directory.Exists(outputDir)) + { Directory.CreateDirectory(outputDir); + } + + // List of continuous DataBar symbologies to process + BaseEncodeType[] dataBarTypes = new BaseEncodeType[] + { + EncodeTypes.DatabarOmniDirectional, + EncodeTypes.DatabarStacked, + EncodeTypes.DatabarStackedOmniDirectional, + EncodeTypes.DatabarLimited, + EncodeTypes.DatabarExpanded, + EncodeTypes.DatabarExpandedStacked, + EncodeTypes.DatabarTruncated + }; - // Iterate over each DataBar type, generate the barcode, and save in both formats. - foreach (var (type, codeText) in dataBarTypes) + // Iterate over each symbology type + foreach (BaseEncodeType type in dataBarTypes) { - // Initialize the barcode generator with the specific DataBar type and code text. - using (var generator = new BarcodeGenerator(type, codeText)) + // Choose appropriate code text based on symbology requirements + string codeText = type == EncodeTypes.DatabarLimited + ? "(01)08888888888888" + : "(01)12345678901231"; + + // Initialize the barcode generator with the selected type and text + using (BarcodeGenerator generator = new BarcodeGenerator(type, codeText)) { - // Disable automatic sizing so that the explicit BarHeight is applied. + // Disable auto‑sizing so that explicit BarHeight takes effect generator.Parameters.AutoSizeMode = AutoSizeMode.None; - // Set the bar height to 70 pixels. + // Set the bar height to 70 pixels generator.Parameters.Barcode.BarHeight.Pixels = 70f; - // Save the barcode as a PNG file. - string pngPath = Path.Combine(outputDir, $"{type}.png"); - generator.Save(pngPath, BarCodeImageFormat.Png); + // Optionally set a modest XDimension for better visual clarity + generator.Parameters.Barcode.XDimension.Pixels = 2f; - // Save the barcode as a JPEG file. - string jpgPath = Path.Combine(outputDir, $"{type}.jpg"); - generator.Save(jpgPath, BarCodeImageFormat.Jpeg); + // Save the barcode as a JPEG image + string jpegPath = Path.Combine(outputDir, $"{type.TypeName}_70px.jpeg"); + generator.Save(jpegPath, BarCodeImageFormat.Jpeg); - // Retrieve file sizes for comparison. - long pngSize = new FileInfo(pngPath).Length; - long jpgSize = new FileInfo(jpgPath).Length; + // Save the same barcode as a PNG image + string pngPath = Path.Combine(outputDir, $"{type.TypeName}_70px.png"); + generator.Save(pngPath, BarCodeImageFormat.Png); - // Output the size comparison to the console. - Console.WriteLine($"{type}: PNG size = {pngSize} bytes, JPEG size = {jpgSize} bytes"); + // Retrieve and display file sizes for comparison + long jpegSize = new FileInfo(jpegPath).Length; + long pngSize = new FileInfo(pngPath).Length; + Console.WriteLine($"{type.TypeName}: JPEG size = {jpegSize} bytes, PNG size = {pngSize} bytes"); } } - - Console.WriteLine("Barcode generation completed."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-barcode-height-to-50-mm-while-keeping-default-xdimension-to-preserve-aspect-ratio.cs b/one-dimensional-barcode-types/set-barcode-height-to-50-mm-while-keeping-default-xdimension-to-preserve-aspect-ratio.cs index 4ed0c1d..a70df12 100644 --- a/one-dimensional-barcode-types/set-barcode-height-to-50-mm-while-keeping-default-xdimension-to-preserve-aspect-ratio.cs +++ b/one-dimensional-barcode-types/set-barcode-height-to-50-mm-while-keeping-default-xdimension-to-preserve-aspect-ratio.cs @@ -1,35 +1,37 @@ -// Title: Set barcode height to 50 mm while preserving XDimension -// Description: Demonstrates how to configure a barcode's bar height in millimeters using Aspose.BarCode without altering the default XDimension, ensuring the aspect ratio remains unchanged. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to adjust barcode dimensions via the BarcodeGenerator.Parameters API. Typical use cases include customizing barcode size for printing or display while maintaining visual fidelity. Developers often need to modify bar height, XDimension, or other layout properties to meet design specifications. +// Title: Set barcode height to 50 mm while preserving default XDimension +// Description: Demonstrates how to generate a Code128 barcode image with a specific height of 50 mm, keeping the default XDimension to maintain the correct aspect ratio. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and barcode parameter settings. Typical use cases include creating barcodes with custom dimensions for printing or embedding in documents. Developers often need to adjust size properties while preserving default scaling factors to ensure readability and scanner compatibility. // Prompt: Set barcode height to 50 mm while keeping default XDimension to preserve aspect ratio. -// Tags: code128, set-height, png, aspose.barcode, barcodegenerator +// Tags: code128, set-height, png, barcodegenerator, parameters using System; -using Aspose.BarCode.Generation; using Aspose.BarCode; +using Aspose.BarCode.Generation; /// -/// Demonstrates setting the barcode height to 50 mm while keeping the default XDimension. +/// Generates a Code128 barcode image with a custom height while preserving the default XDimension. /// class Program { /// - /// Entry point. Generates a Code128 barcode with a specific height and saves it as PNG. + /// Entry point of the example. Creates a barcode, configures its height, and saves it as a PNG file. /// static void Main() { - // Initialize a barcode generator for Code128 with the sample text "Sample123" - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Initialize the barcode generator for Code128 symbology + using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) { - // Set the bar height to 50 millimeters; XDimension remains at its default value, - // preserving the original aspect ratio of the barcode. + // Define the data to encode in the barcode + generator.CodeText = "123456"; + + // Set the barcode height to 50 millimeters; XDimension remains at its default value generator.Parameters.Barcode.BarHeight.Millimeters = 50f; - // Save the generated barcode image to a PNG file in the current directory. + // Save the generated barcode image to a PNG file generator.Save("barcode.png"); } - // Inform the user that the barcode has been generated successfully. - Console.WriteLine("Barcode generated successfully."); + // Inform the user that the barcode has been created + Console.WriteLine("Barcode generated and saved as barcode.png"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-barcode-resolution-to-120-dpi-generate-image-and-compare-visual-quality-against-300-dpi-reference.cs b/one-dimensional-barcode-types/set-barcode-resolution-to-120-dpi-generate-image-and-compare-visual-quality-against-300-dpi-reference.cs index 0c42e8b..8fa0c06 100644 --- a/one-dimensional-barcode-types/set-barcode-resolution-to-120-dpi-generate-image-and-compare-visual-quality-against-300-dpi-reference.cs +++ b/one-dimensional-barcode-types/set-barcode-resolution-to-120-dpi-generate-image-and-compare-visual-quality-against-300-dpi-reference.cs @@ -1,72 +1,70 @@ -// Title: Barcode resolution comparison between 120 DPI and 300 DPI -// Description: Demonstrates how to set barcode image resolution, generate PNG files, and compare their DPI metadata. -// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, its Parameters.Resolution property, and image metadata retrieval via Aspose.Drawing. Developers often need to control output resolution for printing or screen display and compare quality across different DPI settings. +// Title: Generate and Compare Barcode Images at Different DPI Settings +// Description: Demonstrates how to set barcode resolution to 120 DPI, generate a PNG image, and compare its pixel dimensions with a 300 DPI reference image. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator, BarCodeImageFormat, and Aspose.Drawing.Image to create barcode images at specific resolutions. Typical scenarios include preparing barcodes for print media where DPI impacts visual quality and scanner readability. Developers often need to adjust resolution, export formats, and verify output size for optimal results. // Prompt: Set barcode resolution to 120 DPI, generate image, and compare visual quality against 300 DPI reference. -// Tags: barcode resolution, code128, png, image generation, aspose.barcode, aspose.drawing +// Tags: barcode, code128, resolution, dpi, image generation, png, aspose.barcode, aspose.drawing using System; -using Aspose.BarCode; +using System.IO; using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Demonstrates setting barcode resolution to 120 DPI, generating an image, and comparing its visual quality against a 300 DPI reference. +/// Example program that creates two barcode images at different DPI settings +/// and compares their pixel dimensions to illustrate the effect of resolution. /// class Program { /// - /// Entry point that creates low‑ and high‑resolution Code128 barcodes, reads their DPI metadata, and outputs a simple quality comparison. + /// Entry point of the application. + /// Generates low‑ and high‑resolution barcode images, then prints size comparison. /// static void Main() { - // Define barcode content and output file names - const string codeText = "1234567890"; - const string lowResPath = "barcode_120dpi.png"; - const string highResPath = "barcode_300dpi.png"; + // Ensure the output directory exists + string outputFolder = "output"; + Directory.CreateDirectory(outputFolder); - // Generate low‑resolution barcode (120 DPI) - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) - { - generator.Parameters.Resolution = 120f; // set resolution to 120 DPI - generator.Save(lowResPath, BarCodeImageFormat.Png); - } + // Define file paths for the low‑resolution (120 DPI) and high‑resolution (300 DPI) images + string lowResPath = Path.Combine(outputFolder, "barcode_120dpi.png"); + string highResPath = Path.Combine(outputFolder, "barcode_300dpi.png"); - // Generate high‑resolution reference barcode (300 DPI) - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // -------------------- Generate barcode at 120 DPI -------------------- + using (var generatorLow = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - generator.Parameters.Resolution = 300f; // set resolution to 300 DPI - generator.Save(highResPath, BarCodeImageFormat.Png); + // Set the desired resolution (dots per inch) + generatorLow.Parameters.Resolution = 120f; + // Save the barcode as a PNG file + generatorLow.Save(lowResPath, BarCodeImageFormat.Png); } - // Load the generated images to read their DPI metadata - float lowResHorizontal, lowResVertical; - float highResHorizontal, highResVertical; - - using (var img = Image.FromFile(lowResPath)) + // -------------------- Generate barcode at 300 DPI -------------------- + using (var generatorHigh = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - lowResHorizontal = img.HorizontalResolution; - lowResVertical = img.VerticalResolution; + // Set a higher resolution for finer visual detail + generatorHigh.Parameters.Resolution = 300f; + // Save the barcode as a PNG file + generatorHigh.Save(highResPath, BarCodeImageFormat.Png); } - using (var img = Image.FromFile(highResPath)) + // -------------------- Load images and compare dimensions -------------------- + using (var lowImage = Image.FromFile(lowResPath)) + using (var highImage = Image.FromFile(highResPath)) { - highResHorizontal = img.HorizontalResolution; - highResVertical = img.VerticalResolution; - } + // Output the pixel width and height of each image + Console.WriteLine($"120 DPI image size: {lowImage.Width}×{lowImage.Height} pixels"); + Console.WriteLine($"300 DPI image size: {highImage.Width}×{highImage.Height} pixels"); - // Output the resolution values for comparison - Console.WriteLine($"Low‑resolution image DPI: {lowResHorizontal}x{lowResVertical}"); - Console.WriteLine($"High‑resolution reference DPI: {highResHorizontal}x{highResVertical}"); - - // Simple visual quality comparison based on DPI - if (lowResHorizontal < highResHorizontal && lowResVertical < highResVertical) - { - Console.WriteLine("The low‑resolution barcode may appear less sharp than the 300 DPI reference."); - } - else - { - Console.WriteLine("Resolution comparison could not be performed as expected."); + // Determine whether the higher DPI produced a larger pixel image + if (highImage.Width > lowImage.Width && highImage.Height > lowImage.Height) + { + Console.WriteLine("Higher DPI produces a larger pixel image, indicating higher visual detail."); + } + else + { + Console.WriteLine("Unexpected size relationship between DPI settings."); + } } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-barcode-resolution-to-200-dpi-generate-image-and-compare-file-size-against-300-dpi-version.cs b/one-dimensional-barcode-types/set-barcode-resolution-to-200-dpi-generate-image-and-compare-file-size-against-300-dpi-version.cs index 9b70158..dae7c38 100644 --- a/one-dimensional-barcode-types/set-barcode-resolution-to-200-dpi-generate-image-and-compare-file-size-against-300-dpi-version.cs +++ b/one-dimensional-barcode-types/set-barcode-resolution-to-200-dpi-generate-image-and-compare-file-size-against-300-dpi-version.cs @@ -1,8 +1,8 @@ -// Title: Barcode resolution comparison between 200 DPI and 300 DPI -// Description: Demonstrates how to set barcode image resolution using Aspose.BarCode, generate PNG images at two DPI settings, and compare their file sizes. -// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes. Developers often need to control image resolution for printing or display quality, and compare resulting file sizes to optimize storage or performance. +// Title: Compare barcode image file sizes at different DPI settings +// Description: Generates a Code128 barcode image at 200 DPI and 300 DPI, saves them as PNG files, and reports their file sizes to illustrate the impact of resolution on output size. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, demonstrating how to configure the resolution parameter of BarcodeGenerator, save images in PNG format, and perform basic file‑system validation. Developers working with barcode rendering often need to adjust DPI for print quality or file‑size optimization, using classes such as BarcodeGenerator, BarCodeImageFormat, and the Parameters property. // Prompt: Set barcode resolution to 200 DPI, generate image, and compare file size against 300 DPI version. -// Tags: barcode, resolution, png, code128, image-generation, file-size-comparison +// Tags: barcode, code128, resolution, dpi, image generation, file size comparison, aspose.barcode, png using System; using System.IO; @@ -10,63 +10,69 @@ using Aspose.BarCode.Generation; /// -/// Generates Code128 barcodes at two different resolutions (200 DPI and 300 DPI), -/// saves them as PNG files, and compares the resulting file sizes. +/// Demonstrates how to generate barcode images at different DPI settings +/// and compare their resulting file sizes. /// class Program { /// - /// Entry point of the example. Creates barcode images, verifies their existence, - /// and outputs a size comparison to the console. + /// Entry point of the example. Generates two PNG barcode images + /// (200 DPI and 300 DPI) and prints their file sizes for comparison. /// static void Main() { - // Define barcode content and output file names - const string barcodeText = "123456789"; + // Define the barcode content and the output file names. + string codeText = "123456"; string file200 = "barcode_200dpi.png"; string file300 = "barcode_300dpi.png"; - // Generate barcode image at 200 DPI - using (var generator200 = new BarcodeGenerator(EncodeTypes.Code128, barcodeText)) + // ------------------------------------------------------------ + // Generate a barcode image with a resolution of 200 DPI. + // ------------------------------------------------------------ + using (var generator200 = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - generator200.Parameters.Resolution = 200f; // set resolution to 200 DPI + // Set the resolution (dots per inch) for the image. + generator200.Parameters.Resolution = 200f; + // Save the generated barcode as a PNG file. generator200.Save(file200, BarCodeImageFormat.Png); } - // Generate barcode image at 300 DPI - using (var generator300 = new BarcodeGenerator(EncodeTypes.Code128, barcodeText)) + // ------------------------------------------------------------ + // Generate a barcode image with a resolution of 300 DPI. + // ------------------------------------------------------------ + using (var generator300 = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - generator300.Parameters.Resolution = 300f; // set resolution to 300 DPI + generator300.Parameters.Resolution = 300f; generator300.Save(file300, BarCodeImageFormat.Png); } - // Verify that both files were successfully created + // Verify that both image files were successfully created. if (!File.Exists(file200) || !File.Exists(file300)) { - Console.WriteLine("Failed to generate one or both barcode images."); + Console.WriteLine("Failed to create one or both barcode images."); return; } - // Retrieve file sizes in bytes + // Retrieve the file sizes (in bytes) for each image. long size200 = new FileInfo(file200).Length; long size300 = new FileInfo(file300).Length; - // Display file sizes + // Output the file sizes to the console. Console.WriteLine($"200 DPI file size: {size200} bytes"); Console.WriteLine($"300 DPI file size: {size300} bytes"); - // Compare and report which image is larger - if (size200 == size300) + // Compare the sizes and report which image is smaller. + if (size200 < size300) { - Console.WriteLine("Both images have the same file size."); + Console.WriteLine("The 200 DPI image is smaller than the 300 DPI image."); } else if (size200 > size300) { - Console.WriteLine("200 DPI image is larger than 300 DPI image."); + Console.WriteLine("The 300 DPI image is smaller than the 200 DPI image."); } else { - Console.WriteLine("300 DPI image is larger than 200 DPI image."); + Console.WriteLine("Both images have the same file size."); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-barcode-resolution-to-250-dpi-generate-png-and-evaluate-file-size-for-storage-optimization.cs b/one-dimensional-barcode-types/set-barcode-resolution-to-250-dpi-generate-png-and-evaluate-file-size-for-storage-optimization.cs index cc0eab2..28bb34d 100644 --- a/one-dimensional-barcode-types/set-barcode-resolution-to-250-dpi-generate-png-and-evaluate-file-size-for-storage-optimization.cs +++ b/one-dimensional-barcode-types/set-barcode-resolution-to-250-dpi-generate-png-and-evaluate-file-size-for-storage-optimization.cs @@ -1,8 +1,8 @@ -// Title: Generate Code128 barcode PNG with 250 DPI resolution -// Description: Demonstrates setting barcode image resolution to 250 DPI, saving as PNG, and checking file size for storage optimization. -// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to configure resolution, choose output format, and evaluate generated file size. It uses BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes, common tasks for developers needing high‑resolution barcodes for printing or digital storage while managing file size. +// Title: Generate Code128 barcode PNG at 250 DPI and assess file size +// Description: This example creates a Code128 barcode, sets the image resolution to 250 DPI, saves it as a PNG, and reports the resulting file size for storage considerations. +// Category-Description: Demonstrates Aspose.BarCode generation features such as barcode symbology selection, image resolution configuration, and output format handling. It showcases the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes to produce high‑resolution barcode images, a common requirement for printing, scanning, and archival storage scenarios. Developers looking for barcode creation, image quality tuning, and file size evaluation will find this pattern useful. // Prompt: Set barcode resolution to 250 DPI, generate PNG, and evaluate file size for storage optimization. -// Tags: code128, resolution, png, file-size, barcode-generation, aspose.barcode +// Tags: code128, barcode, resolution, png, file-size, aspose.barcode, generation using System; using System.IO; @@ -10,40 +10,44 @@ using Aspose.BarCode.Generation; /// -/// Example program that creates a Code128 barcode, sets a high image resolution, -/// saves it as a PNG file, and reports the resulting file size. +/// Demonstrates generating a Code128 barcode PNG with a custom resolution and measuring its file size. /// class Program { /// - /// Entry point of the example. Generates the barcode and evaluates its file size. + /// Entry point that creates the barcode, sets resolution, saves to PNG, and outputs file size. /// - /// Command‑line arguments (not used). - static void Main(string[] args) + static void Main() { - // Define the output file path for the generated PNG image - string outputPath = "barcode.png"; + // Define the output file name for the generated PNG image + const string outputFile = "barcode.png"; - // Initialize a BarcodeGenerator for Code128 with the sample text "Sample123" - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Initialize a barcode generator for the Code128 symbology with sample text + using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) { + generator.CodeText = "1234567890"; + // Configure the image resolution to 250 DPI for higher quality output generator.Parameters.Resolution = 250f; - // Save the generated barcode as a PNG image to the specified path - generator.Save(outputPath, BarCodeImageFormat.Png); - } + // Save the barcode image to a memory stream in PNG format + using (var memoryStream = new MemoryStream()) + { + generator.Save(memoryStream, BarCodeImageFormat.Png); - // Verify that the file was created and output its size for storage analysis - if (File.Exists(outputPath)) - { - var fileInfo = new FileInfo(outputPath); - Console.WriteLine($"Generated barcode saved to {outputPath}"); - Console.WriteLine($"File size: {fileInfo.Length} bytes"); - } - else - { - Console.WriteLine("Failed to generate barcode image."); + // Determine the size of the generated PNG file in bytes + long fileSize = memoryStream.Length; + Console.WriteLine($"Generated barcode size: {fileSize} bytes"); + + // Reset the stream position before writing to disk + memoryStream.Position = 0; + + // Write the PNG image from the memory stream to the specified file + using (var fileStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write)) + { + memoryStream.CopyTo(fileStream); + } + } } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-barcode-resolution-to-72-dpi-for-quick-preview-generation-in-web-thumbnail-view.cs b/one-dimensional-barcode-types/set-barcode-resolution-to-72-dpi-for-quick-preview-generation-in-web-thumbnail-view.cs index 2e99b4c..05b5bbb 100644 --- a/one-dimensional-barcode-types/set-barcode-resolution-to-72-dpi-for-quick-preview-generation-in-web-thumbnail-view.cs +++ b/one-dimensional-barcode-types/set-barcode-resolution-to-72-dpi-for-quick-preview-generation-in-web-thumbnail-view.cs @@ -1,41 +1,35 @@ -// Title: Generate barcode thumbnail with 72 DPI resolution -// Description: Demonstrates setting barcode resolution to 72 DPI and creating a small PNG thumbnail for web preview. -// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to configure resolution, size, and auto‑size mode using BarcodeGenerator and its Parameters. Developers often need to produce low‑resolution barcode images for quick previews, thumbnails, or email attachments, and this snippet shows the typical API usage for such scenarios. +// Title: Generate a low‑resolution barcode thumbnail (72 DPI) using Aspose.BarCode +// Description: Demonstrates how to create a Code128 barcode image with a resolution of 72 DPI, suitable for quick preview thumbnails in web applications. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and resolution settings. Developers often need to produce low‑resolution barcode images for thumbnails, previews, or email attachments, where speed and file size are more important than print quality. The snippet shows the typical workflow of configuring barcode parameters and saving the result. // Prompt: Set barcode resolution to 72 DPI for quick preview generation in a web thumbnail view. -// Tags: barcode, code128, resolution, preview, thumbnail, png, aspnet, aspose.barcode, imagegeneration +// Tags: barcode, code128, resolution, thumbnail, preview, aspose.barcode, image generation, png using System; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; -namespace BarcodePreview +/// +/// Example program that creates a Code128 barcode image with a low resolution (72 DPI) for use as a web thumbnail. +/// +class Program { /// - /// Generates a Code128 barcode image optimized for thumbnail preview with a resolution of 72 DPI. + /// Entry point of the example. Generates the barcode and saves it as a PNG file. /// - class Program + static void Main() { - /// - /// Entry point that creates and saves a low‑resolution barcode PNG suitable for web thumbnails. - /// - static void Main() + // Initialize a barcode generator for the Code128 symbology. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) { - // Initialize the barcode generator with Code128 symbology and sample data. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample")) - { - // Set the image resolution to 72 DPI for faster rendering and smaller file size. - generator.Parameters.Resolution = 72f; + // Define the data to encode in the barcode. + generator.CodeText = "123456"; - // Choose interpolation auto‑size mode to keep the barcode sharp at the target dimensions. - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; + // Configure the image resolution to 72 DPI to keep the file lightweight for quick previews. + generator.Parameters.Resolution = 72f; - // Define the thumbnail dimensions in points (1 point = 1/72 inch). - generator.Parameters.ImageWidth.Point = 150f; // Approx. 2.08 inches wide - generator.Parameters.ImageHeight.Point = 50f; // Approx. 0.69 inches tall - - // Save the generated barcode as a PNG file named "thumbnail.png". - generator.Save("thumbnail.png"); - } + // Render the barcode and write it to a PNG file. + generator.Save("barcode_thumbnail.png"); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-barcode-resolution-to-96-dpi-for-standard-screen-display-then-render-image-for-web-preview.cs b/one-dimensional-barcode-types/set-barcode-resolution-to-96-dpi-for-standard-screen-display-then-render-image-for-web-preview.cs index 88943d3..0cea7d8 100644 --- a/one-dimensional-barcode-types/set-barcode-resolution-to-96-dpi-for-standard-screen-display-then-render-image-for-web-preview.cs +++ b/one-dimensional-barcode-types/set-barcode-resolution-to-96-dpi-for-standard-screen-display-then-render-image-for-web-preview.cs @@ -1,14 +1,17 @@ -// Title: Set Barcode Resolution to 96 DPI and Save as PNG -// Description: Demonstrates setting the barcode image resolution to 96 DPI for standard screen display and saving it as a PNG file. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure image resolution using the BarcodeGenerator class. Typical use cases include creating barcodes for web previews, reports, or UI elements where screen‑friendly DPI is required. Developers often need to adjust resolution, select symbology, and export to common image formats. +// Title: Generate Code128 barcode image with 96 DPI resolution for web preview +// Description: Demonstrates how to set the barcode image resolution to 96 DPI, suitable for standard screen display, and save it as a PNG file for web usage. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator and its Parameters to control output quality. Typical scenarios include creating barcodes for e‑commerce sites, online tickets, or any web‑based application where screen‑optimized images are required. Developers often need to adjust resolution, format, and encoding to meet UI and performance constraints. // Prompt: Set barcode resolution to 96 DPI for standard screen display, then render image for web preview. -// Tags: code128, barcode generation, resolution, png, aspose.barcode, image export +// Tags: code128, resolution, png, barcodegenerator, aspose.barcode using System; +using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Example program that generates a Code128 barcode, sets its resolution to 96 DPI, +/// Example program that creates a Code128 barcode, sets its resolution to 96 DPI, /// and saves the result as a PNG image suitable for web preview. /// class Program @@ -21,20 +24,24 @@ static void Main() // Define the output file path for the generated barcode image. string outputPath = "barcode.png"; - // Initialize a BarcodeGenerator for the Code128 symbology. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) + // Ensure the target directory exists; create it if necessary. + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(outputDir)) { - // Specify the text to encode in the barcode. - generator.CodeText = "1234567890"; + Directory.CreateDirectory(outputDir); + } - // Configure the image resolution to 96 DPI (standard screen display). + // Initialize a BarcodeGenerator for Code128 symbology with sample data. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + { + // Configure the generator to use a screen‑friendly resolution of 96 DPI. generator.Parameters.Resolution = 96f; - // Save the barcode image to the specified file in PNG format. - generator.Save(outputPath); + // Save the generated barcode as a PNG file, ideal for web display. + generator.Save(outputPath, BarCodeImageFormat.Png); } - // Inform the user where the barcode image has been saved. - Console.WriteLine($"Barcode image saved to {outputPath}"); + // Output the absolute path of the saved image for verification. + Console.WriteLine($"Barcode image saved to: {Path.GetFullPath(outputPath)}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-barcode-text-font-to-comic-sans-ms-size-11-pt-and-align-text-centrally-for-decorative-labels.cs b/one-dimensional-barcode-types/set-barcode-text-font-to-comic-sans-ms-size-11-pt-and-align-text-centrally-for-decorative-labels.cs index b927436..72a2765 100644 --- a/one-dimensional-barcode-types/set-barcode-text-font-to-comic-sans-ms-size-11-pt-and-align-text-centrally-for-decorative-labels.cs +++ b/one-dimensional-barcode-types/set-barcode-text-font-to-comic-sans-ms-size-11-pt-and-align-text-centrally-for-decorative-labels.cs @@ -1,40 +1,39 @@ -// Title: Set Barcode Text Font and Alignment for Decorative Labels -// Description: Demonstrates how to set the human‑readable text font to Comic Sans MS, size 11 pt, and center it beneath a Code128 barcode, then save the image as PNG. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator and CodeTextParameters to customize barcode appearance. Developers commonly need to adjust font, size, and alignment of human‑readable text for branding, labeling, and decorative purposes. Typical use cases include creating product labels, tickets, and promotional materials where visual style matters. +// Title: Generate a Code128 barcode with custom Comic Sans text for decorative labels +// Description: Demonstrates how to set the human‑readable text font to Comic Sans MS, size 11 pt, and center‑align it when generating a Code128 barcode image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and CodeTextParameters to customize text appearance. Typical use cases include creating branded or decorative labels where font style and alignment are important. Developers often need to adjust font family, size, and alignment to match design guidelines. // Prompt: Set barcode text font to Comic Sans MS, size 11 pt, and align text centrally for decorative labels. -// Tags: code128, font, png, barcodegenerator, codetextparameters +// Tags: code128, barcode generation, text formatting, font customization, image output, aspose.barcode, aspose.drawing -using System; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Example program that generates a Code128 barcode with customized text font and alignment, -/// then saves it as a PNG image. +/// Provides an example of generating a Code128 barcode with custom text formatting. /// -class Program +public class Program { /// - /// Entry point of the application. Creates a barcode, configures text appearance, - /// saves the image, and writes a confirmation message to the console. + /// Entry point that creates the barcode image with Comic Sans font, 11 pt size, centered text, and saves it as PNG. /// - static void Main() + public static void Main() { - // Initialize a BarcodeGenerator for Code128 with the sample value "DecorativeLabel" + // Initialize the barcode generator with Code128 symbology and the desired data. using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "DecorativeLabel")) { - // Configure the human‑readable text font to Comic Sans MS, 11 pt + // Set the human‑readable text font to Comic Sans MS, 11 pt. generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Comic Sans MS"; generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 11f; - // Align the text centrally beneath the barcode + // Align the human‑readable text centrally beneath the barcode. generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center; - // Save the generated barcode as a PNG file - generator.Save("decorative_label.png"); + // Generate the barcode image (returned as Aspose.Drawing.Bitmap). + using (Aspose.Drawing.Bitmap image = generator.GenerateBarCodeImage()) + { + // Save the generated barcode image to a PNG file. + generator.Save("decorative_label.png"); + } } - - // Inform the user that the barcode has been generated and saved - Console.WriteLine("Barcode generated and saved as decorative_label.png"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-barcode-text-font-to-times-new-roman-italic-style-size-16-pt-for-emphasis.cs b/one-dimensional-barcode-types/set-barcode-text-font-to-times-new-roman-italic-style-size-16-pt-for-emphasis.cs index 7a92ec7..fc294e2 100644 --- a/one-dimensional-barcode-types/set-barcode-text-font-to-times-new-roman-italic-style-size-16-pt-for-emphasis.cs +++ b/one-dimensional-barcode-types/set-barcode-text-font-to-times-new-roman-italic-style-size-16-pt-for-emphasis.cs @@ -1,37 +1,40 @@ -// Title: Set barcode text font to Times New Roman, italic, 16 pt -// Description: Demonstrates how to change the human‑readable text font of a barcode using Aspose.BarCode. -// Category-Description: This example belongs to the Aspose.BarCode text formatting category, showing how to customize the CodeText font properties such as family, size, and style. It uses BarcodeGenerator, EncodeTypes, and FontStyle classes, which are commonly employed when developers need to emphasize barcode data in generated images or documents. +// Title: Set barcode text font to Times New Roman italic 16pt +// Description: Demonstrates how to customize the human‑readable text font of a Code128 barcode using Aspose.BarCode, saving the result as a PNG image. +// Category-Description: This example belongs to the Aspose.BarCode font customization category, illustrating the use of BarcodeGenerator and CodeTextParameters to modify text appearance. Developers often need to match branding guidelines or emphasize barcode data, and these APIs provide fine‑grained control over font family, style, and size. // Prompt: Set barcode text font to Times New Roman, italic style, size 16 pt for emphasis. -// Tags: barcode, code128, font, text formatting, png, aspose.barcode, generation +// Tags: code128, set-font, png, barcodegenerator, codetextparameters using System; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; -/// -/// Demonstrates setting the barcode's human‑readable text font to Times New Roman, italic, 16 pt. -/// -class Program +namespace BarcodeFontExample { /// - /// Entry point. Generates a Code128 barcode with customized text font and saves it as PNG. + /// Shows how to set the barcode's human‑readable text font to Times New Roman, italic, 16 pt, and save the image. /// - static void Main() + class Program { - // Initialize a barcode generator for Code128 with the sample text "Emphasis Text" - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Emphasis Text")) + /// + /// Entry point of the example. Generates a Code128 barcode with custom font settings and writes the image to disk. + /// + static void Main() { - // Configure the human‑readable text font: - // - Family: Times New Roman - // - Size: 16 points - // - Style: Italic - generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Times New Roman"; - generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 16f; - generator.Parameters.Barcode.CodeTextParameters.Font.Style = FontStyle.Italic; + // Initialize a BarcodeGenerator for Code128 with the sample value "Sample123" + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + { + // Configure the font used for the human‑readable (code text) part of the barcode + generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Times New Roman"; + generator.Parameters.Barcode.CodeTextParameters.Font.Style = Aspose.Drawing.FontStyle.Italic; + generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 16f; - // Save the generated barcode image to a PNG file - generator.Save("barcode.png"); + // Save the generated barcode as a PNG file + generator.Save("barcode.png"); + } + + // Inform the user that the barcode has been created + Console.WriteLine("Barcode generated with custom font."); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-barcode-text-font-to-verdana-bold-style-size-14-pt-for-improved-readability.cs b/one-dimensional-barcode-types/set-barcode-text-font-to-verdana-bold-style-size-14-pt-for-improved-readability.cs index b7163ca..bce78e8 100644 --- a/one-dimensional-barcode-types/set-barcode-text-font-to-verdana-bold-style-size-14-pt-for-improved-readability.cs +++ b/one-dimensional-barcode-types/set-barcode-text-font-to-verdana-bold-style-size-14-pt-for-improved-readability.cs @@ -1,31 +1,40 @@ +// Title: Set barcode text font to Verdana bold 14pt using Aspose.BarCode +// Description: Demonstrates how to change the human‑readable text font of a barcode to Verdana, bold style, 14 pt, and save the image. +// Category-Description: This example belongs to the Aspose.BarCode appearance‑customization category, illustrating how to modify barcode text styling using the BarcodeGenerator class. It covers setting font family, style, and size via CodeTextParameters, a common requirement when generating readable barcodes for print or screen. Developers often need to adjust these properties to match branding guidelines or improve legibility. +// Prompt: Set barcode text font to Verdana, bold style, size 14 pt for improved readability. +// Tags: barcode symbology, text formatting, code128, image output, aspose.barcode, generation + using System; -using Aspose.BarCode.Generation; using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.Drawing; +/// +/// Example program that generates a Code128 barcode with customized text font. +/// class Program { + /// + /// Generates the barcode and saves it to a PNG file. + /// static void Main() { - // Create a barcode generator for Code128 (any symbology can be used) - using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) + // Initialize a barcode generator for Code128 with the sample value "Sample123" + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - // Set the text to be encoded - generator.CodeText = "1234567890"; - - // Configure human‑readable text (code text) appearance - // Font family + // Configure the human‑readable text font: + // - Font family: Verdana + // - Font style: Bold + // - Font size: 14 points generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Verdana"; - // Font size 14 pt + generator.Parameters.Barcode.CodeTextParameters.Font.Style = FontStyle.Bold; generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 14f; - // Bold style – set to true if the property exists - // (If the Font object does not expose a Bold property, this line can be omitted) - // generator.Parameters.Barcode.CodeTextParameters.Font.Bold = true; - // Save the barcode image to a PNG file + // Save the generated barcode as a PNG image generator.Save("barcode.png"); } - Console.WriteLine("Barcode generated and saved as barcode.png"); + // Inform the user that the barcode image has been created + Console.WriteLine("Barcode generated: barcode.png"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-barcode-width-reduction-to-20-percent-to-fit-narrow-label-spaces.cs b/one-dimensional-barcode-types/set-barcode-width-reduction-to-20-percent-to-fit-narrow-label-spaces.cs index 0ec5984..355dc8b 100644 --- a/one-dimensional-barcode-types/set-barcode-width-reduction-to-20-percent-to-fit-narrow-label-spaces.cs +++ b/one-dimensional-barcode-types/set-barcode-width-reduction-to-20-percent-to-fit-narrow-label-spaces.cs @@ -1,36 +1,40 @@ -// Title: Barcode width reduction example using Aspose.BarCode -// Description: Demonstrates how to reduce the bar width of a Code128 barcode by 20 percent to fit narrow label spaces. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to customize barcode appearance using the BarcodeGenerator class and its Parameters.Barcode properties. Typical use cases include adjusting bar dimensions for limited label real‑estate, ensuring readability while meeting size constraints. Developers often need to modify bar width, height, margins, or other visual parameters before saving the barcode to an image or document. +// Title: Apply 20% Width Reduction to a Code128 Barcode +// Description: Demonstrates how to generate a Code128 barcode and reduce its width by 20 percent using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, showcasing the use of BarcodeGenerator, EncodeTypes, and barcode parameter settings. Typical use cases include creating compact barcodes for narrow label spaces, adjusting visual dimensions without altering encoded data, and exporting to common image formats. Developers often need to fine‑tune barcode size for printing constraints, and this snippet illustrates the standard approach. // Prompt: Set barcode width reduction to 20 percent to fit narrow label spaces. -// Tags: barcode, width reduction, code128, png, aspose.barcode, generation +// Tags: code128, width reduction, barcode generation, png, aspose.barcode, c# using System; using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Provides an entry point that generates a Code128 barcode with a 20 percent width reduction -/// and saves it as a PNG image. +/// Generates a Code128 barcode, applies a 20 percent width reduction, and saves it as a PNG image. /// class Program { /// - /// Creates a for Code128, applies a 20 percent bar width reduction, - /// saves the barcode to a file, and writes a completion message to the console. + /// Entry point of the example. Creates the barcode, configures width reduction, and writes the output file. /// static void Main() { - // Initialize the barcode generator with the desired symbology (Code128) and data. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Initialize a barcode generator for the Code128 symbology. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) { - // Apply a 20 percent reduction to the bar width (specified in points). - generator.Parameters.Barcode.BarWidthReduction.Point = 20f; + // Define the data to encode in the barcode. + generator.CodeText = "123456"; - // Save the generated barcode as a PNG image file. - generator.Save("barcode.png"); - } + // Apply a 20 percent width reduction (approximately 0.2 points). + generator.Parameters.Barcode.BarWidthReduction.Point = 0.2f; + + // Specify the output file name and format (PNG by default). + string outputFile = "barcode.png"; - // Output a simple confirmation that the barcode was generated successfully. - Console.WriteLine("Barcode generated with 20% width reduction."); + // Render and save the barcode image to disk. + generator.Save(outputFile); + + // Inform the user that the barcode has been saved. + Console.WriteLine($"Barcode saved to '{outputFile}' with 20% width reduction."); + } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-barcode-xdimension-to-04-mm-and-ydimension-to-25-mm-to-meet-specific-label-dimensions.cs b/one-dimensional-barcode-types/set-barcode-xdimension-to-04-mm-and-ydimension-to-25-mm-to-meet-specific-label-dimensions.cs index 299fcf8..3d8c742 100644 --- a/one-dimensional-barcode-types/set-barcode-xdimension-to-04-mm-and-ydimension-to-25-mm-to-meet-specific-label-dimensions.cs +++ b/one-dimensional-barcode-types/set-barcode-xdimension-to-04-mm-and-ydimension-to-25-mm-to-meet-specific-label-dimensions.cs @@ -1,6 +1,6 @@ // Title: Set XDimension and YDimension for a Code128 barcode -// Description: Demonstrates configuring the module width (XDimension) and bar height (YDimension) of a Code128 barcode using Aspose.BarCode, then saving it as a PNG image. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to customize barcode dimensions with the BarcodeGenerator class. Developers commonly adjust XDimension for module width and YDimension for bar height to meet specific label size requirements, using the Parameters.Barcode properties before rendering the image. +// Description: Demonstrates how to configure the module size (XDimension) and bar height (YDimension) of a Code128 barcode using Aspose.BarCode and save it as a PNG image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of the BarcodeGenerator class together with EncodeTypes and the Parameters property to customize barcode appearance. Typical use cases include creating labels with precise dimensions for packaging, inventory, or shipping. Developers often need to adjust XDimension and YDimension to meet label size specifications, ensuring readability and scanner compatibility. // Prompt: Set barcode XDimension to 0.4 mm and YDimension to 25 mm to meet specific label dimensions. // Tags: code128, xdimension, ydimension, barcode, generation, png, aspose.barcode @@ -9,26 +9,32 @@ using Aspose.BarCode.Generation; /// -/// Example program that creates a Code128 barcode with custom XDimension and YDimension settings. +/// Example program that creates a Code128 barcode with custom XDimension and YDimension. /// class Program { /// - /// Entry point of the application. Generates a barcode, configures its dimensions, and saves it as a PNG file. + /// Generates a barcode with specified dimensions and saves it to a PNG file. /// static void Main() { - // Initialize a barcode generator for Code128 symbology with the sample text "123456" - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // Initialize a barcode generator for the Code128 symbology + using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) { - // Set the module width (XDimension) to 0.4 mm + // Configure the module size (XDimension) to 0.4 millimeters generator.Parameters.Barcode.XDimension.Millimeters = 0.4f; - // Set the bar height (YDimension) to 25 mm + // Configure the bar height (YDimension) to 25 millimeters generator.Parameters.Barcode.BarHeight.Millimeters = 25f; - // Render and save the barcode image to a PNG file named "barcode.png" + // Define the text to encode in the barcode + generator.CodeText = "123456"; + + // Save the generated barcode as a PNG image file generator.Save("barcode.png"); } + + // Inform the user that the barcode has been created + Console.WriteLine("Barcode generated and saved as 'barcode.png'."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-codabar-start-symbol-to-c-and-stop-symbol-to-d-then-generate-barcode-with-sample-data.cs b/one-dimensional-barcode-types/set-codabar-start-symbol-to-c-and-stop-symbol-to-d-then-generate-barcode-with-sample-data.cs index f16579d..ca10abc 100644 --- a/one-dimensional-barcode-types/set-codabar-start-symbol-to-c-and-stop-symbol-to-d-then-generate-barcode-with-sample-data.cs +++ b/one-dimensional-barcode-types/set-codabar-start-symbol-to-c-and-stop-symbol-to-d-then-generate-barcode-with-sample-data.cs @@ -1,39 +1,39 @@ -// Title: Generate Codabar Barcode with Custom Start/Stop Symbols -// Description: Demonstrates how to set Codabar start and stop symbols and generate a PNG barcode image. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and Codabar parameters to customize barcode symbology. Typical use cases include creating printable labels, inventory tags, or scanning-friendly images where specific start/stop characters are required. Developers often need to adjust these symbols to meet industry standards or legacy system requirements. +// Title: Generate Codabar barcode with custom start/stop symbols +// Description: Demonstrates how to set the Codabar start symbol to C and stop symbol to D, then generate and save the barcode as a PNG image. +// Category-Description: Examples of barcode generation using Aspose.BarCode, focusing on configuring symbology-specific parameters. This collection shows how to use BarcodeGenerator, EncodeTypes, and barcode parameter objects to customize barcodes such as Codabar, QR, and Code128 for various output formats. Developers often need to set start/stop symbols, error correction levels, or visual styles before saving the image. // Prompt: Set Codabar start symbol to C and stop symbol to D, then generate barcode with sample data. -// Tags: codabar, barcode, generation, png, startsymbol, stopsymbol, aspose.barcode +// Tags: codabar, start-stop-symbol, png, aspose.barcode, aspose.barcode.generation using System; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Example program that creates a Codabar barcode with custom start and stop symbols. +/// Demonstrates generating a Codabar barcode with custom start and stop symbols using Aspose.BarCode. /// class Program { /// - /// Entry point of the application. Generates a Codabar barcode using sample data, - /// sets the start symbol to 'C' and the stop symbol to 'D', and saves the image as PNG. + /// Entry point that creates the barcode, configures symbols, and saves it as a PNG file. /// static void Main() { - // Sample codetext (without start/stop symbols; they are defined via parameters) - const string sampleCode = "123456"; + // Sample data to encode + const string codeText = "123456"; - // Initialize a Codabar barcode generator with the sample codetext - using (var generator = new BarcodeGenerator(EncodeTypes.Codabar, sampleCode)) + // Initialize a BarcodeGenerator for Codabar with the sample data + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Codabar, codeText)) { - // Configure the Codabar start and stop symbols - generator.Parameters.Barcode.Codabar.StartSymbol = CodabarSymbol.C; // start symbol 'C' - generator.Parameters.Barcode.Codabar.StopSymbol = CodabarSymbol.D; // stop symbol 'D' + // Configure the start and stop symbols (C and D respectively) + generator.Parameters.Barcode.Codabar.StartSymbol = CodabarSymbol.C; + generator.Parameters.Barcode.Codabar.StopSymbol = CodabarSymbol.D; - // Save the generated barcode image to a PNG file + // Save the generated barcode as a PNG image generator.Save("codabar.png"); } - // Inform the user that the barcode has been created + // Inform the user that the barcode has been generated Console.WriteLine("Codabar barcode generated and saved as 'codabar.png'."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-code-16k-left-quiet-zone-coefficient-05-and-right-coefficient-07-export-jpeg.cs b/one-dimensional-barcode-types/set-code-16k-left-quiet-zone-coefficient-05-and-right-coefficient-07-export-jpeg.cs index 8a514cb..9d73a14 100644 --- a/one-dimensional-barcode-types/set-code-16k-left-quiet-zone-coefficient-05-and-right-coefficient-07-export-jpeg.cs +++ b/one-dimensional-barcode-types/set-code-16k-left-quiet-zone-coefficient-05-and-right-coefficient-07-export-jpeg.cs @@ -1,8 +1,8 @@ -// Title: Set Code 16K Quiet Zone Coefficients and Export as JPEG -// Description: Demonstrates how to configure quiet‑zone coefficients for a Code 16K barcode and save it as a JPEG image. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and barcode parameter settings such as quiet‑zone coefficients. Developers often need to adjust quiet zones for scanner compatibility or layout requirements, and then export the barcode to common image formats like JPEG. +// Title: Set Code 16K quiet‑zone coefficients and export as JPEG +// Description: Demonstrates how to configure left and right quiet‑zone coefficients for a Code 16K barcode using Aspose.BarCode and save the result as a JPEG image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and barcode parameter settings such as quiet‑zone coefficients. Typical use cases include customizing barcode appearance for printing or digital display, where precise quiet‑zone control is required. Developers often need to adjust these settings to meet scanner specifications or layout constraints. // Prompt: Set Code 16K left quiet zone coefficient 0.5 and right coefficient 0.7, export JPEG. -// Tags: code16k, quietzone, jpeg, aspose.barcode, barcode generation +// Tags: code16k, quiet zone, jpeg, barcode generation, aspose.barcode, aspose.drawing using System; using Aspose.BarCode.Generation; @@ -10,44 +10,45 @@ using Aspose.Drawing.Imaging; /// -/// Generates a Code 16K barcode, demonstrates handling of quiet‑zone coefficient constraints, -/// and saves the result as a JPEG image. +/// Entry point for the Code16K quiet‑zone demonstration. /// class Program { /// - /// Entry point of the example. Configures quiet‑zone coefficients (if valid) and exports the barcode. + /// Configures quiet‑zone coefficients for a Code16K barcode and saves it as a JPEG file. /// static void Main() { - // Desired quiet‑zone coefficients (the task requests fractional values) - float leftCoefRequested = 0.5f; - float rightCoefRequested = 0.7f; + // Desired quiet‑zone coefficients (the API expects integers, so non‑integer values are invalid) + double leftCoefRequested = 0.5; + double rightCoefRequested = 0.7; - // Code16K quiet‑zone coefficients are integer properties. - // If non‑integer values are supplied we cannot assign them. - // Inform the user and retain default coefficients. + // Validate that the coefficients are whole numbers because the properties are of type int if (leftCoefRequested % 1 != 0 || rightCoefRequested % 1 != 0) { - Console.WriteLine("Code16K quiet‑zone coefficients must be integers. Using default values."); + Console.WriteLine("Error: Code16K quiet‑zone coefficients must be integer values. " + + $"Requested values: left={leftCoefRequested}, right={rightCoefRequested}"); + return; } - // Sample Code16K barcode text (any valid string for Code16K) - string codeText = "12345678901234567890"; + // Sample codetext for Code16K (any non‑empty string is acceptable for demonstration) + string codeText = "1234567890"; - // Create the generator for Code16K symbology + // Create the barcode generator for Code16K using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, codeText)) { - // Set integer quiet‑zone coefficients only if they are whole numbers. - // In this example we keep defaults because the requested values are fractional. - // Example of setting integer values: - // generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = 1; - // generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = 2; + // Apply integer quiet‑zone coefficients + generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef = (int)leftCoefRequested; + generator.Parameters.Barcode.Code16K.QuietZoneRightCoef = (int)rightCoefRequested; - // Export the barcode as JPEG - generator.Save("code16k.jpg"); - } + // Optional: set a simple appearance (black bars on white background) + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; - Console.WriteLine("Barcode generated: code16k.jpg"); + // Define output file path and save the barcode as a JPEG image + string outputPath = "code16k.jpg"; + generator.Save(outputPath, BarCodeImageFormat.Jpeg); + Console.WriteLine($"Barcode saved to {outputPath}"); + } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-databar-stacked-parameters-aspect-ratio-twelve-enable-2d-component-generate-pdf-output.cs b/one-dimensional-barcode-types/set-databar-stacked-parameters-aspect-ratio-twelve-enable-2d-component-generate-pdf-output.cs index 9d81d93..92768c0 100644 --- a/one-dimensional-barcode-types/set-databar-stacked-parameters-aspect-ratio-twelve-enable-2d-component-generate-pdf-output.cs +++ b/one-dimensional-barcode-types/set-databar-stacked-parameters-aspect-ratio-twelve-enable-2d-component-generate-pdf-output.cs @@ -1,38 +1,69 @@ -// Title: Generate DataBar Stacked Barcode with 2D Composite Component and PDF Output -// Description: Demonstrates setting DataBar stacked aspect ratio to 12, enabling the 2D composite component, and saving the result as a PDF file. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure DataBar stacked symbology using the BarcodeGenerator class. Typical use cases include creating retail product barcodes with composite components for additional data. Developers often need to adjust aspect ratios, enable 2D components, and export barcodes to various formats such as PDF. +// Title: Generate DataBar Stacked barcode with 2D component and export to PDF +// Description: Demonstrates how to configure a DataBar Stacked barcode, set its aspect ratio, enable the 2D composite component, and embed the resulting image into a PDF file using Aspose.BarCode and Aspose.Pdf. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on DataBar symbologies. It showcases the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to create a barcode, and Aspose.Pdf Document and Image classes to embed the barcode into a PDF. Typical scenarios include generating product labels, receipts, or any documents that require high‑density barcodes with optional 2D components. // Prompt: Set DataBar stacked parameters aspect ratio twelve, enable 2D component, generate PDF output. -// Tags: databar stacked, aspect ratio, 2d component, pdf output, aspose.barcode, barcode generation +// Tags: databar, stacked, aspectratio, 2dcomponent, pdf, aspose.barcode, aspose.pdf, barcode-generation using System; -using Aspose.BarCode; +using System.IO; using Aspose.BarCode.Generation; +using Aspose.Pdf; /// -/// Example program that creates a DataBar Stacked barcode, configures its aspect ratio, -/// enables the 2D composite component, and saves the result as a PDF file. +/// Example program that creates a DataBar Stacked barcode with a 2D composite component, +/// embeds it into a PDF document, and saves the result to disk. /// class Program { /// - /// Entry point of the example. Generates the barcode and writes it to "databar_stacked.pdf". + /// Entry point of the application. /// static void Main() { - // Sample GTIN code text suitable for DataBar stacked symbology - const string codeText = "(01)12345678901231"; + // Define the output PDF file name. + const string outputPdfPath = "DataBarStacked.pdf"; - // Initialize a BarcodeGenerator for DataBar stacked symbology with the provided text - using (var generator = new BarcodeGenerator(EncodeTypes.DatabarStacked, codeText)) + // Initialize a barcode generator for the DataBar Stacked symbology. + using (var generator = new BarcodeGenerator(EncodeTypes.DatabarStacked)) { - // Set the aspect ratio of the DataBar stacked module to 12 (wide modules) - generator.Parameters.Barcode.DataBar.AspectRatio = 12f; + // Set the barcode text to a sample GTIN code (required format for DataBar Stacked). + generator.CodeText = "(01)12345678901231"; - // Enable the 2D composite component for the DataBar barcode - generator.Parameters.Barcode.DataBar.Is2DCompositeComponent = true; + // Configure DataBar‑specific parameters. + generator.Parameters.Barcode.DataBar.AspectRatio = 12f; // Aspect ratio = 12 + generator.Parameters.Barcode.DataBar.Is2DCompositeComponent = true; // Enable 2D component - // Save the generated barcode as a PDF file in the current directory - generator.Save("databar_stacked.pdf"); + // Render the barcode to a memory stream in PNG format. + using (var barcodeStream = new MemoryStream()) + { + generator.Save(barcodeStream, BarCodeImageFormat.Png); + barcodeStream.Position = 0; // Reset stream position for subsequent reading. + + // Create a new PDF document and add a page. + using (var pdfDoc = new Document()) + { + var page = pdfDoc.Pages.Add(); + + // Create an Aspose.Pdf.Image object that reads the barcode from the stream. + var pdfImage = new Aspose.Pdf.Image + { + ImageStream = barcodeStream, + FixWidth = 200f, + FixHeight = 100f, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }; + + // Add the image to the page's paragraph collection. + page.Paragraphs.Add(pdfImage); + + // Save the PDF document to the specified file. + pdfDoc.Save(outputPdfPath); + } + } } + + // Inform the user where the PDF was saved. + Console.WriteLine($"PDF with DataBar Stacked barcode saved to: {outputPdfPath}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-xdimension-to-033-mm-for-code-16k-generation-verify-quiet-zone-scaling.cs b/one-dimensional-barcode-types/set-xdimension-to-033-mm-for-code-16k-generation-verify-quiet-zone-scaling.cs index a83e67e..ff35752 100644 --- a/one-dimensional-barcode-types/set-xdimension-to-033-mm-for-code-16k-generation-verify-quiet-zone-scaling.cs +++ b/one-dimensional-barcode-types/set-xdimension-to-033-mm-for-code-16k-generation-verify-quiet-zone-scaling.cs @@ -1,49 +1,53 @@ -// Title: Set XDimension for Code 16K and verify quiet zone scaling -// Description: Demonstrates how to configure the XDimension of a Code 16K barcode to 0.33 mm and calculate the resulting quiet zone sizes. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and barcode parameter settings. Developers often need to adjust module size (XDimension) and quiet zone coefficients for precise barcode printing and scanning requirements. The snippet shows typical steps for configuring dimensions, retrieving default quiet‑zone coefficients, and saving the output image. +// Title: Set XDimension for Code 16K barcode and verify quiet zone scaling +// Description: Demonstrates how to configure the XDimension of a Code 16K barcode to 0.33 mm, retrieve quiet‑zone coefficients, calculate their sizes, and save the result as a PNG image. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and barcode parameter settings. Typical use cases include customizing barcode dimensions, quiet‑zone handling, and exporting images for printing or display. Developers often need to adjust XDimension and quiet‑zone values to meet specific scanning standards. // Prompt: Set XDimension to 0.33 mm for Code 16K generation, verify quiet zone scaling. -// Tags: code16k, xdimension, quietzone, barcode generation, png, aspose.barcode +// Tags: barcode, code16k, xdimension, quietzone, generation, png, aspose.barcode using System; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Demonstrates setting XDimension for a Code 16K barcode and verifying quiet zone scaling. +/// Generates a Code 16K barcode, sets a custom XDimension, verifies quiet‑zone scaling, +/// and saves the barcode as a PNG image. /// class Program { /// - /// Entry point. Generates a Code 16K barcode with XDimension 0.33 mm, computes quiet zones, and saves the image. + /// Entry point of the example. Creates a BarcodeGenerator, configures parameters, + /// outputs verification data, and writes the barcode image to disk. /// static void Main() { - // Sample codetext for Code16K (any alphanumeric string is acceptable) - const string codeText = "SampleCode16K"; - - // Initialize the barcode generator for Code16K with the provided text - using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, codeText)) + // Initialize a BarcodeGenerator for the Code16K symbology + using (var generator = new BarcodeGenerator(EncodeTypes.Code16K)) { - // Set the module width (XDimension) to 0.33 millimeters + // Assign sample data to be encoded + generator.CodeText = "1234567890123456789012345678901234567890"; + + // Set the XDimension (module width) to 0.33 mm generator.Parameters.Barcode.XDimension.Millimeters = 0.33f; - // Retrieve the default quiet zone coefficients for Code16K (left = 10, right = 1) + // Retrieve the default quiet‑zone coefficients for Code16K int leftCoef = generator.Parameters.Barcode.Code16K.QuietZoneLeftCoef; int rightCoef = generator.Parameters.Barcode.Code16K.QuietZoneRightCoef; - // Calculate the quiet zone sizes in millimeters using the coefficients - float leftQuietZoneMm = leftCoef * generator.Parameters.Barcode.XDimension.Millimeters; - float rightQuietZoneMm = rightCoef * generator.Parameters.Barcode.XDimension.Millimeters; + // Compute the actual quiet‑zone sizes in millimeters + float leftQuietZone = leftCoef * generator.Parameters.Barcode.XDimension.Millimeters; + float rightQuietZone = rightCoef * generator.Parameters.Barcode.XDimension.Millimeters; - // Output the configuration and calculated quiet zone values - Console.WriteLine($"XDimension set to: {generator.Parameters.Barcode.XDimension.Millimeters} mm"); - Console.WriteLine($"Quiet zone left coefficient: {leftCoef}"); - Console.WriteLine($"Quiet zone right coefficient: {rightCoef}"); - Console.WriteLine($"Calculated left quiet zone: {leftQuietZoneMm} mm"); - Console.WriteLine($"Calculated right quiet zone: {rightQuietZoneMm} mm"); + // Output the configuration and calculated quiet‑zone values + Console.WriteLine($"XDimension set to {generator.Parameters.Barcode.XDimension.Millimeters} mm"); + Console.WriteLine($"QuietZoneLeftCoef = {leftCoef}, QuietZoneRightCoef = {rightCoef}"); + Console.WriteLine($"Calculated left quiet zone: {leftQuietZone} mm"); + Console.WriteLine($"Calculated right quiet zone: {rightQuietZone} mm"); - // Save the generated barcode image to a PNG file - generator.Save("code16k.png"); + // Save the generated barcode as a PNG file + string outputPath = "code16k.png"; + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode image saved to '{outputPath}'."); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/set-xdimension-to-05-mm-and-ydimension-to-30-mm-before-generating-barcode-image.cs b/one-dimensional-barcode-types/set-xdimension-to-05-mm-and-ydimension-to-30-mm-before-generating-barcode-image.cs index 6780282..2a90f12 100644 --- a/one-dimensional-barcode-types/set-xdimension-to-05-mm-and-ydimension-to-30-mm-before-generating-barcode-image.cs +++ b/one-dimensional-barcode-types/set-xdimension-to-05-mm-and-ydimension-to-30-mm-before-generating-barcode-image.cs @@ -1,33 +1,37 @@ -// Title: Generate Code128 Barcode with Custom X and Y Dimensions -// Description: This example shows how to set the X‑dimension to 0.5 mm and the image height (Y‑dimension) to 30 mm before generating a barcode image using Aspose.BarCode. -// Category-Description: The sample belongs to the Aspose.BarCode generation category, illustrating how to configure barcode size parameters via the BarcodeGenerator and its Parameters properties. It covers common tasks such as adjusting module width (XDimension) and image height for precise printing or display requirements. Developers often need these settings when integrating barcodes into labels, packaging, or UI components. +// Title: Generate Code128 barcode with custom X and Y dimensions +// Description: This example shows how to set the XDimension (module width) to 0.5 mm and the image height (Y dimension) to 30 mm before creating a barcode image using Aspose.BarCode. +// Category-Description: Aspose.BarCode barcode generation examples demonstrate how to configure barcode parameters such as size, format, and symbology. The key API classes include BarcodeGenerator, EncodeTypes, and the Parameters property hierarchy. Typical use cases involve creating printable barcodes for inventory, shipping, or point‑of‑sale systems where precise module dimensions are required. // Prompt: Set XDimension to 0.5 mm and YDimension to 30 mm before generating the barcode image. -// Tags: code128, xdimension, ydimension, imageheight, barcode generation, aspose.barcode, png +// Tags: code128, xdimension, ydimension, imageheight, barcode, generation, png, aspose.barcode using System; +using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Demonstrates generating a Code128 barcode with custom X and Y dimensions. +/// Demonstrates generating a Code128 barcode image with custom X and Y dimensions using Aspose.BarCode. /// class Program { /// - /// Entry point of the example. Configures barcode size parameters and saves the image. + /// Entry point of the example. Configures barcode parameters and saves the image. /// static void Main() { - // Create a barcode generator for Code128 with sample text - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Initialize a barcode generator for Code128 symbology with the sample text "12345" + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "12345")) { - // Set X-dimension (module width) to 0.5 millimeters + // Set the module width (XDimension) to 0.5 mm generator.Parameters.Barcode.XDimension.Millimeters = 0.5f; - // Set image height (Y dimension) to 30 millimeters + // Set the image height (Y dimension) to 30 mm generator.Parameters.ImageHeight.Millimeters = 30f; - // Save the generated barcode image as PNG + // Save the generated barcode as a PNG file generator.Save("barcode.png"); } + + // Inform the user that the barcode image has been created + Console.WriteLine("Barcode image generated: barcode.png"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/use-barcodebuilder-to-create-barcode-and-retrieve-raw-byte-array-for-network-transmission.cs b/one-dimensional-barcode-types/use-barcodebuilder-to-create-barcode-and-retrieve-raw-byte-array-for-network-transmission.cs index bce40f9..1764d99 100644 --- a/one-dimensional-barcode-types/use-barcodebuilder-to-create-barcode-and-retrieve-raw-byte-array-for-network-transmission.cs +++ b/one-dimensional-barcode-types/use-barcodebuilder-to-create-barcode-and-retrieve-raw-byte-array-for-network-transmission.cs @@ -1,52 +1,45 @@ // Title: Generate Code128 barcode and obtain raw PNG byte array -// Description: Demonstrates creating a Code128 barcode with Aspose.BarCode, converting it to a PNG image, and extracting the raw byte array for transmission. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator, Bitmap, and ImageFormat to produce barcode images. Typical use cases include creating barcodes for labels, receipts, or embedding in network messages where the image must be sent as a byte stream. Developers often need to retrieve the image bytes for APIs, web services, or storage without writing to disk. +// Description: Demonstrates creating a Code128 barcode with Aspose.BarCode, saving it to a memory stream in PNG format, and extracting the raw byte array for network transmission. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to use BarcodeGenerator and related parameter classes to customize barcode appearance, render the image to a stream, and retrieve binary data. Developers working with barcode creation for web services, APIs, or file storage commonly need to generate barcodes on‑the‑fly and send the resulting bytes over the network. The snippet showcases key classes such as BarcodeGenerator, EncodeTypes, BarCodeImageFormat, and the Parameters property for visual tweaks. // Prompt: Use BarCodeBuilder to create a barcode and retrieve the raw byte array for network transmission. -// Tags: barcode, code128, generation, png, bytearray, aspose.barcode, aspose.drawing +// Tags: barcode, code128, generation, png, bytearray, network, aspose.barcode, barcodegenerator using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Example program that generates a Code128 barcode, saves it to a memory stream as PNG, -/// and retrieves the raw byte array for further processing or network transmission. +/// Demonstrates barcode generation and raw byte extraction using Aspose.BarCode. /// class Program { /// - /// Entry point of the example. Creates the barcode, extracts its byte representation, - /// and writes the length of the resulting array to the console. + /// Entry point. Generates a Code128 barcode, saves it as PNG to a memory stream, + /// and obtains the byte array for further processing or transmission. /// static void Main() { - // Variable to hold the final barcode byte array - byte[] barcodeBytes; - - // Initialize the barcode generator with Code128 symbology - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128)) + // Initialize a barcode generator for Code128 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) { - // Set the data to be encoded in the barcode - generator.CodeText = "1234567890"; + // Optional: customize the barcode's foreground and background colors + generator.Parameters.Barcode.BarColor = Color.Black; + generator.Parameters.BackColor = Color.White; - // Generate the barcode image as a Bitmap object - using (Bitmap bitmap = generator.GenerateBarCodeImage()) + // Create a memory stream to hold the generated PNG image + using (MemoryStream ms = new MemoryStream()) { - // Create a memory stream to hold the image data - using (MemoryStream ms = new MemoryStream()) - { - // Save the bitmap to the memory stream in PNG format - bitmap.Save(ms, ImageFormat.Png); + // Save the barcode image into the memory stream in PNG format + generator.Save(ms, BarCodeImageFormat.Png); + + // Convert the stream contents to a raw byte array for transmission + byte[] barcodeBytes = ms.ToArray(); - // Convert the stream contents to a byte array - barcodeBytes = ms.ToArray(); - } + // Example usage: display the size of the generated byte array + Console.WriteLine($"Generated barcode byte array length: {barcodeBytes.Length}"); } } - - // Output the size of the generated byte array for verification - Console.WriteLine($"Generated barcode byte array length: {barcodeBytes.Length}"); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/use-databarparameters-to-disable-2d-component-for-specific-barcode-verify-output-format.cs b/one-dimensional-barcode-types/use-databarparameters-to-disable-2d-component-for-specific-barcode-verify-output-format.cs index 43acd21..4d26c9d 100644 --- a/one-dimensional-barcode-types/use-databarparameters-to-disable-2d-component-for-specific-barcode-verify-output-format.cs +++ b/one-dimensional-barcode-types/use-databarparameters-to-disable-2d-component-for-specific-barcode-verify-output-format.cs @@ -1,50 +1,73 @@ -// Title: Disable 2D Composite Component in DataBar OmniDirectional Barcode -// Description: Demonstrates how to generate a DataBar OmniDirectional barcode with the 2‑D composite component turned off and save it as a PNG image. -// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on configuring DataBarParameters for barcode customization. It showcases the use of BarcodeGenerator, EncodeTypes, and DataBar settings to control 2‑D components, a common requirement when generating compact linear barcodes for retail or logistics applications. Developers often need to toggle composite components and verify output formats such as PNG, JPEG, or SVG. +// Title: Disable 2D Composite Component in DataBar Limited Barcode and Verify PNG Output +// Description: Demonstrates how to generate a DataBar Limited barcode with the 2‑D composite component disabled, save it as a PNG file, and verify the image format. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on DataBar symbologies. It shows how to configure DataBarParameters, such as disabling the 2D composite component, and how to use BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to produce and validate barcode images. Developers working with retail or GS1 barcodes often need to customize DataBar settings and confirm output formats. // Prompt: Use DataBarParameters to disable 2D component for specific barcode, verify output format. -// Tags: databar, disable 2d component, png, aspose.barcode, generation, barcode +// Tags: databar, databarlimited, disable-2d-component, png, verification, aspose.barcode, barcode-generation using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Generates a DataBar OmniDirectional barcode with the 2‑D composite component disabled -/// and saves the result as a PNG file. +/// Demonstrates disabling the 2D composite component of a DataBar Limited barcode, +/// saving it as a PNG image, and verifying the file format. /// class Program { /// - /// Entry point of the example. Creates the barcode, configures parameters, - /// saves the image, and validates the output file. + /// Entry point of the example. Generates the barcode, saves it, and checks the PNG signature. /// static void Main() { - // Path where the generated barcode image will be saved + // Define the output file path for the generated barcode image. string outputPath = "databar.png"; - // Sample GTIN code for DataBar OmniDirectional (Application Identifier 01) - string codeText = "(01)12345678901231"; + // Remove any existing file to ensure a clean run. + if (File.Exists(outputPath)) + { + File.Delete(outputPath); + } - // Initialize the barcode generator with the desired symbology and data - using (var generator = new BarcodeGenerator(EncodeTypes.DatabarOmniDirectional, codeText)) + // Create a DataBar Limited barcode generator with a valid GTIN-like text. + // The format "(01)08888888888888" complies with GS1 requirements for DataBar Limited. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.DatabarLimited, "(01)08888888888888")) { - // Disable the optional 2‑D composite component of the DataBar barcode + // Access DataBar-specific parameters. + // Disable the 2D composite component (default is false; set explicitly for clarity). generator.Parameters.Barcode.DataBar.Is2DCompositeComponent = false; - // Persist the barcode as a PNG image + // Optionally adjust other visual parameters, such as the X-dimension. + generator.Parameters.Barcode.XDimension.Point = 2f; + + // Save the generated barcode as a PNG image. generator.Save(outputPath, BarCodeImageFormat.Png); } - // Verify that the file exists and has the expected PNG extension - if (File.Exists(outputPath) && Path.GetExtension(outputPath).Equals(".png", StringComparison.OrdinalIgnoreCase)) + // Verify that the file was created and that it has the expected PNG format. + if (File.Exists(outputPath)) { - Console.WriteLine($"Barcode image successfully saved as PNG: {outputPath}"); + // Read the first 8 bytes of the file to check the PNG signature. + byte[] header = new byte[8]; + using (FileStream fs = new FileStream(outputPath, FileMode.Open, FileAccess.Read)) + { + fs.Read(header, 0, header.Length); + } + + // PNG files start with the following byte sequence: 89 50 4E 47 0D 0A 1A 0A. + bool isPng = header.Length == 8 && + header[0] == 0x89 && header[1] == 0x50 && header[2] == 0x4E && + header[3] == 0x47 && header[4] == 0x0D && header[5] == 0x0A && + header[6] == 0x1A && header[7] == 0x0A; + + Console.WriteLine(isPng + ? $"Barcode saved successfully as PNG: {outputPath}" + : $"Barcode saved, but file format verification failed: {outputPath}"); } else { - Console.WriteLine("Failed to create the barcode image or incorrect format."); + Console.WriteLine("Failed to create the barcode image."); } } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/write-method-dynamically-adjusting-code-16k-aspect-ratio-based-on-input-string-length-for-consistent-visual-size.cs b/one-dimensional-barcode-types/write-method-dynamically-adjusting-code-16k-aspect-ratio-based-on-input-string-length-for-consistent-visual-size.cs index 5697ac3..7d2f9c2 100644 --- a/one-dimensional-barcode-types/write-method-dynamically-adjusting-code-16k-aspect-ratio-based-on-input-string-length-for-consistent-visual-size.cs +++ b/one-dimensional-barcode-types/write-method-dynamically-adjusting-code-16k-aspect-ratio-based-on-input-string-length-for-consistent-visual-size.cs @@ -1,70 +1,109 @@ -// Title: Dynamic Code 16K Aspect Ratio Based on Text Length -// Description: Demonstrates adjusting the Code 16K barcode's aspect ratio according to the length of the input string to maintain a consistent visual size. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on symbology-specific parameter tuning. It shows how to use BarcodeGenerator, EncodeTypes, and the Code16K parameters to modify aspect ratio and image dimensions. Developers creating barcodes that need uniform appearance regardless of data length can use this pattern to dynamically calculate visual properties. +// Title: Dynamic Aspect Ratio Adjustment for Code 16K Barcodes +// Description: Demonstrates how to calculate and apply a variable aspect ratio to Code 16K barcodes so that the visual size stays consistent across different input lengths. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and barcode parameter settings. It shows a common scenario where developers need to create Code 16K barcodes with a visual size that does not vary dramatically with the length of the encoded data, a frequent requirement in inventory and labeling systems. // Prompt: Write method dynamically adjusting Code 16K aspect ratio based on input string length for consistent visual size. -// Tags: barcode, code16k, aspectratio, dynamic, generation, image, aspose.barcode +// Tags: barcode, symbology, code16k, aspectratio, generation, png, aspose.barcode, csharp using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Demonstrates dynamic adjustment of Code 16K barcode aspect ratio based on input string length. +/// Generates Code 16K barcodes with a dynamically calculated aspect ratio to keep visual size consistent. /// class Program { /// - /// Calculates an aspect ratio based on the length of the codetext. - /// Longer text results in a higher height‑to‑width ratio to keep the visual size consistent. + /// Calculates an aspect ratio that tries to keep the visual size of the barcode + /// roughly constant regardless of the length of the encoded text. + /// Shorter texts get a larger aspect ratio (taller), longer texts get a smaller one (wider). /// /// The text to encode in the barcode. - /// A float representing the calculated aspect ratio. + /// A float representing the height‑to‑width ratio. static float CalculateAspectRatio(string codeText) { - const float baseAspect = 1.0f; // Default ratio for a typical length. - const int baseLength = 10; // Reference length for the default ratio. - - if (codeText == null) throw new ArgumentNullException(nameof(codeText)); - - // If the text length does not exceed the reference, return the base aspect. - if (codeText.Length <= baseLength) - return baseAspect; - - // Increase the ratio by 0.05 for each character beyond the base length. - // Adjust the multiplier as needed for different visual requirements. - float extraRatio = (codeText.Length - baseLength) * 0.05f; - return baseAspect + extraRatio; + const float baseAspect = 1.0f; // default height/width ratio + // Simple heuristic: inverse proportional to length, with a minimum divisor of 1. + float lengthFactor = Math.Max(1, codeText.Length); + float ratio = baseAspect * (10f / lengthFactor); // 10 is an arbitrary scaling constant + return ratio; } /// - /// Entry point that generates a Code 16K barcode with a calculated aspect ratio and saves it as an image. + /// Resolves a symbology name to the corresponding EncodeTypes field using reflection. /// - static void Main() + /// The name of the symbology (e.g., "Code16K"). + /// The matching instance. + static BaseEncodeType ResolveEncodeType(string symbologyName) { - // Sample codetext; replace with any string as needed. - string codeText = "DynamicAspectRatioExample"; + var field = typeof(EncodeTypes).GetField(symbologyName); + if (field == null) + { + throw new ArgumentException($"Unknown symbology: {symbologyName}"); + } + return (BaseEncodeType)field.GetValue(null); + } - // Determine the appropriate aspect ratio based on the input length. - float aspectRatio = CalculateAspectRatio(codeText); + /// + /// Generates a Code 16K barcode image with an aspect ratio adjusted for the supplied text. + /// + /// The text to encode. + /// Full file path where the PNG image will be saved. + static void GenerateCode16K(string codeText, string outputPath) + { + // Resolve the Code16K encode type. + BaseEncodeType encodeType = ResolveEncodeType("Code16K"); - // Create the barcode generator for Code16K using the provided codetext. - using (var generator = new BarcodeGenerator(EncodeTypes.Code16K, codeText)) + // Create the barcode generator with the specified text. + using (var generator = new BarcodeGenerator(encodeType, codeText)) { - // Apply the calculated aspect ratio to the Code16K parameters. - generator.Parameters.Barcode.Code16K.AspectRatio = aspectRatio; + // Adjust the aspect ratio based on the length of the code text. + float aspect = CalculateAspectRatio(codeText); + generator.Parameters.Barcode.Code16K.AspectRatio = aspect; + + // Optional: set a modest XDimension so the image is not too small. + generator.Parameters.Barcode.XDimension.Point = 2f; - // Optional: set a fixed image width to keep output size predictable. - generator.Parameters.ImageWidth.Point = 300f; + // Save the barcode as PNG. + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Generated '{outputPath}' with AspectRatio={aspect:F3}"); + } + } - // Use interpolation mode so the image size respects ImageWidth. - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; + /// + /// Entry point. Generates a set of Code 16K barcodes with varying text lengths to demonstrate aspect‑ratio adjustment. + /// + /// Command‑line arguments (not used). + static void Main(string[] args) + { + // Sample inputs of varying lengths. + string[] samples = new[] + { + "ABC", + "ABCDEFGHIJ", + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", + "12345678901234567890", + "LongerSampleTextToTestAspectRatioAdjustment" + }; - // Save the barcode image to a file. - string outputPath = "code16k.png"; - generator.Save(outputPath); + // Ensure the output directory exists. + string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } - // Inform the user about the saved file and the used aspect ratio. - Console.WriteLine($"Barcode saved to '{outputPath}' with aspect ratio {aspectRatio:F2}"); + // Generate a barcode for each sample. + for (int i = 0; i < samples.Length; i++) + { + string text = samples[i]; + string fileName = $"Code16K_{i + 1}.png"; + string outputPath = Path.Combine(outputDir, fileName); + GenerateCode16K(text, outputPath); } + + Console.WriteLine("Barcode generation completed."); } } \ No newline at end of file diff --git a/one-dimensional-barcode-types/write-unit-tests-validating-databar-stacked-aspect-ratio-calculations-for-values-eight-to-fifteen.cs b/one-dimensional-barcode-types/write-unit-tests-validating-databar-stacked-aspect-ratio-calculations-for-values-eight-to-fifteen.cs index cc16d44..91a06f9 100644 --- a/one-dimensional-barcode-types/write-unit-tests-validating-databar-stacked-aspect-ratio-calculations-for-values-eight-to-fifteen.cs +++ b/one-dimensional-barcode-types/write-unit-tests-validating-databar-stacked-aspect-ratio-calculations-for-values-eight-to-fifteen.cs @@ -1,67 +1,88 @@ -// Title: DataBar Stacked Aspect Ratio Validation -// Description: Demonstrates unit-test-like validation of DataBar stacked barcode aspect ratios for values 8‑15, ensuring the property is set correctly and barcode generation succeeds. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on DataBar stacked symbology. It showcases usage of BarcodeGenerator, EncodeTypes, and DataBar parameters to adjust aspect ratios, a common requirement when customizing barcode size for packaging or labeling applications. Developers often need to verify that aspect ratio settings are applied without errors. +// Title: Validate DataBar Stacked Aspect Ratio Calculations +// Description: Demonstrates how to generate GS1‑DataBar stacked barcodes with varying aspect ratios and verify that the rendered image matches the expected height‑to‑width ratio. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on DataBar stacked symbology. It shows usage of BarcodeGenerator, EncodeTypes, and DataBar parameters to control aspect ratio, a common requirement when integrating barcodes into print layouts or scanning systems. Developers often need to programmatically validate visual dimensions to meet specification tolerances. // Prompt: Write unit tests validating DataBar stacked aspect ratio calculations for values eight to fifteen. -// Tags: databar, stacked, aspectratio, png, barcodegenerator, aspose.barcode +// Tags: databar, stacked, aspectratio, barcode, generation, unit-test, aspnet, aspose.barcode using System; +using System.Collections.Generic; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; -/// -/// Example program that validates DataBar stacked aspect ratio settings (8‑15) by generating PNG images in memory. -/// -class Program +namespace DataBarStackedAspectRatioTests { /// - /// Entry point of the example. Iterates through aspect ratios, sets the property, and attempts barcode generation. + /// Executes a series of runtime checks that verify the rendered height‑to‑width ratio of + /// GS1‑DataBar stacked barcodes for aspect ratios 8 through 15. /// - static void Main() + class Program { - int failures = 0; + // Simple tolerance for floating‑point comparison (2 %). + const float Tolerance = 0.02f; - // Loop through the required aspect ratio values (8 to 15 inclusive) - for (int ratio = 8; ratio <= 15; ratio++) + /// + /// Entry point. Generates barcodes with different aspect ratios, measures the resulting image, + /// and reports any deviations beyond the allowed tolerance. + /// + static void Main() { - // Create a generator for DataBar stacked symbology with a valid GTIN payload - using (var generator = new BarcodeGenerator(EncodeTypes.DatabarStacked, "(01)12345678901231")) - { - // Apply the current aspect ratio to the DataBar parameters - generator.Parameters.Barcode.DataBar.AspectRatio = (float)ratio; + // Aspect ratios to validate (inclusive range 8‑15). + var ratiosToTest = new List { 8f, 9f, 10f, 11f, 12f, 13f, 14f, 15f }; + var failures = new List(); - // Verify that the aspect ratio property was set accurately - if (Math.Abs(generator.Parameters.Barcode.DataBar.AspectRatio - ratio) > 0.001f) - { - Console.WriteLine($"FAILED: Expected AspectRatio {ratio}, but got {generator.Parameters.Barcode.DataBar.AspectRatio}"); - failures++; - continue; - } + // Sample valid GS1‑DataBar stacked code text. + const string codeText = "(01)12345678901231"; - // Attempt to generate the barcode and save it to a memory stream (PNG format) + foreach (float expectedRatio in ratiosToTest) + { try { - using (var ms = new System.IO.MemoryStream()) + // Create a generator for the DataBar stacked symbology. + using (var generator = new BarcodeGenerator(EncodeTypes.DatabarStacked, codeText)) { - generator.Save(ms, BarCodeImageFormat.Png); + // Apply the test aspect ratio (height / width) to the stacked module. + generator.Parameters.Barcode.DataBar.AspectRatio = expectedRatio; + + // Render the barcode to an Aspose.Drawing.Bitmap. + using (Bitmap image = generator.GenerateBarCodeImage()) + { + // Guard against zero dimensions which would invalidate the ratio. + if (image.Width == 0 || image.Height == 0) + throw new InvalidOperationException("Generated image has zero width or height."); + + // Compute the actual height‑to‑width ratio of the rendered image. + float actualRatio = (float)image.Height / image.Width; + + // Verify the actual ratio is within the allowed tolerance. + if (Math.Abs(actualRatio - expectedRatio) > Tolerance) + { + failures.Add( + $"AspectRatio {expectedRatio}: expected ≈{expectedRatio:F2}, actual {actualRatio:F2}"); + } + } } - Console.WriteLine($"PASSED: AspectRatio {ratio}"); } catch (Exception ex) { - Console.WriteLine($"FAILED: Exception for AspectRatio {ratio}: {ex.Message}"); - failures++; + // Record any unexpected exceptions for later reporting. + failures.Add($"AspectRatio {expectedRatio}: exception – {ex.Message}"); } } - } - // Summarize test results - if (failures == 0) - { - Console.WriteLine("All tests passed."); - } - else - { - Console.WriteLine($"FAILED: {failures} test(s) failed."); + // Output the overall test result. + if (failures.Count == 0) + { + Console.WriteLine("PASSED: All DataBar stacked aspect ratio tests succeeded."); + } + else + { + Console.WriteLine($"FAILED: {failures.Count} test(s) failed."); + foreach (var msg in failures) + { + Console.WriteLine(msg); + } + } } } } \ No newline at end of file