如何打印A4尺寸页面?A4面板打印图片居中异常问题求助
问题:打印A4面板时图片未适配A4尺寸,仅居中显示
我编写了用于打印带图片的A4尺寸面板的代码,目前面板可按A4尺寸打印,但图片仅在纸张居中显示,未适配A4面板。

以下是我的代码:
private void btn_print_Click(object sender, EventArgs e) { PrintDocument pd = new PrintDocument(); pd.PrintPage += new PrintPageEventHandler(PrintPage); PrintDialog printDialog = new PrintDialog(); printDialog.Document = pd; if (printDialog.ShowDialog() == DialogResult.OK) { pd.Print(); } } private void PrintPage(object sender, PrintPageEventArgs e) { Graphics g = e.Graphics; Rectangle marginBounds = e.MarginBounds; // Calculate the aspect ratio of the image float aspectRatio = (float) panel1.BackgroundImage.Width / panel1.BackgroundImage.Height; // Calculate the target width and height for A4 size int targetWidth = marginBounds.Width; int targetHeight = (int)(targetWidth / aspectRatio); // Check if the height exceeds the printable area height if (targetHeight > marginBounds.Height) { targetHeight = marginBounds.Height; targetWidth = (int)(targetHeight * aspectRatio); } // Calculate the position to center the image int x = marginBounds.Left + (marginBounds.Width - targetWidth) / 2; int y = marginBounds.Top + (marginBounds.Height - targetHeight) / 2; // Draw the image on the print page graphics g.DrawImage(panel1.BackgroundImage, x, y, targetWidth, targetHeight); }
问题排查与修复
你的代码逻辑是保持图片原比例居中显示,因此会出现图片无法铺满A4面板的情况。若要让图片完全适配A4可打印区域,可根据需求选择以下两种修改方式:
方式1:拉伸图片铺满整个可打印区域(忽略原比例)
直接使用可打印区域的宽高绘制图片,无需计算比例:
private void PrintPage(object sender, PrintPageEventArgs e) { Graphics g = e.Graphics; Rectangle marginBounds = e.MarginBounds; // 直接用可打印区域尺寸绘制图片 g.DrawImage(panel1.BackgroundImage, marginBounds); }
方式2:按比例铺满(裁剪超出部分)
若要保持图片比例并铺满A4区域,需计算覆盖整个区域的尺寸,再裁剪超出部分:
private void PrintPage(object sender, PrintPageEventArgs e) { Graphics g = e.Graphics; Rectangle marginBounds = e.MarginBounds; Image img = panel1.BackgroundImage; float imgRatio = (float)img.Width / img.Height; float areaRatio = (float)marginBounds.Width / marginBounds.Height; int drawWidth, drawHeight; int x = marginBounds.Left, y = marginBounds.Top; if (imgRatio > areaRatio) { // 图片更宽,按高度铺满,裁剪左右 drawHeight = marginBounds.Height; drawWidth = (int)(drawHeight * imgRatio); x -= (drawWidth - marginBounds.Width) / 2; } else { // 图片更高,按宽度铺满,裁剪上下 drawWidth = marginBounds.Width; drawHeight = (int)(drawWidth / imgRatio); y -= (drawHeight - marginBounds.Height) / 2; } // 绘制图片,超出可打印区域的部分会被自动裁剪 g.DrawImage(img, x, y, drawWidth, drawHeight); }
额外注意点
- 若需要去掉打印边距,可将
MarginBounds替换为e.PageBounds(对应整个纸张区域)。 - 可通过
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;设置图形插值模式,提升拉伸后图片的清晰度。
内容的提问来源于stack exchange,提问作者Gihan Sanjeewa
相关产品推荐
相关产品推荐

