Auto scaling of Images with iTextSharp

后端 未结 1 1807
说谎
说谎 2021-01-07 05:44

I’m generating PDF files from my C# 4.0 windows application using iTextSharp API. I’ll be passing HTML string which will contain Rich Text and Images. My PDF file size is A4

相关标签:
1条回答
  • 2021-01-07 06:18

    That's correct, iTextSharp won't automatically size images that are too big for the document. So it's just a matter of:

    • Calculating available document width and height with left/right and top/bottom page margins.
    • Getting the image width and height.
    • Comparing the document's width and height with the image's width and height.
    • Scaling the image if needed.

    Here's one way, see inline comments:

    // change this to any page size you want    
    Rectangle defaultPageSize = PageSize.A4;   
    using (Document document = new Document(defaultPageSize)) {
      PdfWriter.GetInstance(document, STREAM);
      document.Open();
    // if you don't account for the left/right margins, the image will
    // run off the current page
      float width = defaultPageSize.Width
        - document.RightMargin
        - document.LeftMargin
      ;
      float height = defaultPageSize.Height
        - document.TopMargin
        - document.BottomMargin
      ;
      foreach (string path in imagePaths) {
        Image image = Image.GetInstance(path);
        float h = image.ScaledHeight;
        float w = image.ScaledWidth;
        float scalePercent;
    // scale percentage is dependent on whether the image is 
    // 'portrait' or 'landscape'        
        if (h > w) {
    // only scale image if it's height is __greater__ than
    // the document's height, accounting for margins
          if (h > height) {
            scalePercent = height / h;
            image.ScaleAbsolute(w * scalePercent, h * scalePercent);
          }
        }
        else {
    // same for image width        
          if (w > width) {
            scalePercent = width / w;
            image.ScaleAbsolute(w * scalePercent, h * scalePercent);
          }
        }
        document.Add(image);
      }
    }
    

    The only point worth noting is that imagePaths above is a string[] so that you can test what happens when adding a collection of images that are to big to fit in a page.

    Another way is to put the image in a one column, single cell PdfPTable:

    PdfPTable table = new PdfPTable(1);
    table.WidthPercentage = 100;
    foreach (string path in imagePaths) {
      Image image = Image.GetInstance(path);
      PdfPCell cell = new PdfPCell(image, true);
      cell.Border = Rectangle.NO_BORDER;
      table.AddCell(cell);
    }
    document.Add(table);
    
    0 讨论(0)
提交回复
热议问题