Print multiple gridviews in c# using single procedure - c#

This is my working code. I need a little help with making this iterative as I am not familiar with itextsharp.
When I click Print button, it runs MySelectProcedure1 and table result is downloaded in a PDF named DataTable.
protected void btnPrint_Click(object sender, EventArgs e)
{
Procedure("MySelectProcedure1");.
Procedure("MySelectProcedure2");
}
protected void Procedure(string Proc)
{
Connection con = new Connection();
SqlDataAdapter da;
DataTable dt;
con.con = new SqlConnection(con.str);
con.cmd.CommandText = Proc;
con.cmd.CommandType = CommandType.StoredProcedure;
da = new SqlDataAdapter();
da.SelectCommand = con.cmd;
dt = new DataTable();
try
{
con.con.Open();
da.Fill(dt);
print(dt);
}
catch (Exception ex)
{
}
finally
{
con.con.Close();
con.con.Dispose();
}
}
protected void print (DataTable dt)
{
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=DataTable.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
}
However, it does not print MySelectProcedure1 in the same PDF.
This is what I want:
Open PDF document.
Print a few lines
Print result of MySelectProcedure1
Print a few more lines
Print result of MySelectProcedure2
Close and Save PDF document
How do I do this?

Yok can create a public function for export PDF. I will write how i use it.
Create a public class for example general.cs. And add this code in it.
public static void ExportPDF(DataTable dt1, DataTable dt2)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.pdf", "PDFExport"));
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
//For First DataTable
System.IO.StringWriter stringWrite1 = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1);
DataGrid myDataGrid1 = new DataGrid();
myDataGrid1.DataSource = dt1;
myDataGrid1.DataBind();
myDataGrid1.RenderControl(htmlWrite1);
//For Second DataTable
System.IO.StringWriter stringWrite2 = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite2 = new HtmlTextWriter(stringWrite2);
DataGrid myDataGrid2 = new DataGrid();
myDataGrid2.DataSource = dt2;
myDataGrid2.DataBind();
myDataGrid2.RenderControl(htmlWrite2);
//You can add more DataTable
StringReader sr = new StringReader(stringWrite1.ToString() + stringWrite2.ToString());
Document pdfDoc = new Document(new Rectangle(288f, 144f), 10f, 10f, 10f, 0f);
pdfDoc.SetPageSize(PageSize.A4.Rotate());
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
HttpContext.Current.Response.Write(pdfDoc);
HttpContext.Current.Response.End();
}
When you need PDF only call this function
protected void lnkExportPDF_Click(object sender, EventArgs e)
{
General.ExportPDF(rptList);
}
public override void VerifyRenderingInServerForm(Control control)
{ }

Related

How to make excel file on read only mode using itextsharp in C#

I want to export excel file in readonly mode, no one can copy the cells data neither edit.
My code is:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=MorotoriamReportData.xls");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter htmlwr = new HtmlTextWriter(sw);
Document pdfDoc = new Document(PageSize.A4.Rotate(), 10f, 10f, 10f, 0f);
gvViewLedger.AllowPaging = false;
gvViewLedger.RenderControl(htmlwr);
string headerTable = #"<Table><tr><td>Report Header</td></tr><tr><td>a</td></tr></Table>";
Response.Write(headerTable);
Response.Write(sw.ToString());
Response.End();
btnExport.Visible = false;
}
This is not possible using the HttpResponse object. You may want to look into using something like EPPlus

Converting a modal dialog window to pdf

I'm trying to convert a modal dialog with 3 DataTables to pdf using iTextSharp:
DataTable dtTable = (DataTable)ViewState["LoanPlan"];
DataTable dtTax = (DataTable)ViewState["PlanTaxData"];
DataTable dtPlan = (DataTable)ViewState["PlanAllData"];
I'm using this code to try and accomplish it:
protected void buttonPDF_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
this.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
But it seems that it's actually trying to convert the whole .aspx page to .pdf format. How should I go about targeting just the modal dialogue or just the 3 DataTables?

Export gridview WebPart to PDF using htmlForm

