使用iTextSharp自动缩放图像

RSP*_*RSP 2 c# itext c#-4.0

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

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

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

kuu*_*nbo 7

这是正确的,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);
  }
}
Run Code Online (Sandbox Code Playgroud)

唯一值得注意的是,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);
Run Code Online (Sandbox Code Playgroud)