将图像添加到单元格 - iTextSharp

Add image to cell - iTextSharp

我正在尝试将图像添加到 pdf 单元格,但出现错误:

Argument 1: cannot convert from 'System.Drawing.Image' to 'iTextSharp.text.pdf.PdfPCell'

行内:

content.AddCell(myImage);

这是我的代码:

PdfPTable content = new PdfPTable(new float[] { 500f });
content.AddCell(myImage);
document.Add(content);

myImage变量为Image类型。我做错了什么?

不能只添加图片,需要先创建单元格,然后将图片添加到单元格中: http://api.itextpdf.com/itext/com/itextpdf/text/pdf/PdfPCell.html#PdfPCell(com.itextpdf.text.Image)

PdfPCell cell = new PdfPCell(myImage);
content.AddCell(cell);

您也不能使用 System.Drawing.Image class,iTextSharp 有自己的 class 图像: http://api.itextpdf.com/itext/com/itextpdf/text/Image.html

它需要一个 URL 传递给图像位置的构造函数。

所以:

iTextSharp.text.Image myImage = iTextSharp.text.Image.GetInstance("Image location");
PdfPCell cell = new PdfPCell(myImage);
content.AddCell(cell);

您应该先创建一个单元格,然后将图像添加到该单元格,最后将单元格添加到 table。

var image = iTextSharp.text.Image.GetInstance(imagepath + "/logo.jpg");
var imageCell = new PdfPCell(image);
content.AddCell(imageCell);

查看关于此 post 的回答:How to add an image to a table cell in iTextSharp using webmatrix