Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,50 +1,51 @@
// Title: Calculate XDimension in Pixels for 2 mm Module Width at 300 dpi
// Description: Demonstrates how to compute the X‑dimension (module width) in pixels for a 2 mm barcode module at 300 dpi and apply it to a barcode generator.
// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to control barcode sizing by setting resolution and X‑dimension. It uses the BarcodeGenerator, EncodeTypes, and generation parameters classes, which are commonly employed when developers need precise physical dimensions for printed barcodes. Typical use cases include packaging, labeling, and compliance with industry standards that require exact module widths.
// Prompt: Calculate XDimension in Pixels for 2 mm module width at 300 dpi, then set it on generator.
// Tags: barcode, xdimension, resolution, dpi, code128, image, aspose.barcode, generation

using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;

/// <summary>
/// Demonstrates how to set the X‑dimension (module width) of a barcode
/// based on a desired physical size (millimetres) and DPI.
/// Example program that calculates the X‑dimension in pixels for a 2 mm module width at 300 dpi
/// and applies the value to a barcode generator.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the application.
/// Calculates the pixel value for a 2 mm module width at 300 dpi,
/// configures the barcode generator accordingly, and saves the image.
/// Entry point. Performs the calculation, configures the generator, and saves the barcode image.
/// </summary>
static void Main()
{
// Desired module (X‑dimension) width in millimetres.
const float moduleWidthMm = 2f;

// Target resolution in dots per inch.
const float dpi = 300f;

// Convert the module width from millimetres to inches.
// 1 inch = 25.4 mm.
float inches = moduleWidthMm / 25.4f;

// Calculate the X‑dimension in pixels using the DPI.
float xDimensionPixels = inches * dpi;

// Create a barcode generator for Code128.
// Desired module (X‑dimension) width: 2 mm.
// Convert millimetres to inches: 2 mm = 0.0787401575 inches.
// At 300 dpi, pixels = inches × DPI ≈ 23.622 pixels.
// Use the exact float value for maximum precision.
const float xDimensionPixels = 23.622f;
const float resolutionDpi = 300f;

// Create a barcode generator for Code128 (any symbology could be used here).
using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
{
// Set the data to encode.
generator.CodeText = "123456";
// Set the generator's resolution to match the DPI used in the calculation.
generator.Parameters.Resolution = resolutionDpi;

// Apply the calculated X‑dimension (pixel value).
// Apply the calculated X‑dimension in pixels.
generator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels;

// Ensure the generator's resolution matches the DPI used for the calculation.
generator.Parameters.Resolution = dpi;
// Example codetext to encode.
generator.CodeText = "1234567890";

// Save the generated barcode as a PNG file.
// Save the generated barcode as a PNG image.
generator.Save("barcode.png");
}

// Output the calculated pixel value for verification.
Console.WriteLine($"XDimension set to {xDimensionPixels:F2} pixels (2 mm at {dpi} dpi).");
// Inform the user that the barcode has been generated with the specified settings.
Console.WriteLine(
"Barcode generated with XDimension = {0} pixels at {1} DPI.",
xDimensionPixels,
resolutionDpi);
}
}
Original file line number Diff line number Diff line change
@@ -1,35 +1,34 @@
// Title: Generate Code128 Barcode with Millimeter Dimensions and Save as JPEG
// Description: Demonstrates configuring Aspose.BarCode's BarcodeGenerator to use millimeter units, set specific height and width, and export the barcode as a JPEG image.
// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to control image size using the Parameters.ImageHeight and ImageWidth properties with millimeter units. Developers commonly use these APIs to produce barcodes with precise physical dimensions for printing on labels, packaging, or documents. The key classes shown are BarcodeGenerator, EncodeTypes, and the Parameters sub‑objects, which are essential for customizing barcode appearance.
// Prompt: Configure BarcodeGenerator with Millimeters, set BarCodeHeight to 30, BarCodeWidth to 50, and save JPEG.
// Tags: code128, barcode generation, jpeg, millimeters, aspose.barcode, barcodegenerator, parameters

using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing.Imaging;

/// <summary>
/// Demonstrates generating a Code128 barcode using Aspose.BarCode and saving it as a JPEG image.
/// Example program that creates a Code128 barcode, sets its size in millimeters, and saves it as a JPEG file.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the application. Generates a barcode with specified dimensions and saves it to disk.
/// Entry point of the application.
/// </summary>
static void Main()
{
// Initialize a BarcodeGenerator with Code128 symbology and the desired text.
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
// Initialize a BarcodeGenerator for Code128 with the sample text "123456"
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
// Disable automatic sizing; we'll set dimensions manually.
generator.Parameters.AutoSizeMode = AutoSizeMode.None;

// Set the barcode's bar height to 30 millimeters.
generator.Parameters.Barcode.BarHeight.Millimeters = 30f; // BarCodeHeight = 30 mm
// Configure the barcode image height to 30 millimeters
generator.Parameters.ImageHeight.Millimeters = 30f;

// Set the overall image width to 50 millimeters.
generator.Parameters.ImageWidth.Millimeters = 50f; // BarCodeWidth = 50 mm
// Configure the barcode image width to 50 millimeters
generator.Parameters.ImageWidth.Millimeters = 50f;

// Save the generated barcode as a JPEG file named "barcode.jpg".
// Save the generated barcode as a JPEG image file named "barcode.jpg"
generator.Save("barcode.jpg");
}

