Odd Numbered Cell Not Added To Pdf - asp.net

I am trying to add PdfPCell inside a loop to a iTextSharp Table with 2 columns in a Document. But if the count inside the loop is an odd number. Then the last cell does not get added. Can someone please provide a solution to this problem?
My code is below:
var doc = new Document();
PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("~/QrCodes/") + fileName + ".pdf", FileMode.Create));
doc.Open();
PdfPTable table = new PdfPTable(2);
table.WidthPercentage = 100;
foreach (var item in items)
{
if (itemImages.Any(p => p.Reference == item.Reference) == true)
{
System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(#item.ItemQrCode));
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(image, ImageFormat.Jpeg);
PdfPCell cellImage = new PdfPCell(pdfImage);
cellImage.HorizontalAlignment = Element.ALIGN_CENTER;
cellImage.VerticalAlignment = Element.ALIGN_MIDDLE;
cellImage.Border = 0;
table.AddCell(cellImage);
}
}
doc.Add(table);
doc.Close();

On your PdfPTable you can call the CompleteRow() method when you're done and missing cells will be filled in.

Related

Downloading in pdf format

This is how I'm downloading the gridview in Excel. Pls help with the pdf download code:
string strFileName = "Salary_Statement" + DateTime.Now.ToString("ddMMyyyy");
GridView1.AllowPaging = false;
GridView1.HeaderRow.Cells[2].Visible = true;
GridView1.HeaderRow.Cells[3].Visible = true;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
}
GridView1.HeaderRow.Style.Add("background-color", "#e5e1e1");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
row.Attributes.Add("class", "textmode");
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=" + strFileName + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
GridView1.AllowPaging = true;//AB
Try this. Following code shows how to download
http://www.codeproject.com/Questions/317301/Code-of-Downloading-PDF-file-in-asp-net
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.pdf;
protected void ExportToPDF(GridView gvReport, bool LandScape)
{
int noOfColumns = 0, noOfRows = 0;
DataTable tbl = null;
if (gvReport.AutoGenerateColumns)
{
tbl = gvReport.DataSource as DataTable; // Gets the DataSource of the GridView Control.
noOfColumns = tbl.Columns.Count;
noOfRows = tbl.Rows.Count;
}
else
{
noOfColumns = gvReport.Columns.Count;
noOfRows = gvReport.Rows.Count;
}
float HeaderTextSize = 8;
float ReportNameSize = 10;
float ReportTextSize = 8;
float ApplicationNameSize = 7;
// Creates a PDF document
Document document = null;
if (LandScape == true)
{
// Sets the document to A4 size and rotates it so that the orientation of the page is Landscape.
document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
}
else
{
document = new Document(PageSize.A4, 0, 0, 15, 5);
}
// Creates a PdfPTable with column count of the table equal to no of columns of the gridview or gridview datasource.
iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);
// Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.
mainTable.HeaderRows = 4;
// Creates a PdfPTable with 2 columns to hold the header in the exported PDF.
iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);
// Creates a phrase to hold the application name at the left hand side of the header.
Phrase phApplicationName = new Phrase("Sample Application", FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));
// Creates a PdfPCell which accepts a phrase as a parameter.
PdfPCell clApplicationName = new PdfPCell(phApplicationName);
// Sets the border of the cell to zero.
clApplicationName.Border = PdfPCell.NO_BORDER;
// Sets the Horizontal Alignment of the PdfPCell to left.
clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;
// Creates a phrase to show the current date at the right hand side of the header.
Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));
// Creates a PdfPCell which accepts the date phrase as a parameter.
PdfPCell clDate = new PdfPCell(phDate);
// Sets the Horizontal Alignment of the PdfPCell to right.
clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
// Sets the border of the cell to zero.
clDate.Border = PdfPCell.NO_BORDER;
// Adds the cell which holds the application name to the headerTable.
headerTable.AddCell(clApplicationName);
// Adds the cell which holds the date to the headerTable.
headerTable.AddCell(clDate);
// Sets the border of the headerTable to zero.
headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;
// Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
PdfPCell cellHeader = new PdfPCell(headerTable);
cellHeader.Border = PdfPCell.NO_BORDER;
// Sets the column span of the header cell to noOfColumns.
cellHeader.Colspan = noOfColumns;
// Adds the above header cell to the table.
mainTable.AddCell(cellHeader);
// Creates a phrase which holds the file name.
Phrase phHeader = new Phrase("Sample Export", FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
PdfPCell clHeader = new PdfPCell(phHeader);
clHeader.Colspan = noOfColumns;
clHeader.Border = PdfPCell.NO_BORDER;
clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
mainTable.AddCell(clHeader);
// Creates a phrase for a new line.
Phrase phSpace = new Phrase("\n");
PdfPCell clSpace = new PdfPCell(phSpace);
clSpace.Border = PdfPCell.NO_BORDER;
clSpace.Colspan = noOfColumns;
mainTable.AddCell(clSpace);
// Sets the gridview column names as table headers.
for (int i = 0; i < noOfColumns; i++)
{
Phrase ph = null;
if (gvReport.AutoGenerateColumns)
{
ph = new Phrase(tbl.Columns[i].ColumnName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
}
else
{
ph = new Phrase(gvReport.Columns[i].HeaderText, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
}
mainTable.AddCell(ph);
}
// Reads the gridview rows and adds them to the mainTable
for (int rowNo = 0; rowNo < noOfRows; rowNo++)
{
for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
{
if (gvReport.AutoGenerateColumns)
{
string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
else
{
if (gvReport.Columns[columnNo] is TemplateField)
{
DataBoundLiteralControl lc = gvReport.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;
string s = lc.Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
else
{
string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
}
}
// Tells the mainTable to complete the row even if any cell is left incomplete.
mainTable.CompleteRow();
}
// Gets the instance of the document created and writes it to the output stream of the Response object.
PdfWriter.GetInstance(document, Response.OutputStream);
// Creates a footer for the PDF document.
HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true);
pdfFooter.Alignment = Element.ALIGN_CENTER;
pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER;
// Sets the document footer to pdfFooter.
document.Footer = pdfFooter;
// Opens the document.
document.Open();
// Adds the mainTable to the document.
document.Add(mainTable);
// Closes the document.
document.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
Response.End();
}

how to place a table in pdf with a itext

public static void writeChartToPDF(int width, int height, String fileName) {
PdfWriter writer = null;
Document document = new Document();
try {
writer = PdfWriter.getInstance(document, new FileOutputStream(
fileName));
document.open();
JFreeChart c= generateBarChart0();
PdfContentByte cb = writer.getDirectContent();
float wid = PageSize.A4.getWidth();
float heigh = PageSize.A4.getHeight() / 2;
PdfTemplate bar = cb.createTemplate(width, height);
Graphics2D g2d1 = new PdfGraphics2D(bar,width, height, new DefaultFontMapper());
Rectangle2D r2d1 = new Rectangle2D.Double(0, 0, width, height);
System.out.println("check 5");
c.draw(g2d1, r2d1);
g2d1.dispose();
cb.addTemplate(bar, 0, heigh);
PdfPTable table = new PdfPTable(3); // 3 columns.
PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
document.add(table);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
document.close();
}
what am i missing here..? i want it to appear as table in the 1st followed by a bar chart. i have a nearly 5 charts and 5 table and i want it to appear in a new page. so each page has a table and a chart.
You're a developer, which means that you should be able to understand the answers that are given. For instance: when you asked jfreechart & itext for adding many number of barcharts, I answered that you can wrap a PdfTemplate inside an image:
Image img = Image.getInstance(bar);
document.add(img);
I'm not really happy that you didn't accept that answer, because it was a really good answer. I'm even less happy that you didn't follow that advice.
In a comment to your current question, I asked you to make a choice: either add the chart and the table at absolute positions, or use iText to do the layout. By wrapping the template inside an Image, adding that image with document.add() and then adding the table, you could solve your problem.
A solution that may even be more elegant would be to wrap the
for (PdfTemplate chart : charts) {
PdfPTable table = new PdfPTable(3); // 3 columns.
table.setWidthPercentage(100);
PdfPCell cell = new PdfPCell(Image.getInstance(chart), true);
cell.setColspan(3);
table.addCell(cell);
PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
document.add(table);
document.newPage();
}
In this example charts could be a list of PdfTemplate instances.

How to print a grid view using iTextSharp

How to print a GridView data (all of it) using iTextSharp in asp.net? I need only a hint not the full code
Try with this:
protected void ExportToPDF(GridView gvReport, bool LandScape)
{
int noOfColumns = 0, noOfRows = 0;
DataTable tbl = null;
if (gvReport.AutoGenerateColumns)
{
tbl = gvReport.DataSource as DataTable; // Gets the DataSource of the GridView Control.
noOfColumns = tbl.Columns.Count;
noOfRows = tbl.Rows.Count;
}
else
{
noOfColumns = gvReport.Columns.Count;
noOfRows = gvReport.Rows.Count;
}
float HeaderTextSize = 8;
float ReportNameSize = 10;
float ReportTextSize = 8;
float ApplicationNameSize = 7;
// Creates a PDF document
Document document = null;
if (LandScape == true)
{
// Sets the document to A4 size and rotates it so that the orientation of the page is Landscape.
document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
}
else
{
document = new Document(PageSize.A4, 0, 0, 15, 5);
}
// Creates a PdfPTable with column count of the table equal to no of columns of the gridview or gridview datasource.
iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);
// Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.
mainTable.HeaderRows = 4;
// Creates a PdfPTable with 2 columns to hold the header in the exported PDF.
iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);
// Creates a phrase to hold the application name at the left hand side of the header.
Phrase phApplicationName = new Phrase("Sample Application", FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));
// Creates a PdfPCell which accepts a phrase as a parameter.
PdfPCell clApplicationName = new PdfPCell(phApplicationName);
// Sets the border of the cell to zero.
clApplicationName.Border = PdfPCell.NO_BORDER;
// Sets the Horizontal Alignment of the PdfPCell to left.
clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;
// Creates a phrase to show the current date at the right hand side of the header.
Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));
// Creates a PdfPCell which accepts the date phrase as a parameter.
PdfPCell clDate = new PdfPCell(phDate);
// Sets the Horizontal Alignment of the PdfPCell to right.
clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
// Sets the border of the cell to zero.
clDate.Border = PdfPCell.NO_BORDER;
// Adds the cell which holds the application name to the headerTable.
headerTable.AddCell(clApplicationName);
// Adds the cell which holds the date to the headerTable.
headerTable.AddCell(clDate);
// Sets the border of the headerTable to zero.
headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;
// Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
PdfPCell cellHeader = new PdfPCell(headerTable);
cellHeader.Border = PdfPCell.NO_BORDER;
// Sets the column span of the header cell to noOfColumns.
cellHeader.Colspan = noOfColumns;
// Adds the above header cell to the table.
mainTable.AddCell(cellHeader);
// Creates a phrase which holds the file name.
Phrase phHeader = new Phrase("Sample Export", FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
PdfPCell clHeader = new PdfPCell(phHeader);
clHeader.Colspan = noOfColumns;
clHeader.Border = PdfPCell.NO_BORDER;
clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
mainTable.AddCell(clHeader);
// Creates a phrase for a new line.
Phrase phSpace = new Phrase("\n");
PdfPCell clSpace = new PdfPCell(phSpace);
clSpace.Border = PdfPCell.NO_BORDER;
clSpace.Colspan = noOfColumns;
mainTable.AddCell(clSpace);
// Sets the gridview column names as table headers.
for (int i = 0; i < noOfColumns; i++)
{
Phrase ph = null;
if (gvReport.AutoGenerateColumns)
{
ph = new Phrase(tbl.Columns[i].ColumnName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
}
else
{
ph = new Phrase(gvReport.Columns[i].HeaderText, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
}
mainTable.AddCell(ph);
}
// Reads the gridview rows and adds them to the mainTable
for (int rowNo = 0; rowNo < noOfRows; rowNo++)
{
for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
{
if (gvReport.AutoGenerateColumns)
{
string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
else
{
if (gvReport.Columns[columnNo] is TemplateField)
{
DataBoundLiteralControl lc = gvReport.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;
string s = lc.Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
else
{
string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
}
}
// Tells the mainTable to complete the row even if any cell is left incomplete.
mainTable.CompleteRow();
}
// Gets the instance of the document created and writes it to the output stream of the Response object.
PdfWriter.GetInstance(document, Response.OutputStream);
// Creates a footer for the PDF document.
HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true);
pdfFooter.Alignment = Element.ALIGN_CENTER;
pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER;
// Sets the document footer to pdfFooter.
document.Footer = pdfFooter;
// Opens the document.
document.Open();
// Adds the mainTable to the document.
document.Add(mainTable);
// Closes the document.
document.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
Response.End();
}
Took from here
Here's what I'm using today. Ripped from http://blog.codovations.com/2011/01/generating-pdf-from-datatable-using.html
using System;
using System.Web;
using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace yetanothercoder
{
/// <summary>
/// Summary description for CreatePdf
/// </summary>
public class PDFExporter
{
private readonly DataTable dataTable;
private readonly string fileName;
private readonly bool timeStamp;
public PDFExporter(DataTable dataTable, string fileName, bool timeStamp)
{
this.dataTable = dataTable;
this.fileName = timeStamp ? String.Format("{0}-{1}", fileName, GetTimeStamp(DateTime.Now)) : fileName;
this.timeStamp = timeStamp;
}
public void ExportPDF()
{
HttpResponse Response = HttpContext.Current.Response;
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".pdf");
// step 1: creation of a document-object
Document document = new Document(PageSize.A4, 10, 10, 90, 10);
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
//set some header stuff
document.AddTitle(fileName);
document.AddSubject(String.Format("Table of {0}", fileName));
document.AddCreator("www.yetanothercoder.com");
document.AddAuthor("naveenj");
// step 3: we open the document
document.Open();
// step 4: we add content to the document
CreatePages(document);
// step 5: we close the document
document.Close();
}
private void CreatePages(Document document)
{
document.NewPage();
document.Add(FormatPageHeaderPhrase(dataTable.TableName));
PdfPTable pdfTable = new PdfPTable(dataTable.Columns.Count);
pdfTable.DefaultCell.Padding = 3;
pdfTable.WidthPercentage = 100; // percentage
pdfTable.DefaultCell.BorderWidth = 2;
pdfTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
foreach (DataColumn column in dataTable.Columns)
{
pdfTable.AddCell(FormatHeaderPhrase(column.ColumnName));
}
pdfTable.HeaderRows = 1; // this is the end of the table header
pdfTable.DefaultCell.BorderWidth = 1;
foreach (DataRow row in dataTable.Rows)
{
foreach (object cell in row.ItemArray)
{
//assume toString produces valid output
pdfTable.AddCell(FormatPhrase(cell.ToString()));
}
}
document.Add(pdfTable);
}
private static Phrase FormatPageHeaderPhrase(string value)
{
return new Phrase(value, FontFactory.GetFont(FontFactory.TIMES, 10, Font.BOLD, new BaseColor(255, 0, 0)));
}
private static Phrase FormatHeaderPhrase(string value)
{
return new Phrase(value, FontFactory.GetFont(FontFactory.TIMES, 8, Font.UNDERLINE, new BaseColor(0, 0, 255)));
}
private Phrase FormatPhrase(string value)
{
return new Phrase(value, FontFactory.GetFont(FontFactory.TIMES, 8));
}
private string GetTimeStamp(DateTime value)
{
return value.ToString("yyyyMMddHHmmssffff");
}
}
}

iTextSharp appending table to document in memory stream after PDFStamper has been used

Hi I am trying to add a table to a pdf after I have used the stamper.
// CREATE MEMORY STRING
MemoryStream ms = new MemoryStream();
string formFile = Server.MapPath("testImg.pdf");
PdfReader reader = new PdfReader(formFile);
PdfStamper outStamper = new PdfStamper(reader, ms);
AcroFields fields = outStamper.AcroFields;
// UPDATE THE FORM FIELDS
fields.SetField("Text1", "John Smith");
fields.SetField("Text2", "1234567890");
fields.SetField("Text3", "1234567890");
//ADD LOGO
iTextSharp.text.Image headerlogo = iTextSharp.text.Image.GetInstance(Server.MapPath("logo.jpg"));
headerlogo.ScaleToFit(140, 399);
headerlogo.Alignment = iTextSharp.text.Image.UNDERLYING;
headerlogo.SetAbsolutePosition(200, 500);
int pageCount = reader.NumberOfPages;
PdfContentByte body = outStamper.GetOverContent(pageCount);
body.AddImage(headerlogo);
outStamper.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=test");
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
I want to be able to append the document with a table.
PdfPTable table = new PdfPTable(3);
PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns"));
cell.Colspan = 3;
cell.BorderWidth = 5;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
table.AddCell(cell);
table.AddCell("Col 1 Row 1");
table.AddCell("Col 2 Row 1");
table.AddCell("Col 3 Row 1");
table.AddCell("Col 1 Row 2");
table.AddCell("Col 2 Row 2");
table.AddCell("Col 3 Row 2");
document.Add(table);
I am having trouble with defining the document to add the table to. Please can someone advise how I would add the table to the PDF in the Memory Stream.
Any help would be greatly appreciated.
Alex
Not sure how you have the two pieces working together but here is how I've done it for my application.
Basically i keep the stamping separate from adding structured content and then merging the results into one big pdf. You could try and do all of it together in one big step using table.WriteSelectedRows (which takes a PdfContentByte as one of its arguments) but the time that i have to spend with manual layouts, tends to outweigh the benefit of having it all done in one step (besides the fact that it becomes one huge method which is hard to maintain / reuse)
For clarification & testing purpose, I've used FileStream but of course, the same works fine with MemoryStream and reuse streams should you end up creating one monolithic function in your development code.
Here is my test application that I used to confirm the code and run your scenario:
Steps:
Create Test2.pdf (stamped contents
of original source) from Test.pdf
(our original source)
Create Test3.pdf (containing all our content to be appended at the end)
Open Test2.pdf & Test3.pdf and merge them into Test4.pdf final stream
Note: I haven't used image stamping code and you may have to adjust using on Document in first section if PdfStamper closes the underlying Document as well (can't recall if it does from top of my head but it will throw a helpful exception in case you need to adjust the using statement)
private static void Main(string[] args)
{
using (FileStream ms = new FileStream("C:\\Test2.pdf", FileMode.Create))
using (FileStream formFile = new FileStream("C:\\Test.pdf", FileMode.Open))
{
PdfReader reader = new PdfReader(formFile);
using (Document document = new Document(reader.GetPageSizeWithRotation(1)))
{
//PdfStamper outStamper = new PdfStamper(reader, ms);
//PdfContentByte body = outStamper.GetOverContent(reader.NumberOfPages);
//document.Open(); //Open document to work with
//AcroFields fields = outStamper.AcroFields;
//// UPDATE THE FORM FIELDS
//fields.SetField("Text1", "John Smith");
//fields.SetField("Text2", "1234567890");
//fields.SetField("Text3", "1234567890");
////ADD LOGO
//iTextSharp.text.Image headerlogo = iTextSharp.text.Image.GetInstance(Server.MapPath("logo.jpg"));
//headerlogo.ScaleToFit(140, 399);
//headerlogo.Alignment = iTextSharp.text.Image.UNDERLYING;
//headerlogo.SetAbsolutePosition(200, 500);
//body.AddImage(headerlogo);
//outStamper.Close();
}
}
using (FileStream ms = new FileStream("C:\\Test3.pdf", FileMode.Create))
using (FileStream formFile = new FileStream("C:\\Test2.pdf", FileMode.Open))
{
PdfReader reader = new PdfReader(formFile);
using (Document document = new Document(reader.GetPageSizeWithRotation(1)))
{
PdfWriter pdfWriter = PdfWriter.GetInstance(document, ms);
document.Open();
PdfPTable table = new PdfPTable(3);
PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns")) { Colspan = 3, BorderWidth = 5, HorizontalAlignment = 1 };
table.AddCell(cell);
table.AddCell("Col 1 Row 1");
table.AddCell("Col 2 Row 1");
table.AddCell("Col 3 Row 1");
table.AddCell("Col 1 Row 2");
table.AddCell("Col 2 Row 2");
table.AddCell("Col 3 Row 2");
table.CompleteRow(); //Added - table won't add the final row if its cells are incomplete - safe to have it ending a table
document.Add(table);
}
}
using (FileStream ms = new FileStream("C:\\Test4.pdf", FileMode.Create))
using (FileStream stampedfile = new FileStream("C:\\Test2.pdf", FileMode.Open))
using (FileStream appendfile = new FileStream("C:\\Test3.pdf", FileMode.Open))
{
PdfReader stampedContentReader = new PdfReader(stampedfile);
PdfReader appendContentReader = new PdfReader(appendfile);
using (Document document = new Document(stampedContentReader.GetPageSizeWithRotation(1)))
{
PdfCopy pdfCopy = new PdfCopy(document, ms);
document.Open();
for (int i = 1; i <= stampedContentReader.NumberOfPages; i++)
pdfCopy.AddPage(pdfCopy.GetImportedPage(stampedContentReader, i));
for (int i = 1; i <= appendContentReader.NumberOfPages; i++)
pdfCopy.AddPage(pdfCopy.GetImportedPage(appendContentReader, i));
}
}
}
Hope this helps.

ASP.NET Dynamically creating HTMLTableColumns (headers)

is it possible to dynamically create html table columns (< th>< /th>) using namespae System.Web.UI.HtmlControls ?
try this:
HtmlTable table1 = new HtmlTable();
// Set the table's formatting-related properties.
table1.Border = 1;
table1.CellPadding = 3;
table1.CellSpacing = 3;
table1.BorderColor = "red";
// Start adding content to the table.
HtmlTableRow row;
HtmlTableCell cell;
for (int i=1; i<=5; i++)
{
// Create a new row and set its background color.
row = new HtmlTableRow();
row.BgColor = (i%2==0 ? "lightyellow" : "lightcyan");
for (int j=1; j<=4; j++)
{
// Create a cell and set its text.
cell = new HtmlTableCell();
cell.InnerHtml = "Row: " + i.ToString()+ "<br />Cell: " + j.ToString();
// Add the cell to the current row.
row.Cells.Add(cell);
}
// Add the row to the table.
table1.Rows.Add(row);
}
// Add the table to the page.
this.Controls.Add(table1);
Yes in that name space you will want to look at:
HtmlTable
HtmlTableRow
HtmlTableCell
Use is like so:
HtmlTable htmlTable = new HtmlTable(); //creating table object
HtmlTableRow htmlRow = new HtmlTableRow(); //creating row object
HtmlTableCell htmlTableCell = new HtmlTableCell(); //create cell
htmlTableCell.InnerHtml = "<b>Test Text Bolded</b>";//setting cell content
HtmlTableCell textTableCell = new HtmlTableCell(); //create cell
textTableCell.InnerText = "Test plain text"; //setting cell content
htmlRow.Cells.Add(htmlTableCell); //add cell to row
htmlRow.Cells.Add(textTableCell); //add cell to row
htmlTable.Rows.Add(htmlRow); // add row to table
HtmlTableCell = new HtmlTableCell("th");

Resources