Printing a panel to a printer

2019-09-11 00:53发布

问题:

I am trying to print a panel (with its contents) to a printer. I saw different posts on the net, but I am not able to print the panel and get the correct size. The panel is getting printed very large and not as expected.

For example, I want to print a panel and get as output size 80mm X 40mm:

    private void Print_Click(object sender, EventArgs e)
    {
        int pixelsWidth = 300;   // 300 pixels= ~8cm 
        int pixelsHeight = 150;  // 150 pixels= ~4cm            
        panelLabel.Size = new Size(pixelsWidth,pixelsHeight);  

        PrintPanel();
    }

    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(panelLabel.Width, panelLabel.Height);
        panelLabel.DrawToBitmap(bmp, new Rectangle(0, 0, panelLabel.Width, panelLabel.Height));
        RectangleF bounds = e.PageSettings.PrintableArea;

        e.Graphics.PageUnit = GraphicsUnit.Millimeter;
        e.Graphics.DrawImage(bmp, bounds.Left, bounds.Top, bounds.Width, bounds.Height);
    }

回答1:

You have set up things almost right.

The only thing missing is setting the resolution for the Bitmap.

If you don't do that is gets copied from the screen, which will usually not work well with the printer. Often resulting in way too small output, but as you have already set the Graphics to use millimeters we need to adapt the bitmap to understand what the pixels are supposed to translate to.

Assuming quadratic pixels try this :

int pixelsWidth = 300;   // 300 pixels= ~8cm 
int pixelsHeight = 150;  // 150 pixels= ~4cm  
Bitmap bmp = new Bitmap(pixelsWidth, pixelsHeight);
//..    

float targetWidthInInches = 80f / 25.4f;
float dpi = 1f * pixelsWidth / targetWidthInInches;

bmp.SetResolution(dpi, dpi);