barcodelib icon indicating copy to clipboard operation
barcodelib copied to clipboard

Barcode Appearing Black

Open cammifsud opened this issue 2 years ago • 1 comments

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

cammifsud avatar Nov 21 '23 00:11 cammifsud

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)

barnhill avatar Apr 28 '24 20:04 barnhill