【问题标题】:Auto scaling of Images with iTextSharp使用 iTextSharp 自动缩放图像
【发布时间】:2012-03-05 13:52:51
【问题描述】:

我正在使用 iTextSharp API 从我的 C# 4.0 Windows 应用程序生成 PDF 文件。我将传递包含富文本和图像的 HTML 字符串。我的 PDF 文件大小为 A4,默认边距。注意到当我有一个大尺寸的图像时(例如 height="701px" width="935px"),图像不会变成 PDF。看起来,我必须缩小应该能够适合 PDF A4 大小的图像尺寸。我通过将图像粘贴到 A4 大小的 Word 文档来检查这一点,MS Word 会自动将图像缩小 36%,即 MS Word 仅占用原始图像尺寸的 64% 并设置绝对高度和宽度。

有人可以帮忙模仿 C# 中的类似行为吗?

让我知道如何自动设置图像高度和宽度以适应 A4 PDF 文件。

【问题讨论】:

    标签: c# c#-4.0 itext


    【解决方案1】:

    没错,iTextSharp 不会自动调整对于文档来说太大的图像。所以这只是一个问题:

    • 使用左/右和上/下页边距计算可用的文档宽度和高度。
    • 获取图像的宽度和高度。
    • 比较文档的宽度和高度与图像的宽度和高度。
    • 根据需要缩放图像。

    这是一种方法,请参见内联 cmets:

    // 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);
      }
    }
    

    唯一值得注意的一点是,上面的imagePathsstring[],这样您就可以测试在添加大到无法放入页面的图像集合时会发生什么。

    另一种方法是将图像放在一个列中,单个单元格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);
    

    【讨论】:

    • 感谢完美的解决方案 :)
    猜你喜欢
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 2013-02-19
    • 1970-01-01
    • 2013-07-03
    • 2017-06-29
    相关资源
    最近更新 更多