将itextsharp条形码图像添加到PdfPCell

时间:2013-10-16 20:14:38

标签: itextsharp cell barcode

我正在尝试从文本字符串生成条形码,然后使用iTextSharp将结果PDF化。现在,我有以下代码:

// Create a Document object
var pdfToCreate = new Document(PageSize.A4, 0, 0, 0, 0);

// Create a new PdfWrite object, writing the output to a MemoryStream
var outputStream = new MemoryStream();
var pdfWriter = PdfWriter.GetInstance(pdfToCreate, outputStream);
PdfContentByte cb = new PdfContentByte(pdfWriter);
// Open the Document for writing
pdfToCreate.Open();

PdfPTable BarCodeTable = new PdfPTable(3);
// Create barcode
Barcode128 code128          = new Barcode128();
code128.CodeType            = Barcode.CODE128_UCC;
code128.Code                = "00100370006756555316";
// Generate barcode image
iTextSharp.text.Image image128 = code128.CreateImageWithBarcode(cb, null, null);
// Add image to table cell
BarCodeTable.AddCell(image128);
// Add table to document
pdfToCreate.Add(BarCodeTable);

pdfToCreate.Close();

当我运行此程序并尝试以编程方式打开PDF时,收到错误消息“文档没有页面。”

但是当我使用时:

 pdfToCreate.Add(image128);

(而不是添加到表格中,我将其添加到单元格中),条形码显示出来(尽管它从文档中浮出来)。

我想将条形码发送到表格,以便我可以更轻松地格式化文档。最终产品将从数据库中读取20-60个条形码。我知道哪里出错了?

1 个答案:

答案 0 :(得分:4)

您告诉PdfPTable构造函数创建一个三列表但只提供其中一列:

PdfPTable BarCodeTable = new PdfPTable(3);

iTextSharp默认忽略不完整的行。您可以更改构造函数以匹配列数,添加额外的单元格或调用BarCodeTable.CompleteRow(),这将使用默认单元格模板填充空白。

相关问题