// Inform the user that the barcode has been successfully generated.
Console.WriteLine("Barcode generated and saved as barcode.jpg");
}
}
Original file line number Diff line number Diff line change
@@ -1,41 +1,49 @@
// Title: Convert Pixels to Points and Generate Code128 Barcode Image
// Description: Demonstrates converting image dimensions from pixels to points using Aspose.BarCode's Unit class and generating a Code128 barcode with those dimensions.
// Category-Description: This example belongs to the Aspose.BarCode image sizing and barcode generation category. It showcases the use of the BarcodeGenerator class, AutoSizeMode, and Unit properties (ImageWidth, ImageHeight) to control output size. Developers often need to convert between measurement units (pixels, points, inches) when creating barcodes for print or screen, and this snippet illustrates the typical workflow for such scenarios.
// Prompt: Convert dimensions from Pixels to Points via Unit class, then generate Code128 image using converted values.
// Tags: barcode, code128, image sizing, unit conversion, points, pixels, aspnet, aspose.barcode, generation, png

using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;

/// <summary>
/// Demonstrates generating a Code128 barcode with specific image dimensions using Aspose.BarCode.
/// Example program that converts pixel dimensions to points and generates a Code128 barcode image.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the application. Generates a barcode image and saves it to disk.
/// Entry point of the application.
/// </summary>
static void Main()
{
// Define desired image dimensions in pixels.
float pixelWidth = 300f;
float pixelHeight = 150f;
// Desired dimensions in pixels
float widthPixels = 300f;
float heightPixels = 150f;

// Convert pixels to points (1 point = 1/72 inch, 1 pixel = 1/96 inch)
// points = pixels * (72 / 96) = pixels * 0.75
float widthPoints = widthPixels * 0.75f;
float heightPoints = heightPixels * 0.75f;

// Initialize a barcode generator for Code128 with the sample text.
// Create a Code128 barcode generator with sample text
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
// Set the image width and height using pixel units.
generator.Parameters.ImageWidth.Pixels = pixelWidth;
generator.Parameters.ImageHeight.Pixels = pixelHeight;
// Use interpolation mode so ImageWidth/ImageHeight control the size
generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;

// Convert the pixel dimensions to points (1 point = 1/72 inch) via the Unit class.
float widthInPoints = generator.Parameters.ImageWidth.Point;
float heightInPoints = generator.Parameters.ImageHeight.Point;
// Apply the converted dimensions (points) to the generator
generator.Parameters.ImageWidth.Point = widthPoints;
generator.Parameters.ImageHeight.Point = heightPoints;

// Apply the converted point values back to the generator (ensures proper scaling).
generator.Parameters.ImageWidth.Point = widthInPoints;
generator.Parameters.ImageHeight.Point = heightInPoints;
// Optional: set resolution (dpi) if needed
generator.Parameters.Resolution = 96f;

// Save the generated barcode as a PNG file.
// Save the barcode image as PNG
generator.Save("code128.png");
}

// Inform the user that the barcode has been created.
Console.WriteLine("Barcode generated and saved as code128.png");
}
}
Original file line number Diff line number Diff line change
@@ -1,123 +1,114 @@
// Title: Generate Code128 barcodes from CSV and save as PNG
// Description: Reads a CSV file containing barcode text and image dimensions, then creates PNG images using Aspose.BarCode.
// Category-Description: Demonstrates Aspose.BarCode generation with size control, covering BarcodeGenerator, EncodeTypes, and image format settings. Useful for developers needing batch barcode creation, custom dimensions, and file output in console utilities.
// Prompt: Create console utility reading CSV values, assigning size units, and outputting PNG files.
// Tags: barcode symbology, generation, png, csv, console, aspose.barcode, code128, size units

using System;
using System.IO;
using System.Collections.Generic;
using Aspose.BarCode;
using System.Globalization;
using System.IO;
using Aspose.BarCode.Generation;
using Aspose.Drawing;

