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());
}
}
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 want export data to Excel, for that I have use the code (linked below), code is working, data is being exported, but Excel is not downloading, please anyone can help me what is the problem?
Export data into Excel, Word and PDF with Formatting
This how I have use this code in my project
foreach (var enq_item in enquiries)
{
enquiry_list.Add(new enquiry_master
{
enquiry_source_id = enq_item.enquiry_source_id,
reference_no = enq_item.reference_no,
assigned_staff_no = enq_item.assigned_staff_no,
emp_id = enq_item.emp_id,
status_id = enq_item.status_id,
remarks = enq_item.remarks,
system_date_time = enq_item.system_date_time,
name = enq_item.name,
departing_from = enq_item.departing_from,
travelling_to = enq_item.travelling_to,
departing_date = enq_item.departing_date,
returning_date = enq_item.returning_date,
mobile_no = enq_item.mobile_no,
email = enq_item.email,
}
}
//Get the data from database into datatable
DataTable dt = ToDataTable(enquiry_list);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=DataTable.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
string filename = "DownloadTest.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//Apply text style to each Row
GridView1.Rows[i].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Write(hw.ToString());
Response.End();
Actually our requirement was need to export data to Excel or PDF then we realize best is PDF according to over requirements so I tried ItextSharp it's work out to me this my code
public string generatePDF()
{
string HTML = ""; ///Create a html as per our need
HTML += "<html>";
///Update the html here
HTML += "</html>";
string pdf_file_path = Request.PhysicalApplicationPath + "pdf\\quotations\\"; //getting physical application path for save the pdf
string final_name = "Here pdf name";
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdf_file_path + final_name, FileMode.Create));
wri.PageEvent = new ITextEvents();
doc.Open();
var content = wri.DirectContent;
content.MoveTo(28, doc.PageSize.Height - 150);
content.LineTo(28, doc.PageSize.Height - 200);
content.Stroke(); //generating line
content.MoveTo(573, doc.PageSize.Height - 150);
content.LineTo(573, doc.PageSize.Height - 200);
content.Stroke();
HTMLWorker htmlworker = new HTMLWorker(doc); //here we have to pass created instance of pdfWritter
htmlworker.SetStyleSheet(style);
htmlworker.Parse(new StringReader(HTML)); ///here pass the created HTML what we have need in the PDF
doc.NewPage();
doc.Close();
var json = JsonConvert.SerializeObject(final_name, Newtonsoft.Json.Formatting.Indented, common.JsonSerializeSettings());
return json; // retruning the file name
Response.Write(doc);
Response.End();
}
Above code is worked to me. Finally I'm returning the file name and showing the PDF in browser using the JavaScript
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'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