2013-06-19 36 views
0

我想从我的ASP.NET Web窗体应用程序中使用iTextSharp生成PDF,该应用程序包含一个包含2列的表格和所需的行数以及图像和文本。但目前,我可以在一个单元格中添加图像或文本。以下是我想要的格式的HTML标记示例:生成包含图像和文本的PDF

<table align="center" style="border-spacing:20px;"> 
    <tr> 
     <td> 
      <label style="display:block;text-align:center;">Corvette</label> 
      <br /> 
      <img src="QrCodes/Ibrahim.jpg" /> 
     </td> 
     <td> 
      <label style="display:block;text-align:center;">Mercedes</label> 
      <br /> 
      <img src="QrCodes/Amazon.jpg" /> 
     </td> 
    </tr> 
</table> 

如何从我的代码背后创建此格式?它可以来自HTML字符串或使用iTextSharp对象。无论哪个工作。任何建议表示赞赏。

当前代码:

PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create)); 
doc.Open(); 
PdfPTable table = new PdfPTable(2); 
System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(@item.ItemQrCode)); 
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(image, ImageFormat.Jpeg); 
pdfImage.Alignment = iTextSharp.text.Image.UNDERLYING; 

Phrase phrase = new Phrase(item.ItemName); 
PdfPCell cellText = new PdfPCell(phrase); 
cellText.HorizontalAlignment = Element.ALIGN_CENTER; 
cellText.VerticalAlignment = Element.ALIGN_MIDDLE; 

PdfPCell cellImage = new PdfPCell(pdfImage); 
cellImage.HorizontalAlignment = Element.ALIGN_CENTER; 
cellImage.VerticalAlignment = Element.ALIGN_MIDDLE; 

table.AddCell(cellImage); 

doc.Add(table); 
doc.Close(); 

回答

0

由于有在主表2个栏,当我加入细胞中,这通过侧添加他们侧。但我的解决方案是为每个单元格提供1列的表格,然后将它们添加到主表格单元格以获取文本,然后在其下面显示图像。代码:

PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create)); 
doc.Open(); 
PdfPTable table = new PdfPTable(2); 

System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(@item.ItemQrCode)); 
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(image, ImageFormat.Jpeg); 

PdfPTable cellTable = new PdfPTable(1); //Table for each cell 

Phrase phrase = new Phrase(item.ItemName); 
PdfPCell cellText = new PdfPCell(phrase); 
cellText.HorizontalAlignment = Element.ALIGN_CENTER; 
cellText.VerticalAlignment = Element.ALIGN_MIDDLE; 

PdfPCell cellImage = new PdfPCell(pdfImage); 
cellImage.HorizontalAlignment = Element.ALIGN_CENTER; 
cellImage.VerticalAlignment = Element.ALIGN_MIDDLE; 

cellTable.AddCell(cellText); 
table.AddCell(cellImage); 

table.AddCell(cellTable); //Add each cells' table to main table cell 

doc.Add(table); 
doc.Close();