title: c# - itextsharp image scaletofit
body: <p>im having a problem with scaling image to fit properly </p>
  
  <p>this is my problem. the red border of the image must not overlap the blue border of the pdf page</p>
  
  <p>the size of the image below i used is 173*292</p>
  
  <p><a href="https://i.stack.imgur.com/4uz7Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4uz7Q.png" alt="enter image description here"></a></p>
  
  <p>and here is my code</p>
  
  <pre><code>using (MemoryStream ms = new MemoryStream())
              {
                  Document doc = new Document(PageSize.A4, 10, 10, 20, 35);
                  PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(System.IO.Path.Combine(filepath, pdfLocation), FileMode.Create));
                  doc.AddTitle("Document Title");
  
                  doc.Open();
  
                  iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(strFilename);
                  image1.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
  
                  image1.Border = iTextSharp.text.Rectangle.BOX;
                  image1.BorderWidth = 3.0f;
                  image1.BorderColor = iTextSharp.text.BaseColor.RED;
  
                  PdfContentByte content = writer.DirectContent;
                  iTextSharp.text.Rectangle rectangle = new iTextSharp.text.Rectangle(doc.PageSize);
                  rectangle.Left += doc.LeftMargin;
                  rectangle.Right -= doc.RightMargin;
                  rectangle.Top -= doc.TopMargin;
                  rectangle.Bottom += doc.BottomMargin;
                  content.SetColorStroke(iTextSharp.text.BaseColor.BLUE);
                  content.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height);
                  content.Stroke();
  
                  float pageWidth = doc.PageSize.Width - (35 + 35);
                  float pageHeight = doc.PageSize.Height - (35 + 35);
                  image1.ScaleToFit(pageWidth, pageHeight);
  
                  image1.SetAbsolutePosition((PageSize.A4.Width - image1.ScaledWidth) / 2, (PageSize.A4.Height - image1.ScaledHeight) / 2);
                  doc.Add(image1);
                  doc.Close();
  
              }
  </code></pre>
  
  <p>i thought my code works properly. </p>
  
  <p>the screenshot below is i used an image with the size of 3000*2363 and the image border doesn't overlap the border of the pdf size</p>
  
  <p><a href="https://i.stack.imgur.com/9143i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9143i.png" alt="enter image description here"></a></p>