barnhill / barcodelib

C# Barcode Image Generation Library
Apache License 2.0
731 stars 239 forks source link

Barcode Appearing Black #181

Open cammifsud opened 9 months ago

cammifsud commented 9 months ago

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

barnhill commented 4 months ago

have you tried specifying the foreground and background colors in the encode method?

b.Encode(BarcodeStandard.Type.Code128, "061200204001", new(0F, 0F, 255F), new(255F, 0F, 0F), w, h)