c# - 使用 iTextSharp 自动缩放图像

标签 c# c#-4.0 itext

我正在使用 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 文件。

最佳答案

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

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

这是一种方法,请参阅内嵌注释:

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

唯一值得注意的一点是上面的 imagePaths 是一个 string[] 以便您可以测试当添加一个太大而不适合的图像集合时会发生什么在页面中。

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

关于c# - 使用 iTextSharp 自动缩放图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9272777/

相关文章:

C# ModInverse 函数

c#-4.0 - 根据非并行任务实现同步方法的模式(翻译/展开聚合异常)

java - 使用 Flying Saucer 将jsp转换为PDF

c# - 使用模数查找数字的目的?

c# - 如何在不知道何时完成的情况下显示进程的进展

c# - 在 C# 中对一个段落进行正则表达式

java - iText 7.0.2 目的地错误

c# - 无论我输入什么数字,我的文本框总是与 '0' 进行比较

c# - Registry.LocalMachine 和 RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default) 之间有什么区别

pdf - 使用 iText 时某些 pdf 文件水印不显示