Skip to content

Barcode Appearing Black #181

@cammifsud

Description

@cammifsud

Hi 👋

When I try to print a PrintDocument with a Code128 barcode drawn, the barcode appears as just black. Could it be due to the way I've converted everything to actually get it somewhat functional? What's the correct way of doing this?

    public void PrintTestDocument()
    {
        // Create new Barcode
        Barcode barcode = new()
        {
            IncludeLabel = true,
            ForeColor = new(0F, 0F, 255F),
            BackColor = new(255F, 0F, 0F),
        };

        // Encode Barcode to SKImage
        SKImage skImage = barcode.Encode(BarcodeStandard.Type.Code128, "061200204001");

        // Start the Print Document
        PrintDocument pd = new PrintDocument();
        pd.PrinterSettings.PrinterName = "OneNote (Desktop)"; // Demo printing
        pd.PrintPage += (sender, e) => PrintPageHandler(e, skImage);

        // Print
        pd.Print();
    }

    private static void PrintPageHandler(PrintPageEventArgs e, SKImage skImage)
    {

        Bitmap bitmap = ToBitmap(skImage);

        // Calculate the position to center the image on the page
        int x = (e.PageBounds.Width - bitmap.Width) / 2;
        int y = (e.PageBounds.Height - bitmap.Height) / 2;

        // Draw the image on the print document
        e.Graphics.DrawImage(bitmap, new Point(x, y));
    }

    private static Bitmap ToBitmap(SKImage skImage)
    {
        // SKImage to SKPixmap
        SKPixmap skiaPixmap = skImage.PeekPixels();

        using MemoryStream stream = new MemoryStream();
        // Encode SKPixmap to bitmap
        skImage.Encode(SKEncodedImageFormat.Png, 100)
            .SaveTo(stream);

        // Create a Bitmap from the MemoryStream
        return new Bitmap(stream);
    }
}

When PrintTestDocument() is run, the below document is printed.

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions