Tuesday, June 7, 2022

How to convert div to PDF with coding ASP.NET C#

 


    {

        String Covering_ID = "";

        // New

        DataTable dt_CoverID = new DataTable();

        string UserQuery = "Select ISNULL(Max(I_KIA_InvoiceCover_ID),0)+1 as I_KIA_InvoiceCover_ID from T005_InvoiceDetails";

        dt_CoverID = Luminious.DataAcessLayer.SqlHelper.ExecuteDataTable(Luminious.Connection.Configuration.ConnectionString, CommandType.Text, UserQuery,

        new SqlParameter[] { });

        if (dt_CoverID != null && dt_CoverID.Rows.Count > 0)

        {

            Covering_ID = Convert.ToString(dt_CoverID.Rows[0]["I_KIA_InvoiceCover_ID"]);

        }



        //For PDF Name


        String Invoice_FileName = "";

        String Invoice_FileName_CF = "";

        if (Type == false)

        {

            Invoice_FileName = "Covering-" + Covering_ID + ".pdf";

        }

        else

        {

            Invoice_FileName = "Covering-" + Covering_ID + ".pdf";

            Invoice_FileName_CF = "CoveringCF-" + Covering_ID + ".pdf";

        }


        // Save in DB


        DataTable dt = new DataTable();

        SqlParameter[] Parm = new SqlParameter[]

                        {

                        new SqlParameter("@I_KIA_InvoiceUpload", Invoice_FileName),

                        new SqlParameter("@I_KIA_InvoiceUpload_CF", Invoice_FileName_CF),

                        new SqlParameter("@I_TP_State", Convert.ToInt16(DDL_State.SelectedValue)),  

                        new SqlParameter("@I_TP_ID", Convert.ToString(DDL_TP.SelectedValue)),  

                        new SqlParameter("@I_ID", dtI_ID),  

                        new SqlParameter("@Combine_I_No", CombineInvoiceNo),  

                        new SqlParameter("@Entryby", Convert.ToString(Session["CAId"]))  

                        };


        dt = Luminious.DataAcessLayer.SqlHelper.ExecuteDataTable(Luminious.Connection.Configuration.ConnectionString, CommandType.StoredProcedure, "SP_Update_InvoiceUpload_KIA", Parm);

        if (dt != null && dt.Rows.Count > 0)

        {

            Covering_ID = Convert.ToString(dt.Rows[0]["Cover_ID"]);

            String Covering_No = Convert.ToString(dt.Rows[0]["Cover_No"]);

            Lbl_CoveringNo.Text = Covering_No;

            Lbl_CoveringNoCF.Text = Covering_No;

            Lbl_CoveringNoRCCF.Text = Covering_No;

        }


        //Pdf cerate and save in folder

        Response.ContentType = "application/pdf";

        StringWriter stringWriter = new StringWriter();

        StringWriter stringWriter1 = new StringWriter();

        StringWriter stringWriter2 = new StringWriter();

        StringWriter stringWriter3 = new StringWriter();

        StringWriter stringWriter4 = new StringWriter();

        StringWriter stringWriter5 = new StringWriter();


        HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);

        HtmlTextWriter htmlTextWriter1 = new HtmlTextWriter(stringWriter1);

        HtmlTextWriter htmlTextWriter2 = new HtmlTextWriter(stringWriter2);

        HtmlTextWriter htmlTextWriter3 = new HtmlTextWriter(stringWriter3);

        HtmlTextWriter htmlTextWriter4 = new HtmlTextWriter(stringWriter4);

        HtmlTextWriter htmlTextWriter5 = new HtmlTextWriter(stringWriter5);



        if (Type == false)

        {

            //Div_Covering.RenderControl(htmlTextWriter);

            Div_Covering_UpperContent.RenderControl(htmlTextWriter);

            Div_Covering_LowerContent.RenderControl(htmlTextWriter1);


        }

        else

        {

            Div_Covering_RCCF_UpperContent.RenderControl(htmlTextWriter2);

            Div_Covering_RCCF_LowerContent.RenderControl(htmlTextWriter3);

            Div_Covering_CF_UpperContent.RenderControl(htmlTextWriter4);

            Div_Covering_CF_LowerContent.RenderControl(htmlTextWriter5);

            //Grid_InvoiceList.Visible = false;



        }


        //Start Pdf cerate for CF,RCCF and save in folder

        PdfPTable table = null;

        //Start Pdf cerate for CF and save in folder

        PdfPTable table1 = null;

        //Start Pdf cerate for RCCF and save in folder

        PdfPTable table2 = null;


        if (Type == false)

        {


            int colCount = Grid_InvoiceListLoad.Columns.Count;


            table = new PdfPTable(colCount);

            table.HorizontalAlignment = 1;

            table.WidthPercentage = 100;


            int[] colWidths = new int[Grid_InvoiceListLoad.Columns.Count];

            float[] widths = new float[] { 8f, 20f, 18f, 18f, 30f, 16f, 20f, 18f };

            table.SetWidths(widths);


            PdfPCell cell;

            string cellText;


            for (int colIndex = 0; colIndex < colCount; colIndex++)

            {


                colWidths[colIndex] = (int)Grid_InvoiceListLoad.Columns[colIndex].ItemStyle.Width.Value;

                cellText = Server.HtmlDecode(Grid_InvoiceListLoad.HeaderRow.Cells[colIndex].Text);


                BaseFont bf = BaseFont.CreateFont();


                iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10);

                cell = new PdfPCell(new Phrase(cellText.Replace("<br />", Environment.NewLine), font));

                // table.Columns["ColName"].Visible = false;

                cell.HorizontalAlignment = Element.ALIGN_CENTER;

                cell.VerticalAlignment = Element.ALIGN_MIDDLE;

                cell.FixedHeight = 30f;


                //cell.BackgroundColor = new GridNoteSheet(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));

                cell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#C2D69B"));


                table.AddCell(cell);

            }



            for (int rowIndex = 0; rowIndex < Grid_InvoiceListLoad.Rows.Count; rowIndex++)

            {

                if (Grid_InvoiceList.Rows[rowIndex].RowType == DataControlRowType.DataRow)

                {

                    for (int j = 0; j < Grid_InvoiceListLoad.Columns.Count; j++)

                    {

                        cellText = Server.HtmlDecode(Grid_InvoiceListLoad.Rows[rowIndex].Cells[j].Text);

                        cell = new PdfPCell(new Phrase(cellText, FontFactory.GetFont("PrepareForExport", 8)));

                        cell.HorizontalAlignment = Element.ALIGN_CENTER;

                        cell.VerticalAlignment = Element.ALIGN_MIDDLE;

                        cell.FixedHeight = 25f;

                        table.AddCell(cell);


                    }

                }

            }


            //End Pdf cerate for CF,RCCF and save in folder

        }

        else

        {


            int colCount1 = Grid_InvoiceList_CF.Columns.Count;


            table1 = new PdfPTable(colCount1);

            table1.HorizontalAlignment = 1;

            table1.WidthPercentage = 100;



            float[] widths = new float[] { 8f, 20f, 18f, 18f, 30f, 16f };

            table1.SetWidths(widths);

            int[] colWidths1 = new int[Grid_InvoiceList_CF.Columns.Count];


            PdfPCell cell1;

            string cellText1;


            for (int colIndex1 = 0; colIndex1 < colCount1; colIndex1++)

            {


                colWidths1[colIndex1] = (int)Grid_InvoiceList_CF.Columns[colIndex1].ItemStyle.Width.Value;

                cellText1 = Server.HtmlDecode(Grid_InvoiceList_CF.HeaderRow.Cells[colIndex1].Text);


                BaseFont bf = BaseFont.CreateFont();


                iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10);

                cell1 = new PdfPCell(new Phrase(cellText1.Replace("<br />", Environment.NewLine), font));

                // table.Columns["ColName"].Visible = false;

                cell1.HorizontalAlignment = Element.ALIGN_CENTER;

                cell1.VerticalAlignment = Element.ALIGN_MIDDLE;

                cell1.FixedHeight = 30f;


                //cell.BackgroundColor = new GridNoteSheet(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));

                cell1.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#C2D69B"));


                table1.AddCell(cell1);

            }



            for (int rowIndex1 = 0; rowIndex1 < Grid_InvoiceList_CF.Rows.Count; rowIndex1++)

            {

                if (Grid_InvoiceList_CF.Rows[rowIndex1].RowType == DataControlRowType.DataRow)

                {

                    for (int j = 0; j < Grid_InvoiceList_CF.Columns.Count; j++)

                    {

                        cellText1 = Server.HtmlDecode(Grid_InvoiceList_CF.Rows[rowIndex1].Cells[j].Text);

                        cell1 = new PdfPCell(new Phrase(cellText1, FontFactory.GetFont("PrepareForExport", 8)));

                        cell1.HorizontalAlignment = Element.ALIGN_CENTER;

                        cell1.VerticalAlignment = Element.ALIGN_MIDDLE;

                        cell1.FixedHeight = 25f;

                        table1.AddCell(cell1);


                    }

                }

            }


            //End Pdf cerate for CF and save in folder




            int colCount2 = Grid_InvoiceList_RCCF.Columns.Count;


            table2 = new PdfPTable(colCount2);

            table2.HorizontalAlignment = 1;

            table2.WidthPercentage = 100;


            float[] widths1 = new float[] { 8f, 20f, 18f, 18f, 30f, 16f };

            table2.SetWidths(widths1);

            int[] colWidths2 = new int[Grid_InvoiceList_RCCF.Columns.Count];


            PdfPCell cell2;

            string cellText2;


            for (int colIndex2 = 0; colIndex2 < colCount2; colIndex2++)

            {


                colWidths2[colIndex2] = (int)Grid_InvoiceList_RCCF.Columns[colIndex2].ItemStyle.Width.Value;

                cellText2 = Server.HtmlDecode(Grid_InvoiceList_RCCF.HeaderRow.Cells[colIndex2].Text);


                BaseFont bf = BaseFont.CreateFont();


                iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10);

                cell2 = new PdfPCell(new Phrase(cellText2.Replace("<br />", Environment.NewLine), font));

                // table.Columns["ColName"].Visible = false;

                cell2.HorizontalAlignment = Element.ALIGN_CENTER;

                cell2.VerticalAlignment = Element.ALIGN_MIDDLE;

                cell2.FixedHeight = 30f;


                //cell.BackgroundColor = new GridNoteSheet(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));

                cell2.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#C2D69B"));


                table2.AddCell(cell2);

            }



            for (int rowIndex2 = 0; rowIndex2 < Grid_InvoiceList_RCCF.Rows.Count; rowIndex2++)

            {

                if (Grid_InvoiceList.Rows[rowIndex2].RowType == DataControlRowType.DataRow)

                {

                    for (int j = 0; j < Grid_InvoiceList_RCCF.Columns.Count; j++)

                    {

                        cellText2 = Server.HtmlDecode(Grid_InvoiceList_RCCF.Rows[rowIndex2].Cells[j].Text);

                        cell2 = new PdfPCell(new Phrase(cellText2, FontFactory.GetFont("PrepareForExport", 8)));

                        cell2.HorizontalAlignment = Element.ALIGN_CENTER;

                        cell2.VerticalAlignment = Element.ALIGN_MIDDLE;

                        cell2.FixedHeight = 25f;

                        table2.AddCell(cell2);


                    }

                }

            }


            //End Pdf cerate for RCCF and save in folder        

        }

        StringReader stringReader = new StringReader(stringWriter.ToString());

        StringReader stringReader1 = new StringReader(stringWriter1.ToString());

        StringReader stringReader2 = new StringReader(stringWriter2.ToString());

        StringReader stringReader3 = new StringReader(stringWriter3.ToString());

        StringReader stringReader4 = new StringReader(stringWriter4.ToString());

        StringReader stringReader5 = new StringReader(stringWriter5.ToString());



        if (Type == false)

        {

            Document Doc = new Document(PageSize.A4, 20f, 20f, 20f, 20f);

            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();

            PdfWriter writer = PdfWriter.GetInstance(Doc, memoryStream);

            HTMLWorker htmlparser = new HTMLWorker(Doc);

            PdfWriter.GetInstance(Doc, Response.OutputStream);

            Doc.Open();


            htmlparser.Parse(stringReader);

            Doc.Add(table);

            htmlparser.Parse(stringReader1);


            Paragraph p1 = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, CMYKColor.BLACK, Element.ALIGN_LEFT, 1)));

            Doc.Add(p1);


            BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);

            Paragraph para = new Paragraph(new Chunk("This is system generated covering letter", font));

            para.Alignment = Element.ALIGN_CENTER;


            Doc.Add(para);


            //Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, CMYKColor.BLACK, Element.ALIGN_LEFT, 1)));

            //Doc.Add(p);


            Doc.Close();


            byte[] bytes = memoryStream.ToArray();

            System.IO.File.WriteAllBytes(Server.MapPath("~/View/CertificationAgency/ManageInvoice/Invoice/") + Invoice_FileName, bytes);

        }

        else

        {

            Document Doc = new Document(PageSize.A4, 20f, 20f, 20f, 20f);

            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();

            PdfWriter writer = PdfWriter.GetInstance(Doc, memoryStream);

            HTMLWorker htmlparser = new HTMLWorker(Doc);

            PdfWriter.GetInstance(Doc, Response.OutputStream);

            Doc.Open();


            htmlparser.Parse(stringReader2);

            Doc.Add(table2);

            htmlparser.Parse(stringReader3);


            Paragraph p1 = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, CMYKColor.BLACK, Element.ALIGN_LEFT, 1)));

            Doc.Add(p1);



            BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);

            Paragraph para = new Paragraph(new Chunk("This is system generated covering letter", font));

            para.Alignment = Element.ALIGN_CENTER;

            Doc.Add(para);



            //Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, CMYKColor.BLACK, Element.ALIGN_LEFT, 1)));

            //Doc.Add(p);


            Doc.Close();


            Document Doc1 = new Document(PageSize.A4, 20f, 20f, 20f, 20f);

            System.IO.MemoryStream memoryStream1 = new System.IO.MemoryStream();

            PdfWriter writer1 = PdfWriter.GetInstance(Doc1, memoryStream1);

            HTMLWorker htmlparser1 = new HTMLWorker(Doc1);

            PdfWriter.GetInstance(Doc1, Response.OutputStream);

            Doc1.Open();


            htmlparser1.Parse(stringReader4);

            Doc1.Add(table1);

            htmlparser1.Parse(stringReader5);


            Paragraph p2 = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, CMYKColor.BLACK, Element.ALIGN_LEFT, 1)));

            Doc1.Add(p2);



            BaseFont bf1 = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font font1 = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);

            Paragraph para1 = new Paragraph(new Chunk("This is system generated covering letter", font1));

            para1.Alignment = Element.ALIGN_CENTER;


            Doc1.Add(para1);


            //Paragraph p3 = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, CMYKColor.BLACK, Element.ALIGN_LEFT, 1)));

            //Doc1.Add(p3);


            Doc1.Close();


            byte[] bytes = memoryStream.ToArray();

            System.IO.File.WriteAllBytes(Server.MapPath("~/View/CertificationAgency/ManageInvoice/Invoice/") + Invoice_FileName, bytes);


            byte[] bytes1 = memoryStream1.ToArray();

            System.IO.File.WriteAllBytes(Server.MapPath("~/View/CertificationAgency/ManageInvoice/Invoice/") + Invoice_FileName_CF, bytes1);


        }


        try

        {

            BLL_LoginAudit objAudit = new BLL_LoginAudit();

            objAudit.Transction(new BO_LoginAuditMaster

            {

                Login_action = "I",

                Login_Action_Type = "Covering Created/" + Invoice_FileName,

                Login_Audit_id = 0,

                Login_Date_Time = DateTime.Now,

                Login_IP_Address = LuminiousUtility.Util.Utility.VisitorIPAddress(),

                Login_Module_Name = "KIA",

                Login_Section_Name = LuminiousUtility.Util.Utility.BrowserDetection(),

                Login_Status = "Success",

                Login_User_Name = Convert.ToString(Session["CArsession"]),

                Login_User_Type = 3

            });

        }

        catch (Exception ee)

        {

            ExceptionHandler.WriteException(ee.Message);

        }


        Response.Redirect("KIA_InvoiceInbox.aspx");

    }


