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");
}
}
}
Related
I have a web application developed in ASP.NET. I am using rdlc to do the reporting. Everything seems to work fine on my development machine, but not when I upload the application to the hosting service (GoDaddy.com). The reports show up as preview (ReportViewer Control). But when I click on Print it is not showing the preview.
public void print()
{
try
{
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string extension;
byte[] bytes = ReportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);
FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("output.pdf"), FileMode.Create);
fs.Write(bytes, 0, bytes.Length);
fs.Close();
//Open exsisting pdf
Document document = new Document(PageSize.A4);
PdfReader reader = new PdfReader(HttpContext.Current.Server.MapPath("output.pdf"));
//Getting a instance of new pdf wrtiter
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(HttpContext.Current.Server.MapPath("Print.pdf"), FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
int i = 0;
int p = 0;
int n = reader.NumberOfPages;
Rectangle psize = reader.GetPageSize(1);
float width = psize.Width;
float height = psize.Height;
//Add Page to new document
while (i < n)
{
document.NewPage();
p++;
i++;
PdfImportedPage page1 = writer.GetImportedPage(reader, i);
cb.AddTemplate(page1, 0, 0);
}
//Attach javascript to the document
PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);
writer.AddJavaScript(jAction);
document.Close();
//Attach pdf to the iframe
frmPrint.Attributes["src"] = "Print.pdf";
}
catch (Exception ex)
{
Response.Write("<script>alert('Error Occured')</script>");
}
}
I am using the above code for print..
I have dynamic forms that are build from xml. I can generate the form but I can't get new values from it. I get only the old values that were generated. I would like to update values that are diffrent from old. I think the problem is that I override the new values on page_init with old ones?
This is a dropbox link to my UI for better understanding what I want to achive : https://www.dropbox.com/s/nacs9ohgjxefft9/FormView.png?dl=0#
public sealed class FormViewEditTemplate : IBindableTemplate
{
public FormViewEditTemplate(ListItemType type, mmXMLdoc.mmXMLdoc editXmlForm)
{
templateType = type;
_editXmlForm = editXmlForm;
}
//This method provides a way to insert an instance of text and controls into the specified container.
void ITemplate.InstantiateIn(Control container)
{
tabela = new Table();
tabs = new TabContainer();
tapPanel = new TabPanel();
row = new TableRow();
switch (templateType)
{
case ListItemType.EditItem:
List<XmlElement> Controls = _editXmlForm.getNodCollection("//Tabs");
if (Controls.Count > 0)
{
//pridobimo tabe za formo
foreach (XmlElement ctrlItem in Controls)
{
var ControlsItems = _editXmlForm.getNodCollection("./Controls", "Control", -1, ctrlItem);
tabela = new Table();
tapPanel = new TabPanel();
tapPanel.ID = Guid.NewGuid().ToString();
tapPanel.HeaderText = ctrlItem.GetAttribute("name").ToString();
//pridobimo podatke za formo
//var controls1 = ctrlItem.SelectNodes("//Controls");
foreach (XmlElement ctrl in ControlsItems)
{
string name = _editXmlForm.gStr("./#name", -1, ctrl) + Guid.NewGuid().ToString();
string label = _editXmlForm.gStr("./#label", -1, ctrl);
string width = _editXmlForm.gStr("./#width", -1, ctrl);
string type = _editXmlForm.gStr("./#type", -1, ctrl);
string value = String.Empty;
string helpnote = _editXmlForm.gStr("./HelpNote", -1, ctrl);
string boundfield = _editXmlForm.gStr("./BoundField", -1, ctrl);
row = new TableRow();
TableCell cell = new TableCell();
switch (type)
{
case "TextBox":
//The TemplateField allows for a mix of HTML markup, Web controls, and data-binding syntax.
Label lbl_item = new Label();
lbl_item.Font.Bold = true;
lbl_item.Text = label + ": ";
cell = new TableCell();
cell.Controls.Add(lbl_item);
row.Controls.Add(cell);
TextBox txt_item = new TextBox();
txt_item.ID = boundfield;
txt_item.Text = boundfield;
txt_item.DataBinding += new EventHandler(txt_DataBind);
cell = new TableCell();
cell.Controls.Add(txt_item);
row.Controls.Add(cell);
break;
case "CheckBox":
lbl_item = new Label();
lbl_item.Font.Bold = true;
lbl_item.Text = label + "<br/>";
//The BoundField displays the value of specified DataSource field as text.
BoundField bfield = new BoundField();
bfield.HeaderText = label;
bfield.DataField = boundfield;
break;
default:
break;
}
tabela.Controls.Add(row);
}
tapPanel.Controls.Add(tabela);
tabs.Controls.Add(tapPanel);
}
}
break;
case ListItemType.Footer:
Button saveButton = new Button();
saveButton.Command += new CommandEventHandler(SaveButton_Command);
saveButton.CommandName = "Update";
saveButton.Text = "Save";
saveButton.ID = "EditButton";
container.Controls.Add(saveButton);
break;
}
container.Controls.Add(tabs);
}
IOrderedDictionary IBindableTemplate.ExtractValues(Control container)
{
OrderedDictionary dict = new OrderedDictionary();
List<XmlElement> Controls = _editXmlForm.getNodCollection("//Tabs");
if (Controls.Count > 0)
{
//pridobimo tabe za formo
foreach (XmlElement ctrlItem in Controls)
{
var ControlsItems = _editXmlForm.getNodCollection("./Controls", "Control", -1, ctrlItem);
foreach (XmlElement ctrl in ControlsItems)
{
string type = _editXmlForm.gStr("./#type", -1, ctrl);
string boundfield = _editXmlForm.gStr("./BoundField", -1, ctrl);
switch (type)
{
case "TextBox":
TextBox tb = (TextBox)FindControlRecursive(container, boundfield);
if (tb != null)
dict[boundfield] = tb.Text;
break;
case "Label":
Label lb = (Label)FindControlRecursive(container, boundfield);
if (lb != null)
dict[boundfield] = lb.Text;
break;
case "CheckBox":
CheckBox cb = (CheckBox)FindControlRecursive(container, boundfield);
if (cb != null)
dict[boundfield] = cb.Checked;
break;
case "DropDown":
DropDownList ddl = (DropDownList)FindControlRecursive(container, boundfield);
if (ddl != null)
dict[boundfield] = ddl.SelectedValue;
break;
default:
break;
}
}
}
}
return dict;
}
private Control FindControlRecursive(Control ctlRoot, string sControlId)
{
// if this control is the one we are looking for, break from the recursion
// and return the control.
if (ctlRoot.ID == sControlId)
{
return ctlRoot;
}
// loop the child controls of this parent control and call recursively.
foreach (Control ctl in ctlRoot.Controls)
{
Control ctlFound = FindControlRecursive(ctl, sControlId);
// if we found the control, return it.
if (ctlFound != null)
{
return ctlFound;
}
}
// we never found the control so just return null.
return null;
}
I call this in Page_init
protected void Page_Init(object sender, EventArgs e)
{
FormViewEdit.HeaderTemplate = new FormViewEditTemplate(ListItemType.Header, editXmlForm);
FormViewEdit.EditItemTemplate = new FormViewEditTemplate(ListItemType.EditItem, editXmlForm);
FormViewEdit.FooterTemplate = new FormViewEditTemplate(ListItemType.Footer, editXmlForm);
FormViewEdit.ItemUpdating += new FormViewUpdateEventHandler(FormView1_ItemUpdating);
EditFormView.SelectCommand = "SELECT * FROM " + UniqueTable + " WHERE " + PrimaryKey + "=" + ident;
EditFormView.DataBind();
}
protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
//TODO get all new values and make query string.
EditFormView.UpdateCommand = "UPDATE " + UniqueTable + " SET bla_Opis='" + e.NewValues["bla_Opis"] + "' WHERE " + PrimaryKey + "=" + ident;
EditFormView.Update();
EditFormView.DataBind();
}
I found the problem. I used randomly generated id for tap panel therfore I believe the the two way binding didnt work on post back. On every postback I got new id and the old data didnt find control to bind the new values.
tapPanel.ID = Guid.NewGuid().ToString();
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();
}
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.
i have imgae path in datatable[id, path] now this would a value like
ex: id path
1 F:\R&D\RD\RD\Images\a1.JPG;
2 F:\R&D\RD\RD\Images\a2.JPG;
3 F:\R&D\RD\RD\Images\a3.JPG;
now these images are in size width*height (1018*768). now i need to convert these images into thumnail
caling the function
**C_Thumbnails(100, "F:\R&D\RD\RD\Images\a1.JPG", "F:\R&D\RD\RD\Images]thum.jpg")**
public static void C_Thumbnails(int size, string FilePath, string ThumbPath)
{
System.Drawing.Image image = System.Drawing.Image.FromFile(FilePath);
try
{
int thumbHeight, thumbWidth;
decimal h = image.Height;
decimal w = image.Width;
if (image.Height > image.Width)
{
thumbHeight = size;
decimal tWidth = (w / h) * thumbHeight;
thumbWidth = Convert.ToInt32(tWidth);
}
else
{
thumbWidth = size;
decimal tHeight = (h / w) * thumbWidth;
thumbHeight = Convert.ToInt32(tHeight);
}
System.Drawing.Image thumbnailImage = image.GetThumbnailImage(thumbWidth, thumbHeight, null, IntPtr.Zero);
image.Dispose();
thumbnailImage.Save(ThumbPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex)
{
image.Dispose();
throw ex;
}
}
like this i am coverting into thumbnail image. but here i am saving the thumbnail image under the path F:\R&D\RD\RD\Images\thum.jpg .
so is there any way without saving the thumbnail in the disk and how to bind the new thumbnail image in the repeater control and i need to show image there. but if once user clicks on the thumnail image a orignal image should pop up.
if any one have did this functionlity any where let me know
working on this solution from past 2 days.
any help would be greatly appreciated
now after changing code
like this
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.Params["ImageID"];
string thumbnail = context.Request.Params["thumbnail"];
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand("select Image from Image where ImageID=" + imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
string filePath = dr["image"].ToString();
dr.Close();
if (!System.IO.File.Exists(filePath))
{
//you have a problem
return;
}
if (context.Request.Params["thumbnail"] == "true")
{
//TODO: the thumbnail
// Image thumbnailImage = originalImage.GetThumbnailImage to generate thumbnail then
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "image/" + format;
thumbnailImage.Save(Response.OutputStream, imageFormat);
thumbnailImage.Dispose();
}
else
{ //stream directly the image fromdisk
System.IO.FileStream fs = System.IO.File.OpenRead(filepath);
const int ChunkSize = 10000;
Byte[] buffer = new Byte[ChunkSize];
long dataLengthToRead = fs.Length;
while (dataLengthToRead > 0)
{
int lengthRead = fs.Read(buffer, 0, ChunkSize);
Response.OutputStream.Write(buffer, 0, lengthRead);
System.Web.HttpContext.Current.Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
}
fs.Close();
}
}
}
in repeater control i have added this line of code
','_blank','toolbar=no,menubar=no'))" > '/>
my thumbnail image is not displayed still but once i click my thumbnail image i am able to see the entire image in new pop up
You should use a Photo Image Handler to serve the pages from your disk to the clients.
Then in the repeater control
<a href="ImageHandler.ashx?thumbnail=false&id='<%# Eval("ID")%>'>
<img src="ImageHandler.ashx?thumbnail=true&id='<%# Eval("ID")%>' border='0'/>
</a>
The ideea is not to pass in the actual path/name of the file, but the ID of the item you wish to view. Then the handler will:
public void ProcessRequest(System.Web.HttpContext context)
{
string filePath = //TODO: Get File Path from ItemID = context.Request.Params["id"]
if (!System.IO.File.Exists(filePath))
{
//you have a problem
return;
}
if(context.Request.Params["thumbnail"]=="true")
{
//TODO: the thumbnail
// Image thumbnailImage = originalImage.GetThumbnailImage to generate thumbnail then
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "image/" + format;
thumbnailImage.Save(Response.OutputStream, imageFormat);
thumbnailImage.Dispose();
} else
{ //stream directly the image fromdisk
System.IO.FileStream fs = System.IO.File.OpenRead(filepath);
const int ChunkSize = 10000;
Byte[] buffer = new Byte[ChunkSize];
long dataLengthToRead = fs.Length;
while (dataLengthToRead > 0)
{
int lengthRead = fs.Read(buffer, 0, ChunkSize);
Response.OutputStream.Write(buffer, 0, lengthRead);
System.Web.HttpContext.Current.Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
}
fs.Close();
}
}