Printing a panel to a printer

ⅰ亾dé卋堺 提交于 2020-01-17 04:51:19

问题


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);


来源:https://stackoverflow.com/questions/34116241/printing-a-panel-to-a-printer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!