在iTextSharp中向单元格添加图片

4

我正在尝试将一个图片添加到PDF单元格中,但是出现了错误:

参数 1:无法将类型为 'System.Drawing.Image' 的对象转换为类型 'iTextSharp.text.pdf.PdfPCell'

在以下代码行中出现问题:

content.AddCell(myImage);

这是我的代码:

这是我的代码:

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

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


1
不知道 API 的情况下,你可能需要创建一个单元格并将图片放在那里,然后使用 content.AddCell(yourCreatedCell); - janhartmann
2个回答

7

您不能仅添加图像,需要先创建单元格并将图像添加到单元格中: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类,iTextSharp有自己的Image类: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);

现在我遇到了一个错误:参数1:无法将“System.Drawing.Image”转换为“iTextSharp.text.Phrase”。 - mskuratowski
抱歉,详见上文,您需要使用iTextSharp自己的图像函数,可以在此处找到: http://api.itextpdf.com/itext/com/itextpdf/text/Image.html - Draken

2

首先需要创建一个单元格,然后将图片添加到该单元格中,最后将该单元格添加到表格中。

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

请查看此帖子的答案:如何使用WebMatrix在iTextSharp中将图像添加到表格单元格


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接