C# - Display An Image In PrintPreviewDialog

This code snippet shows how to resize and display an image in a PrintPreviewDialog.
  1. private void Form1_Load(object sender, EventArgs e)
  2. {
  3.  
  4.         PrintDocument document = new PrintDocument();
  5.         document.PrintPage += new PrintPageEventHandler(document_PrintPage);
  6.  
  7.         PrintPreviewDialog ppDialog = new PrintPreviewDialog();
  8.         ppDialog.Document = document;
  9.         ppDialog.Show();
  10. }
  11.  
  12. void document_PrintPage(object sender, PrintPageEventArgs e)
  13. {
  14.         PrintDocument document = (PrintDocument)sender;
  15.         Graphics g = e.Graphics;
  16.  
  17.         Image image = Image.FromFile("path to image");
  18.  
  19.         int imgWidth = image.Width;
  20.         int imgHeight = image.Height;
  21.  
  22.         int pageWidth  = document.DefaultPageSettings.PaperSize.Width;
  23.         int pageHeight  = document.DefaultPageSettings.PaperSize.Height;
  24.  
  25.         if (imgWidth > pageWidth)
  26.         {
  27.                 int diff = imgWidth - pageWidth;
  28.                 imgWidth = pageWidth;
  29.                 imgHeight -= diff;
  30.         }
  31.  
  32.         Rectangle rect = new Rectangle(0,0,imgWidth,imgHeight);
  33.  
  34.         g.DrawImage(image, rect );
  35. }

No comments:

Post a Comment