我正在使用WinForms。在我的表格中,我得到了一个picuturebox和4个文本框margin_top,margin_bottom,margin_left和margin_right。我希望能够为打印预览对话框中显示的图像创建边距,但我还想在提供边距时按比例缩放图像。我还希望将图像包含在打印预览页面中,这意味着没有图像剪切。另一个问题是,当打印预览页面与我的图像大小相同时,为什么我的图像会被切割?我使用了850宽度乘1100高度的图像,当我点击打印预览图像时,它被切断,而我不必重新调整尺寸。
以下是您可以测试的图片的链接。
http://www.filedropper.com/850x1100
下面是在打印预览屏幕中无法正确显示的图像。它缺少右边界和右边界。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Printing_Image_Center
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.Image = new Bitmap(@"C:\Users\Bob\Pictures\850x1100.png");
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
var img_width = e.PageBounds.Width - e.MarginBounds.Left - Math.Abs(e.MarginBounds.Right - e.PageBounds.Width);
var img_height = e.PageBounds.Height - e.MarginBounds.Top - Math.Abs(e.MarginBounds.Bottom - e.PageBounds.Height);
e.Graphics.DrawImage(ResizeAcordingToImage(pictureBox1.Image, img_width, img_height),
e.MarginBounds.Left, e.MarginBounds.Top);
}
private void Btn_Print_Click(object sender, EventArgs e)
{
printPreviewDialog1.Document = printDocument1;
//PrintDocument.OriginAtMargins = true;
printDocument1.DefaultPageSettings.Margins.Top = Convert.ToInt32(txt_Top.Text);
printDocument1.DefaultPageSettings.Margins.Left = Convert.ToInt32(txt_Left.Text);
printDocument1.DefaultPageSettings.Margins.Right = Convert.ToInt32(txt_Right.Text);
printDocument1.DefaultPageSettings.Margins.Bottom = Convert.ToInt32(txt_bottom.Text);
printPreviewDialog1.ShowDialog();
}
private Image ResizeAcordingToImage(Image Source, int boxWidth, int boxHeight)
{
Image resizedImage;
double dbl = (double)Source.Width / (double)Source.Height;
//set height of image to boxHeight and check if resulting width is less than boxWidth,
//else set width of image to boxWidth and calculate new height
if ((int)((double)boxHeight * dbl) <= boxWidth)
{
resizedImage = new Bitmap(Source, (int)((double)boxHeight * dbl), boxHeight);
}
else
{
resizedImage = new Bitmap(Source, boxWidth, (int)((double)boxWidth / dbl));
}
return resizedImage;
}
}
}