All the master, I have trouble about my gridview wich will export to PDF using iText and HtmForm .
I've browse on any sites, they suggest using HtmlForm and iText, but theres ways is enable for aspx not for webpart.
When I implement on my WebPart, the result export to pdf is to many code (I Mean thats code gernerated default of asp) .
this my code .
Page.Response.ContentType = "application/pdf";
Page.Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm();
MyGridView.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(MyGridView);
frm.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Page.Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Page.Response.Write(pdfDoc);
Page.Response.End();
And this is result export to pdf
//var theForm = document.forms['aspnetForm']; if (!theForm) { theForm = document.aspnetForm; } function
__doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit(); } } ////var MSOWebPartPageFormName = 'aspnetForm'; var g_presenceEnabled = true;
var g_wsaEnabled = false; var g_wsaQoSEnabled = false; var g_wsaQoSDataPoints = []; var g_wsaLCID =
1033; var g_wsaListTemplateId = 850; var g_wsaSiteTemplateId = 'BLANKINTERNET#0'; var ULS;if (!ULS)
ULS=new Object();ULS.enable=true;ULS.Correlation="f1edb09c-3170-50d3-ebe2-8970f486cf98";var
_fV4UI=true;var _spPageContextInfo = {webServerRelativeUrl: "\u002fsites\u002ffifpeduli", webAbsoluteUrl:
"http:\u002f\u002febiz4:8882\u002fsites\u002ffifpeduli", siteAbsoluteUrl:
"http:\u002f\u002febiz4:8882\u002fsites\u002ffifpeduli", serverRequestPath:
"\u002fsites\u002ffifpeduli\u002fPages\u002fBookingBusOperational.aspx", layoutsUrl: "_layouts\u002f15",
webTitle: "Bus Peduli", webTemplate: "53", tenantAppVersion: "0", webLogoUrl:
"_layouts\u002f15\u002fimages\u002fsiteicon.png", webLanguage: 1033, currentLanguage: 1033,
currentUICultureName: "en-US", currentCultureName: "en-US", clientServerTimeDelta: new Date("2014-08-22T07:50:45.8058752Z") - new Date(), siteClientTag: "35$$15.0.4569.1000",
crossDomainPhotosEnabled:false, webUIVersion:15,
webPermMasks:{High:432,Low:1011028719},pageListId:"{cda1b8fe-a191-40ae-9d5b-32845313a173}",pageItemId:31, pagePersonalizationScope:1,userId:161, systemUserKey:"i:0\u0029.w|s-1-5-21-3191234019-2725770046-3684772125-1119", alertsEnabled:false, siteServerRelativeUrl:
"\u002fsites\u002ffifpeduli", allowSilverlightPrompt:'True'};function CallServer_59082126(arg, context)
{WebForm_DoCallback('ctl00$ctl21',arg,SP.UI.MyLinksRibbon.MyLinksRibbonPageComponent.ribbonActio
nCallback,context,null,false); }function _myLinksRibbonLoad2() { var fnd = function () { try {
mylinks_init.MyLinksInit('CallServer_59082126'); } catch (Ex) { } }; RegisterSod('mylinks_init',
'/_layouts/15/SP.UI.MyLinksRibbon.js'); LoadSodByKey('mylinks_init', fnd); } function
_myLinksRibbonLoad1() { ExecuteOrDelayUntilScriptLoaded(_myLinksRibbonLoad2, 'SP.Ribbon.js'); }
_spBodyOnLoadFunctionNames.push('_myLinksRibbonLoad1'); var L_Menu_BaseUrl="/sites/fifpeduli"; var
L_Menu_LCID="1033"; var L_Menu_SiteTheme="null"; document.onreadystatechange=fnRemoveAllStatus;
function fnRemoveAllStatus(){removeAllStatus(true)};function WebForm_OnSubmit() {
UpdateFormDigest('\u002fsites\u002ffifpeduli', 1440000); return true; } //
No. FieldOne FieldTwo FieldThree FieldFour FieldFive
1 BEKASI 500.000
2 HEAD OFFICE 225.500 7.205.000 670.001 121.230.712
Total Result 225.500 7.205.000 670.001 121.730.712
//WebForm_InitCallback();var _spFormDigestRefreshInterval = 1440000;//
In real My pdf the table is real, sory before because can't upload image . because my reputations .
Please use below code.
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
private void GetInPDf()
{
if (gridview.Rows.Count > 0)
{
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gridview.RenderControl(htw);
var mem = new MemoryStream();
Document document = new Document(PageSize.LETTER, 50, 50, 50, 50);
PdfWriter.GetInstance(document, mem);
document.Open();
iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
hw.Parse(new StringReader(sw.ToString()));
document.Close();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now);
Response.BinaryWrite(mem.ToArray());
Response.End();
Response.Flush();
Response.Clear();
}
}

Export to pdf | How to show option to open and save

I have this working code for exporting to pdf. When I export it , it asks me location to save file. Instead , I want to have option of OPEN or SAVE . Currently what I am doing is :
protected void btnPdf_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView2.AllowPaging = false;
GridView2.DataBind();
GridView2.RenderControl(hw);
GridView2.HeaderRow.Style.Add("width", "15%");
GridView2.HeaderRow.Style.Add("font-size", "10px");
GridView2.Style.Add("text-decoration", "none");
GridView2.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
GridView2.Style.Add("font-size", "8px");
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
If you have the file on the server
Response.TransmitFile(//FILE PATH);
If you don't
Response.BinaryWrite(//Pass Byte Array)

how to export gridview image and data to PDF using asp.net or Export gridview data to PDF using asp.net

protected void Button4_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition","attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);//this is the error line
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
You will have to use 3rd party control for that
Try using iText Sharp library its free
for more info go here

Categories

Resources