I'm using C#, ASP.NET, iTextSharp for my application.
I have formatting issues when I print my datatable to PDF.
I have two datatables: dt and dt_child
foreach (DataRow dr in dt.Rows)
{
foreach (DataColumn dc in dt.Columns)
{
stringWrite.Write(dr[dc]);
}
indentno=dr["REF"].ToString();
dt_child = getDataTablebyProcedure("ChildProcedure",ref);
stringWrite = getStringWriterbyDataTable(dt_child, stringWrite);
}
Code is working fine. I have an issue with formatting.
The picture shows how it is currently displayed.
I want
1: The header row of dt to be displayed. It is currently not displayed.
2: The row of dt to be displayed in table form. Currently I'm iterating rows in each column.
You will need to set UI for PDF.
Try this if it helps
private void ExportDataToPDFTable()
{
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
try
{
string pdfFilePath = Server.MapPath(".") + "/pdf/myPdf.pdf";
//Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath, FileMode.Create));
doc.Open();//Open Document to write
Font font8 = FontFactory.GetFont("ARIAL", 7);
//Write some content
Paragraph paragraph = new Paragraph("Using ITextsharp I am going to show how to create simple table in PDF document ");
DataTable dt = GetDataTable();
if (dt != null)
{
//Craete instance of the pdf table and set the number of column in that table
PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
PdfPCell PdfPCell = null;
//Add Header of the pdf table
PdfPCell = new PdfPCell(new Phrase(new Chunk("ID", font8)));
PdfTable.AddCell(PdfPCell);
PdfPCell = new PdfPCell(new Phrase(new Chunk("Name", font8)));
PdfTable.AddCell(PdfPCell);
//How add the data from datatable to pdf table
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
PdfTable.AddCell(PdfPCell);
}
}
PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
doc.Add(paragraph);// add paragraph to the document
doc.Add(PdfTable); // add pdf table to the document
}
}
catch (DocumentException docEx)
{
//handle pdf document exception if any
}
catch (IOException ioEx)
{
// handle IO exception
}
catch (Exception ex)
{
// ahndle other exception if occurs
}
finally
{
//Close document and writer
doc.Close();
}
}
Courtesy
Add table into existing PDF using iTExtsharp
For reference
http://www.codeproject.com/Tips/573907/Generating-PDF-using-ItextSharp-with-Footer-in-Csh
Related
I have exported data from database to a datagridview and then to a pdf file and I want to delete one column in this file because it is a photo - I get only type of it in a cell (System.Byte[]).
I've tried to make my column invisible in datagridview but it didn't worked. It didn't have any impact on a pdf file, only column in datagridview had become hidden.
BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN,
BaseFont.CP1250, BaseFont.EMBEDDED);
PdfPTable pdfTable = new PdfPTable(dgv.Columns.Count);
pdfTable.DefaultCell.Padding = 3;
pdfTable.WidthPercentage = 100;
pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
pdfTable.DefaultCell.BorderWidth = 1;
iTextSharp.text.Font text = new iTextSharp.text.Font(bf,10,iTextSharp.text.Font.NORMAL);
//Add header
foreach(DataGridViewColumn column in dgv.Columns)
{
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, text));
cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
pdfTable.AddCell(cell);
}
//add datarow
foreach(DataGridViewRow row in dgv.Rows)
{
foreach(DataGridViewCell cell in row.Cells)
{
//dgv.Columns[7].Visible = false;
pdfTable.AddCell(new Phrase(cell.Value.ToString(), text));
}
}
var savefiledialoge = new SaveFileDialog();
savefiledialoge.FileName = filename;
savefiledialoge.DefaultExt = ".pdf";
if(savefiledialoge.ShowDialog()==DialogResult.OK)
{
using(FileStream stream = new FileStream(savefiledialoge.FileName,FileMode.Create))
{
Document pdfdoc = new Document(PageSize.A4,10f,10f,10f,0f);
PdfWriter.GetInstance(pdfdoc, stream);
pdfdoc.Open();
pdfdoc.Add(pdfTable);
pdfdoc.Close();
stream.Close();
}
}
That's because even if you're making it invisible you still getting it in the loop
so you just need to make a condition in your loop to check if the column is visible or not
like this :
foreach(DataGridViewColumn column in dgv.Columns)
{
if (!column.Visible) continue;
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, text));
cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
pdfTable.AddCell(cell);
}
//add datarow
foreach(DataGridViewRow row in dgv.Rows)
{
foreach(DataGridViewCell cell in row.Cells)
{
if (!dgv.Columns[cell.ColumnIndex].Visible) continue;
//dgv.Columns[7].Visible = false;
pdfTable.AddCell(new Phrase(cell.Value.ToString(), text));
}
}
and now you can make your column to visible and it won't appear in the pdf file
I have a PDfTable like below, my problem is if Phrase text too big than it makes blank line between header and phrase. How can I bound together so if phrase text too big for one page than fit what ever text you can on the same page with headers and rest of the phrase text you can start with new page.
problem:
.............................
. header1 : header2 :header3: Page1 // here I want to fit the phrase as much as can if phrase needs new page than put rest of the text on the next page
. :
. phrase too big to fit here:
............................:
.............................
. phrase starts here . Page2
. .
.............................
code:
private String WritePDF(DataTable dt)
{
String fileName = "";
//Creating iTextSharp Table from the DataTable data
PdfPTable pdfTable = new PdfPTable(m_PDFColumnCount);
pdfTable.DefaultCell.Padding = 1;
pdfTable.WidthPercentage = 100;
pdfTable.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
pdfTable.DefaultCell.BackgroundColor = new iTextSharp.text.BaseColor(194, 214, 155);
//pdfTable.DefaultCell.BorderWidth = 1;
this.BuildPDFHeader(pdfTable, "DATE");
this.BuildPDFHeader(pdfTable, "TIME");
this.BuildPDFHeader(pdfTable, "RESULT");
this.BuildPDFHeader(pdfTable, "FULLNAME");
this.BuildPDFHeader(pdfTable, "REGARDING");
//Adding DataRow
for (int intIndex = 0; intIndex < dt.Rows.Count; intIndex++)
{
dt.Rows[intIndex]["details"] = getplaintext(dt.Rows[intIndex]["details"].ToString());
pdfTable.AddCell(dt.Rows[intIndex]["date"].ToString());
pdfTable.AddCell(dt.Rows[intIndex]["time"].ToString());
pdfTable.AddCell(dt.Rows[intIndex]["result"].ToString());
pdfTable.AddCell(dt.Rows[intIndex]["fullname"].ToString());
pdfTable.AddCell(dt.Rows[intIndex]["regarding"].ToString());
PdfPCell cell = new PdfPCell(new Phrase(dt.Rows[intIndex]["details"].ToString()));
cell.BackgroundColor = new iTextSharp.text.BaseColor(227, 234, 235);
cell.Colspan = 5;
pdfTable.AddCell(cell);
}
//String folderPath = ConfigurationManager.AppSettings["Path"].ToString();
String folderPath = "C:\\PDFs\\";
fileName = String.Format("{0}{1}{2}",folderPath, dt.Rows[0]["id"].ToString(),".pdf" );
//Exporting to PDF
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate ))
{
Document pdfDoc = new Document(PageSize.A4, 20, 20, 20, 20);
PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
pdfDoc.Add(pdfTable);
pdfDoc.Close();
stream.Close();
}
return fileName;
}
private void BuildPDFHeader( PdfPTable pdfTable, String strText)
{
PdfPCell cell = new PdfPCell(new Phrase(strText));
cell.BackgroundColor = new iTextSharp.text.BaseColor(51, 102,102);
pdfTable.AddCell(cell);
}
Introduce the following line right after you define the table:
pdfTable.SplitLate = false;
This will split rows early. In you case, the rows are split only if a row takes up the space of an entire page.
Im writing a simple app that allows a user to export the created datagrid (here its dataGridView1) to a pdf file with a little help from itextsharp reference.
I've found a useful sample code on the internet but im having some problems in configuring it to export the data that the user enters during his work with the app. The user enters the data in textbox, saves it to the datagrid.
The result pdf file only contains the headers taken from the textbox and no cell content (data entered and saved by users using the textboxes).
Here is the code
//Creating iTextSharp Table from the DataTable data
PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount);
pdfTable.DefaultCell.Padding = 3;
pdfTable.WidthPercentage = 30;
pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
pdfTable.DefaultCell.BorderWidth = 1;
//Adding Header row
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
pdfTable.AddCell(cell);
}
//Exporting to PDF
string folderPath = "C:\\Users\\Marcus\\PDFs\\";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
using (FileStream stream = new FileStream(folderPath + "DataGridViewExport.pdf", FileMode.Create))
{
Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
pdfDoc.Add(pdfTable);
pdfDoc.Close();
stream.Close();
}
}
Okay so this is your header code (which you said works so lets leave that alone)
//Adding Header row
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
pdfTable.AddCell(cell);
}
//Lets add code that actually gets the cell contents down below it:
//add the cell contents
foreach(DataGridViewRow row in dataGridView1.Rows) {
foreach(DataGridViewCell cell in row.Cells) {
//we need to call .Value to get the value of the cell, but since a Phrase takes in
//a String, we need to convert the .Value to a String using .ToString()
PdfPCell pdfCell = new PdfPCell(new Phrase(cell.Value.ToString())); //this .Value property is that of a DataGridViewCell
pdfTable.AddCell(pdfCell);
}
}
DataGridViewCell should have a Value property. Use that to get your value of the cells.
I want to convert the data of datagridview into PDF file . For Example if i press button1 i should get the datagridview data as pdf.
How can I do this?
Please use iTextSharp for this.
There are different libraries to accomplish this
1.iTextSharp
2.PDFSharp
3.SharpPDF
Hope this helps
How to Export data as PDF format?
Below code is for export grid view data to PDF format
public void ExportToPdf(DataTable ExDataTable) //Datatable
{
//Here set page size as A4
Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);
try
{
PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
pdfDoc.Open();
//Set Font Properties for PDF File
Font fnt = FontFactory.GetFont("Times New Roman", 12);
DataTable dt = ExDataTable;
if (dt != null)
{
PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
PdfPCell PdfPCell = null;
//Here we create PDF file tables
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
if (rows == 0)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Columns[column].ColumnName.ToString(), fnt)));
PdfTable.AddCell(PdfPCell);
}
}
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), fnt)));
PdfTable.AddCell(PdfPCell);
}
}
// Finally Add pdf table to the document
pdfDoc.Add(PdfTable);
}
pdfDoc.Close();
Response.ContentType = "application/pdf";
//Set default file Name as current datetime
Response.AddHeader("content-disposition", "attachment; filename=" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
System.Web.HttpContext.Current.Response.Write(pdfDoc);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
I am generating PDF from my DataTable using iTextSharp version 5.3.5 in asp.net c#. My DataTable contain unkown rows, sp while PDF generating if it take more then one page i need to fix some header and footer for each page
Code:
public DataTable dataTable;
protected void Page_Load(object sender, EventArgs e)
{
dataTable = getData();
Document document = new Document(PageSize.A4, 10, 10, 90, 10);
string path = Server.MapPath("PDFs");
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path + "/Doc103.pdf", FileMode.Create));
document.Open();
CreatePages(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(column.ColumnName);
}
pdfTable.HeaderRows = 1;
pdfTable.DefaultCell.BorderWidth = 1;
foreach (DataRow row in dataTable.Rows)
{
foreach (object cell in row.ItemArray)
{
pdfTable.AddCell(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)));
}
Screenshoot of PDF:
Try the below links:
Creating PDFs with iTextSharp
Code sample for using iTextSharp PDF library, by Massoud Mazar
There are different ways to solve this.
One of them, is by using page events. You create a page event implementing the OnEndPage() method. If writer.PageNumber > 1, you add a header, for instance like this:
ColumnText.ShowTextAligned(writer.DirectContent,
Element.ALIGN_RIGHT, "Continued from previous page", 36, 820, 0);
See the examples from chapter 5 for more info about page events.
Another way to solve this, is by introducing a table header: table.HeaderRows = 1; so that the first row is repeated (make sure that row contains a cell that spans all columns saying "Continued from previous page"). To avoid that this header appears on the first page, use table.SkipFirstHeader = true;