Adding an image to a PDF using iTextSharp and scale it properly

后端 未结 5 1496
忘掉有多难
忘掉有多难 2020-12-01 10:27

here\'s my code. It correctly adds the pictures I want and everything works except that the images are using their native resolution, so if the image is big

相关标签:
5条回答
  • 2020-12-01 10:59

    I solved it using the following:

    foreach (var image in images)
    {
        iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);
    
        if (pic.Height > pic.Width)
        {
            //Maximum height is 800 pixels.
            float percentage = 0.0f;
            percentage = 700 / pic.Height;
            pic.ScalePercent(percentage * 100);
        }
        else
        {
            //Maximum width is 600 pixels.
            float percentage = 0.0f;
            percentage = 540 / pic.Width;
            pic.ScalePercent(percentage * 100);
        }
    
        pic.Border = iTextSharp.text.Rectangle.BOX;
        pic.BorderColor = iTextSharp.text.BaseColor.BLACK;
        pic.BorderWidth = 3f;
        document.Add(pic);
        document.NewPage();
    }
    
    0 讨论(0)
  • 2020-12-01 11:02
    image.SetAbsolutePosition(1,1);
    
    0 讨论(0)
  • 2020-12-01 11:03

    Personally, I use something close from fubo's solution and it works well:

    image.ScaleToFit(document.PageSize);
    image.SetAbsolutePosition(0,0);
    
    0 讨论(0)
  • 2020-12-01 11:07

    You can try something like this:

          Image logo = Image.GetInstance("pathToTheImage")
          logo.ScaleAbsolute(500, 300)
    
    0 讨论(0)
  • 2020-12-01 11:13
    image.ScaleToFit(500f,30f);
    

    this method keeps the aspect ratio of the image

    0 讨论(0)
提交回复
热议问题