/// <summary>
/// Generates barcode images from a CSV file or sample data using Aspose.BarCode.
/// Console utility that reads barcode data from a CSV file (or uses sample data) and generates PNG images with specified dimensions.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the application.
/// Reads barcode definitions, creates output directory, and generates PNG files.
/// Entry point. Accepts optional CSV file path argument, processes each line, and saves generated barcodes.
/// </summary>
/// <param name="args">Command‑line arguments; first argument may specify the CSV path.</param>
/// <param name="args">Command‑line arguments; first argument may be the CSV file path.</param>
static void Main(string[] args)
{
// Determine CSV file path: use first argument if provided, otherwise default.
string csvPath = args.Length > 0 ? args[0] : "barcodes.csv";
// Determine CSV file path (first argument or default)
string csvPath = args.Length > 0 ? args[0] : "input.csv";

// List to hold barcode data: text, width, and height.
List<(string CodeText, float Width, float Height)> items = new List<(string, float, float)>();
// Prepare data list: each item holds the code text and desired image size (width, height) in points
var items = new List<(string CodeText, float Width, float Height)>();

// Attempt to read barcode definitions from the CSV file.
if (File.Exists(csvPath))
{
using (var reader = new StreamReader(csvPath))
// Read CSV lines
foreach (var line in File.ReadAllLines(csvPath))
{
bool isFirstLine = true; // Tracks header row.
// Skip empty lines
if (string.IsNullOrWhiteSpace(line))
continue;

while (!reader.EndOfStream)
// Expected format: CodeText,Width,Height
var parts = line.Split(',');
if (parts.Length != 3)
{
string line = reader.ReadLine();

// Skip empty lines.
if (string.IsNullOrWhiteSpace(line))
continue;

// Skip header line if it contains column names.
if (isFirstLine && line.Contains("CodeText"))
{
isFirstLine = false;
continue;
}

// Split CSV line into parts.
string[] parts = line.Split(',');

// Ensure we have at least three columns (code, width, height).
if (parts.Length < 3)
continue; // insufficient data, skip

// Extract and trim code text.
string codeText = parts[0].Trim();
Console.WriteLine($"Invalid line (expected 3 columns): {line}");
continue;
}

// Parse width; fall back to default if parsing fails.
if (!float.TryParse(parts[1].Trim(), out float width))
width = 200f; // default width
// Parse barcode text
string code = parts[0].Trim();

// Parse height; fall back to default if parsing fails.
if (!float.TryParse(parts[2].Trim(), out float height))
height = 100f; // default height
// Parse width (points)
if (!float.TryParse(parts[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out float width))
{
Console.WriteLine($"Invalid width value: {parts[1]}");
continue;
}

// Add the parsed item to the collection.
items.Add((codeText, width, height));
// Parse height (points)
if (!float.TryParse(parts[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out float height))
{
Console.WriteLine($"Invalid height value: {parts[2]}");
continue;
}

// Add valid entry to the collection
items.Add((code, width, height));
}
}
else
{
// CSV not found – use hard‑coded sample data.
// Fallback sample data (5 items) when CSV is missing
items.Add(("Sample001", 200f, 100f));
items.Add(("Sample002", 250f, 120f));
items.Add(("Sample003", 180f, 90f));
items.Add(("Sample004", 220f, 110f));
items.Add(("Sample005", 240f, 130f));
Console.WriteLine($"CSV file not found at '{csvPath}'. Using sample data.");
items.Add(("Sample123", 250f, 120f));
items.Add(("Test456", 300f, 150f));
items.Add(("Demo789", 200f, 100f));
}

// Ensure the output directory exists.
string outputDir = "BarcodesOutput";
// Ensure output directory exists
string outputDir = "Barcodes";
if (!Directory.Exists(outputDir))
{
Directory.CreateDirectory(outputDir);
}

// Generate a barcode image for each item.
// Process each item and generate a PNG barcode
foreach (var item in items)
{
// Use Code128 as a generic symbology.
// Use Code128 as a generic 1D barcode type
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, item.CodeText))
{
// Set image dimensions in points.
// Set image size using point units
generator.Parameters.ImageWidth.Point = item.Width;
generator.Parameters.ImageHeight.Point = item.Height;

// Optional: set image resolution (DPI).
generator.Parameters.Resolution = 300f;
// Use interpolation mode to respect the explicit size
generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;

// Optional visual settings
generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
generator.Parameters.BackColor = Aspose.Drawing.Color.White;

// Build a safe file name for the output PNG.
string safeFileName = MakeSafeFileName(item.CodeText);
string outputPath = Path.Combine(outputDir, $"{safeFileName}.png");
// Build a safe output file name
string safeCode = string.Concat(item.CodeText.Split(Path.GetInvalidFileNameChars()));
string outputPath = Path.Combine(outputDir, $"{safeCode}.png");

// Save the barcode image.
generator.Save(outputPath);
// Save as PNG
generator.Save(outputPath, BarCodeImageFormat.Png);
Console.WriteLine($"Generated barcode for '{item.CodeText}' -> {outputPath}");
}
}
}

/// <summary>
/// Creates a file‑system‑safe file name by replacing invalid characters with underscores.
/// </summary>
/// <param name="name">Original file name.</param>
/// <returns>Sanitized file name.</returns>
static string MakeSafeFileName(string name)
{
foreach (char c in Path.GetInvalidFileNameChars())
{
name = name.Replace(c, '_');
}
return name;
// Program ends automatically
}
}
Loading
Loading