Search code examples
c#printingpanelbmp

C# Printing A4 size panel to a printer


I am trying to print a panel to A4 size paper. The panel will contain a report, invoice and etc so it should exactly print as it looks in the designer.

The properties of the panel are,

Properties

The contents of the panel,

contents

and here is the code I have working.

       private void PrintPanel()
    {
        System.Drawing.Printing.PrintDocument doc = new PrintDocument();
        doc.PrintPage += new PrintPageEventHandler(doc_PrintPage);
        doc.Print();
    }

    private void doc_PrintPage(object sender, PrintPageEventArgs e)
    {
        Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);

        float tgtWidthMM = 210;  //A4 paper size
        float tgtHeightMM = 297;  
        float tgtWidthInches = tgtWidthMM / 25.4f;
        float tgtHeightInches = tgtHeightMM / 25.4f;
        float srcWidthPx = bmp.Width; 
        float srcHeightPx = bmp.Height; 
        float dpiX = srcWidthPx / tgtWidthInches;
        float dpiY = srcHeightPx / tgtHeightInches;

        bmp.SetResolution(dpiX, dpiY);

        panel1.DrawToBitmap(bmp, panel1.ClientRectangle);

        e.Graphics.PageUnit = GraphicsUnit.Millimeter;
        e.Graphics.DrawImage(bmp, 0, 0, tgtWidthMM, tgtHeightMM);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        int pixelsWidth = 787;   
        int pixelsHeight = 1114;     //1 cm ~ 37.5      
        panel1.Size = new Size(pixelsWidth, pixelsHeight);

        PrintPanel();
    }

This works good and prints the content to a pdf (my default printer is set to Microsoft pdf printer). The problem is that the content does not fill the A4 sheet, it's just on the side as shown below: pdf

Edit:

Found my mistake as soon as I posted the question. I was setting the panel height and width when the button is clicked. The values are larger than the one set in the designers and the labels are not anchored. By just commenting out the line panel1.Size = new Size(pixelsWidth, pixelsHeight);. Things work better.

Though the label seems like a bit pixelated, is there a way to make it have clearer resolution?


Solution

  • You've got a lot going on with the size adjustments and it seems like your ratios are the culprit here.

    • The panel has width=420, height=594
    • The A4 should then be in the same aspect ratio (ex: width=840, height=1188)

    For your resolution issues, I would recommend that you work in a single unit (pixels) for simplicity, and use integers (as bitmaps don't work well with decimals -- i.e. no such thing as half a pixel)

    My advice if you're going to use a bitmap to print on A4, try and get an integer measure of the width/height of the A4 in pixels and work back from there.