I write code for the print a4 size panel with attach image. so, panel is print in A4 size but image is center the paper. here you can see my code. if anyone know what is the problem please tell me.
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);
}