/////////////////////////////////////////////////////////////////////////////////////

Converting a asp panel to word file


protected void btnPDF_Click(object sender, EventArgs e)

    {

        Response.AddHeader("content-disposition", "attachment;filename=Export.doc");

        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        Response.ContentType = "application/vnd.word";


        System.IO.StringWriter stringWrite = new System.IO.StringWriter();

        System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);



        System.Web.UI.HtmlControls.HtmlForm frm = new System.Web.UI.HtmlControls.HtmlForm();

        panel_disp.Parent.Controls.Add(frm);

       


        frm.Attributes["runat"] = "server";

        frm.Controls.Add(panel_disp);

      


        frm.RenderControl(htmlWrite);

        // frm.RenderControl(strBody);



        Response.Write(stringWrite.ToString());


        Response.End();

        

    }


////////////////////////////////////////////////////////////

Print panel in asp.net

public static void PrintWebControl(Control ctrl, string Script)

    {

        StringWriter stringWrite = new StringWriter();

        System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);

        if (ctrl is WebControl)

        {

            Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;

        }

        Page pg = new Page();

        pg.EnableEventValidation = false;

        if (Script != string.Empty)

        {

            pg.ClientScript.RegisterStartupScript(pg.GetType(), "PrintJavaScript", Script);

        }

        HtmlForm frm = new HtmlForm();

        pg.Controls.Add(frm);

        frm.Attributes.Add("runat", "server");

        frm.Controls.Add(ctrl);

        pg.DesignerInitialize();

        pg.RenderControl(htmlWrite);

        string strHTML = stringWrite.ToString();

        HttpContext.Current.Response.Clear();

        HttpContext.Current.Response.Write(strHTML);

        HttpContext.Current.Response.Write("<script>window.print();</script>");

        HttpContext.Current.Response.End();

    }

No comments:

Post a Comment