LoadStyle() 공개 메소드

public LoadStyle ( String style, Hashtable props ) : void
style String
props System.Collections.Hashtable
리턴 void
예제 #1
0
    protected void btnGenPdf_Click(object sender, EventArgs e)
    {
        iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
        styles.LoadStyle("Invoice-Wrp", "width", "1200px");
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=PaymentInvoice.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter   sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        this.Page.RenderControl(hw);
        StringReader sr         = new StringReader(sw.ToString());
        Document     pdfDoc     = new Document(PageSize.A4, 50f, 50f, 50f, 50f);
        HTMLWorker   htmlparser = new HTMLWorker(pdfDoc);

        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
    }
예제 #2
0
        public void GeneralLetter(String CreditControlID)
        {
            try
               {

               BillCreditControlList Vwobj = new BillCreditControlList();
               Vwobj = BAL.BillCreditControlModel.ViewCreditControlReminderLetter(CreditControlID);

               if (Vwobj != null)
               {
                   var document = new Document(PageSize.A4, 50, 50, 25, 25);
                   String PDFName = Vwobj.BillNo + "-" + Vwobj.ID.ToString() + ".pdf";
                   var filePath = Path.Combine(Server.MapPath("~/PdfContent/CreditControl/Letter"), PDFName);
                   //  var output = new MemoryStream();
                   var output = new FileStream(filePath, FileMode.Create);

                   var writer = PdfWriter.GetInstance(document, output);
                   try
                   {
                       // Open the Document for writing
                       document.Open();
                       // Read in the contents of the Receipt.htm file...

                       StyleSheet styles = new StyleSheet();
                       //styles.LoadTagStyle(HtmlTags.H1, HtmlTags.FONTSIZE, "16");
                       //styles.LoadTagStyle(HtmlTags.P, HtmlTags.FONTSIZE, "10");
                       //styles.LoadTagStyle(HtmlTags.P, HtmlTags.m, "#ff0000");

                       //styles.LoadTagStyle(HtmlTags.CLASS, HtmlTags.COLOR, "#ff0000");
                       styles.LoadTagStyle(HtmlTags.TD, HtmlTags.ALIGN, "left");
                       styles.LoadTagStyle(HtmlTags.TD, HtmlTags.CELLPADDING, "10");
                       styles.LoadTagStyle(HtmlTags.P, HtmlTags.P, "margin-bottom:20px");
                       styles.LoadTagStyle(HtmlTags.P, HtmlTags.SPAN, "text-decoration:underline;");
                       styles.LoadStyle("Subject", "ALIGN", "center");
                       styles.LoadStyle("Subject", "FONTSIZE", "26px");
                       styles.LoadStyle("Subject", "color", "#ff0000");
                       styles.LoadStyle("c_outstanding", "font-size", "20px");
                       styles.LoadStyle("c_outstanding", "text-align", "center");

                       String contents = System.IO.File.ReadAllText(Server.MapPath("~/HTMLTemplate/GeneralLetter.htm"));

                       // Replace the placeholders with the user-specified text
                       contents = contents.Replace("[CustomerName]", Vwobj.ConsumerName.Trim());
                       contents = contents.Replace("[AddressLine1]", Vwobj.ConsumerAddress.Trim());
                       contents = contents.Replace("[AddressLine2]", Vwobj.ConsumerCounty.Trim());
                       contents = contents.Replace("[AddressLine3]", Vwobj.ConsumerCity.Trim());

                       contents = contents.Replace("[PostCode]", Vwobj.ConsumerZipCode.Trim());
                       contents = contents.Replace("[Amount]", Vwobj.LastBillAmount.ToString().Trim());
                      //' contents = contents.Replace("[propertyAddress]", Vwobj.PropertyNo.Trim());
                       contents = contents.Replace("[sitename]", Vwobj.SiteName.Trim());
                       contents = contents.Replace("[balanceofaccount]", Vwobj.Balance.ToString());
                       contents = contents.Replace("[invoicedateFrom]", Vwobj.InvoiceDateForm);
                       contents = contents.Replace("[invoicedateTo]", Vwobj.InvoiceDateTo);
                       contents = contents.Replace("[InvioceDate]", Vwobj.InvoiceDate);
                       contents = contents.Replace("[ClientName]", Vwobj.ClientName);
                       contents = contents.Replace("[ClientTelephoneNumber]", Vwobj.ClientTelephone);
                       contents = contents.Replace("[ClientEmailAddress]", Vwobj.ClientEmail);
                       var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), styles);
                       // Enumerate the elements, adding each one to the Document...
                       foreach (var htmlElement in parsedHtmlElements)
                       {
                           document.Add(htmlElement as IElement);
                       }

                       writer.CloseStream = false;
                       document.Close();
                       output.Dispose();

                   }
                   catch (Exception ex)
                   {
                       output.Dispose();
                       document.Dispose();
                   }

               }//if
               }//try
               catch (Exception ex)
               {
               throw;
               }
        }
예제 #3
0
    public void PDFFormato1(string FilePath, int numPaginas, string[] cuerpoHTML, string nomDoc, string title)
    {
        try
        {
            //Se Crea El Documento tamaño Carta
            Document document = new Document(PageSize.LETTER, 100, 100, 100, 100);

            //Se Obtiene la ruta del servidor
            string ruta = HttpContext.Current.Server.MapPath("~/");;
            //Indicamos donde se va a guardar eldocumento
            PdfWriter.GetInstance(document, new FileStream(ruta + "\\\\" + nomDoc + ".pdf", FileMode.Create));

            //se abre el documento
            document.Open();
            document.AddTitle(title);



            for (int i = 0; i < numPaginas; i++)
            {
                string HTML = "";
                // Crea una imagen
                iTextSharp.text.Image pdfImage;
                iTextSharp.text.Image pdflogo;
                iTextSharp.text.Image pdfInfo;

                //Se obtiene la ruta de la imagen
                pdfImage = iTextSharp.text.Image.GetInstance(ruta + "/images/marca.png");
                pdflogo  = iTextSharp.text.Image.GetInstance(ruta + "/images/logo.png");
                pdfInfo  = iTextSharp.text.Image.GetInstance(ruta + "/images/Info.png");

                //se pone el tamaño
                pdfImage.ScaleToFit(200, 790);
                pdflogo.ScaleToFit(200, 790);
                pdfInfo.ScaleToFit(400, 790);


                //se Indica la posicion
                pdfImage.Alignment = iTextSharp.text.Image.UNDERLYING;

                pdfImage.SetAbsolutePosition(0, 1);

                pdflogo.Alignment = iTextSharp.text.Image.UNDERLYING;

                pdflogo.SetAbsolutePosition(400, 685);

                pdfInfo.Alignment = iTextSharp.text.Image.UNDERLYING;

                pdfInfo.SetAbsolutePosition(200, 3);
                //Se agrega la imagen al documento
                document.Add(pdfImage);
                document.Add(pdflogo);
                document.Add(pdfInfo);


                //se crea un objeto para estilos
                iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();

                //obleto tipo html
                //iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document,styles);

                styles.LoadTagStyle("p", "color", "red");
                styles.LoadStyle("redBigText", "size", "20pt");
                styles.LoadStyle("redBigText", "color", "RED");

                //obleto tipo html
                iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
                if (cuerpoHTML.Count() > i)
                {
                    HTML = cuerpoHTML[i];
                }
                else
                {
                    HTML = "";
                }

                /*  Paragraph p = new Paragraph();
                 * p.IndentationLeft = 100;
                 * HTML.HorizontalAlignment = Element.ALIGN_LEFT;
                 * p.Add(outerTable);
                 * document.Add(p);*/
                //hw.Parse(new StringReader(HTML),styles);
                //var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(HTML), styles);
                hw.Parse(new StringReader(HTML));
                // HTMLWorker.ParseToList(new StringReader(HTML), styles);
                document.NewPage();
            }


            //se Cierra el document0
            document.Close();

            //se muestra el documento
            mostrarPDF(nomDoc + ".pdf", ruta);
        }
        catch (Exception ex)
        {
            Console.Write(ex.Message);
        }
    }
    // Versão Original em: https://social.msdn.microsoft.com/Forums/pt-BR/049133ce-2ce0-4b6e-9194-53b62e12ddbe/como-gerar-um-arquivo-pdf-a-partir-de-uma-pagina-aspx?forum=aspnetpt
    private void ConverteAspx2Pdf()
    {
        // Limpa qualquer coisa já previamente renderizada!
        Response.ClearContent();
        // Para fazer download direto é só descomentar a linha abaixo, caso contrario o PDF é exibido no navegador
        // Response.AddHeader("content-disposition", "attachment; filename=ExportacaoAspx2Pdf.pdf"); 
        
        // Altera o tipo de documento
        Response.ContentType = "application/pdf";

        // Prepara um buffer que conterá todo o HTML que é renderizado
        StringWriter stw = new StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);

        // Renderiza todo o HTML do ASPX no buffer (string)
        this.RenderControl(htextw);

        // Cria um novo documento PDF em branco
        Document doc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);

        // Define o local de saida (gravação) do PDF como o dispositivo de transmissão do ASP.Net que vai para o navegador
        PdfWriter.GetInstance(doc, Response.OutputStream);
        doc.Open();

        // Os estilos do boleto devem ser definidos desta forma
        // http://stackoverflow.com/questions/8414637/itextsharp-htmlworker-parsehtml-tablestyle-and-pdfstamper
        
        StyleSheet styles = new StyleSheet();

        Dictionary<string, string> BolCell = new Dictionary<string, string>();
        //styles.LoadStyle("BolCell", "size", "7px");
        BolCell.Add("size", "7pt");
        //BolCell.Add("face", "verdana");
        styles.LoadStyle("BolCell", BolCell);

        Dictionary<string, string> BolField = new Dictionary<string, string>();
        styles.LoadStyle("BolField", "size", "12px");
        //BolField.Add("weight", "bold");
        BolField.Add("size", "9pt");
        //BolField.Add("face", "arial");
        styles.LoadStyle("BolField", BolField);

        // Lê o HTML completo do buffer como uma String
        StringReader str = new StringReader(stw.ToString());

        // Chama um conversor interno de HTML para PDF
        HTMLWorker htmlworker = new HTMLWorker(doc);

        // Transforma o HTML em PDF
        htmlworker.SetStyleSheet(styles);
        htmlworker.Parse(str);

        // fim do PDF
        doc.Close();

        // Transmite o HTML para o browser
        Response.Write(doc);

        // Finaliza tudo! 
        Response.End();
    }
예제 #5
0
        /// pending: 

        public static StyleSheet getStyleSheet_ApprovedSwitch()
        {
            StyleSheet Style = new StyleSheet();
            Style.LoadTagStyle(HtmlTags.BODY, HtmlTags.FONTSIZE, "5");
            Style.LoadTagStyle(HtmlTags.TH, HtmlTags.TEXTALIGN, "center");
            Style.LoadTagStyle(HtmlTags.TH, HtmlTags.FONTWEIGHT, "bolder");
            Style.LoadStyle("title", HtmlTags.TEXTALIGN, "center");
            //Style.LoadStyle("title", HtmlTags.FONTSIZE, "1em");
            Style.LoadStyle("title", HtmlTags.FONTWEIGHT, "bolder");
            Style.LoadStyle("left", HtmlTags.WIDTH, "40%");
            Style.LoadStyle("left", HtmlTags.FONTWEIGHT, "bold");
            Style.LoadStyle("left", "padding", "0px");
            Style.LoadStyle("right", "padding", "0px");
            Style.LoadStyle("right", HtmlTags.WIDTH, "60%");
            Style.LoadStyle("right", HtmlTags.PADDINGLEFT, "0.5em");
            return Style;
        }
예제 #6
0
        /// <summary>
        /// Merge CV and covering letter and return pdf location
        /// </summary>
        /// <param name="filesToMerge"></param>
        /// <param name="outputFilename"></param>
        /// <param name="result"></param>
        public static void MergePdf(IEnumerable<BulkPrintDocEntry> filesToMerge, string outputFilename, ref BulkPrintCvResult result)
        {
            result.ErrorCvs = new List<BulkPrintErrorCvs>();
            var bulkPrintDocEntries = filesToMerge as BulkPrintDocEntry[] ?? filesToMerge.ToArray();
            if (!bulkPrintDocEntries.Any()) return;
            var document = new iTextSharp.text.Document();
            // initialize pdf writer
            var writer = PdfWriter.GetInstance(document, new FileStream(outputFilename, FileMode.Create));
            // open document to write
            document.Open();
            var content = writer.DirectContent;
            foreach (var docEntry in bulkPrintDocEntries)
            {
                var sCoveringLetterHtml = docEntry.CoveringLetterHtml;
                // create page
                document.NewPage();
                // add styles
                var styles = new StyleSheet();
                styles.LoadStyle("left", "width", "22%");
                styles.LoadTagStyle("td", "valign", "top");
                styles.LoadStyle("bordered", "border", "1");
                var hw = new HTMLWorker(document, null, styles);
                hw.Parse(new StringReader(sCoveringLetterHtml));
                var sFileName = docEntry.CvFileName.ToLower().Replace(".docx", ".pdf").Replace(".DOCX", ".pdf").Replace(".doc", ".pdf").Replace(".DOC", ".pdf").Replace(".rtf", ".pdf").Replace(".RTF", ".pdf");
                if (!File.Exists(sFileName))
                {
                    //pdf file not exists
                    result.ErrorCvs.Add(new BulkPrintErrorCvs
                    {
                        Error = "Pdf file does not exists. " + sFileName,
                        ContactId = docEntry.ContactId,
                        ContactName = new Contacts().GetCandidateName(docEntry.ContactId),
                        Document = docEntry.Doc
                    });
                    continue;
                }

                // Create pdf reader
                var reader = new PdfReader(sFileName);
                if (!reader.IsOpenedWithFullPermissions)
                {
                    //pdf file does not have permission
                    result.ErrorCvs.Add(new BulkPrintErrorCvs
                    {
                        Error = "Do not have enough permissions to read the file",
                        ContactId = docEntry.ContactId,
                        ContactName = new Contacts().GetCandidateName(docEntry.ContactId),
                        Document = docEntry.Doc
                    });
                    continue;
                }

                var numberOfPages = reader.NumberOfPages;

                // Iterate through all pages
                for (var currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                {
                    // Determine page size for the current page
                    document.SetPageSize(reader.GetPageSizeWithRotation(currentPageIndex));
                    // Create page
                    document.NewPage();
                    var importedPage = writer.GetImportedPage(reader, currentPageIndex);
                    // Determine page orientation
                    var pageOrientation = reader.GetPageRotation(currentPageIndex);
                    switch (pageOrientation)
                    {
                        case 90:
                            content.AddTemplate(importedPage, 0, -1, 1, 0, 0, reader.GetPageSizeWithRotation(currentPageIndex).Height);
                            break;
                        case 270:
                            content.AddTemplate(importedPage, 0, 1, -1, 0, reader.GetPageSizeWithRotation(currentPageIndex).Width, 0);
                            break;
                        default:
                            content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
                            break;
                    }
                }
            }
            document.Close();
        }
예제 #7
0
        public void NewBillPDF(String BillNO)
        {
            DAL.BillLayoutMaster Bill = null;
            IEnumerable<DAL.BillConsumption> Consumption = null;
            IEnumerable<DAL.BillFixchargesList> Fixcharges = null;
            IEnumerable<DAL.BiLLVatChargeList> Vatcharges = null;
            Bill = BAL.BillModel.GetBillHeader(BillNO);
            Consumption = BAL.BillModel.BillConsumptionRecordList(BillNO);
            Fixcharges = BAL.BillModel.BillFixedChargeConsumptionRecordList(BillNO);
            Vatcharges = BAL.BillModel.BillVarChargedList(BillNO);
            //------------------------------------------PDF download -----------------------------------------------------------------
            MemoryStream workStream = new MemoryStream();
            var document = new Document(PageSize.A4,10,10,10,10);
            //  var document = new Document();
            String PDFName = BillNO + ".pdf";

            // var filePath = Path.Combine(Server.MapPath("~/PdfContent/Bill"), PDFName);
            //  var output = new MemoryStream();
               // PdfWriter.GetInstance(document, workStream).CloseStream = false;
            //  PdfWriter.GetInstance(document, System.Web.HttpContext.Current.Response.OutputStream);

            //  var output = new FileStream(filePath, FileMode.Create);
            //var writer = PdfWriter.GetInstance(document, output);

            iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, workStream);

            writer.PageEvent = new HeaderFooter(BillNO);

            try
            {

                document.Open();

                String contents = System.IO.File.ReadAllText(Server.MapPath("~/HTMLTemplate/BillTemplate.htm"));

                //---------------------------------style -------------------------------------------
                StyleSheet styles = new StyleSheet();
                // styles.LoadTagStyle(HtmlTags.TABLE, HtmlTags.COLOR, "left");
                styles.LoadStyle("maintable", "color", "#ff0000");
                styles.LoadStyle(HtmlTags.TABLE, HtmlTags.ALIGN, "center");
             //   styles.LoadTagStyle("#headerdiv", "padding-left", "50px");

                styles.LoadStyle("headerdiv", "align", "center");
                styles.LoadStyle("headerdiv", "color", "#ff0000");
                //--------------------------------End -style -------------------------------------------

                String clientLogo = String.Empty;
                // Replace the placeholders with the user-specified text
                //if (!(String.IsNullOrEmpty(Bill.CompanyLogo)) && (Bill.CompanyLogo != ""))
                //{

                //    clientLogo = "<img border='0' src='" + Server.MapPath("~/UserPicture/" + Bill.CompanyLogo) + "' width='190' height='46'>";
                //}
                //else
                //{
                //    clientLogo = "<img border='0' src='" + Server.MapPath("~/Images/logo.png") + "' width='190' height='46'>";
                //}
                contents = contents.Replace("[ClientImage]", clientLogo);
                contents = contents.Replace("[ConsumerName]", Bill.ConsumerName.Trim());
               // contents = contents.Replace("[PropertyNO]", Bill.PropertyNo.Trim());
                contents = contents.Replace("[ConsumerAddress]", Bill.ConsumerAddress);
                if (Bill.ConsumerAddress2 != null)
                {
                    contents = contents.Replace("[ConsumerAddress2]", "<br/>" + Bill.ConsumerAddress2);
                }
                else
                {
                    contents = contents.Replace("[ConsumerAddress2]", " ");
                }
                contents = contents.Replace("[ConsumerCity]", Bill.ConsumerCity);
                contents = contents.Replace("[ConsumerCountry]", Bill.ConsumerCounty);
                contents = contents.Replace("[ConsumerZipCode]", Bill.ConsumerZipCode);
                contents = contents.Replace("[ClientName]", Bill.Client);
                if (Bill.FixedBillNotice == "Yes")
                {
                    contents = contents.Replace("[FixedBillNote]", Bill.FixedBillNote);
                }
                else
                {
                    contents = contents.Replace("[FixedBillNote]", "");
                }
                contents = contents.Replace("[PropertyAddress]", Bill.PropertyAddress);
                contents = contents.Replace("[PaymentDate]", Bill.paymentDate);
               // contents = contents.Replace("[GrossAmount]", Bill.GrossAmount != null ? Bill.GrossAmount.ToString() : "");
                contents = contents.Replace("[BillFromDate]", Bill.BillFromDate);
                contents = contents.Replace("[BillToDate]", Bill.BillToDate);
                contents = contents.Replace("[previousBalance]", Bill.previousBalance != null ? Bill.previousBalance.ToString() : "");
                contents = contents.Replace("[EngergyList]", "");
                contents = contents.Replace("[NoofDays]", Bill.NoofDays);
                contents = contents.Replace("[Othercharges]", Bill.Othercharges.ToString());
                contents = contents.Replace("[NetAmount]", Bill.NetAmount != null ? Bill.NetAmount.ToString() : "");
                contents = contents.Replace("[VATNumber]", Bill.VATNumber);
                contents = contents.Replace("[VatAmount]", Bill.VatAmount != null ?    Bill.VatAmount.ToString() : "");
                contents = contents.Replace("[GrossAmount]", Bill.GrossAmount != null ? Bill.GrossAmount.ToString() : "");
               // contents = contents.Replace("[paymentReceived]", Bill.paymentReceived != null ? Bill.paymentReceived.ToString() : "");

                contents = contents.Replace("[paymentReceived]", Bill.PaybleAmount != null ? Bill.PaybleAmount.ToString() : "");

              contents = contents.Replace("[DirectDebitAmount]", Bill.DirectDebitAmount != null ? Bill.DirectDebitAmount.ToString() : "");

                if(Bill.DirectDebitType ==1)
                {
                    contents = contents.Replace("[DirectDebitDate]", Bill.DirectDebitDate != null ? Bill.DirectDebitDate : "");
                }
                else
                {
                    contents = contents.Replace("[DirectDebitDate]", Bill.paymentDate != null ? Bill.paymentDate : "");
                }

                contents = contents.Replace("[NewBalance]", Bill.NewBalance != null ? Convert.ToString(Bill.previousBalance + Bill.GrossAmount) : "");
                contents = contents.Replace("[Client]", Bill.Client);
                contents = contents.Replace("[ClientAddress]", Bill.ClientAddress);
                if (Bill.ClientAddress2 != null)
                {
                    contents = contents.Replace("[ClientAddress2]", "<br/>" + Bill.ClientAddress2);
                }
                else { contents = contents.Replace("[ClientAddress2]", ""); }

                contents = contents.Replace("[paymentDate]", Bill.paymentDate);
                contents = contents.Replace("[ClientCity]", Bill.ClientCity);
                contents = contents.Replace("[ClientCounty]", Bill.ClientCounty);
                contents = contents.Replace("[ClientZipCode]", Bill.ClientZipCode);
                contents = contents.Replace("[CompRegistrationNo]", Bill.CompRegistrationNo);
                contents = contents.Replace("[BillDate]", Bill.BillDate);
                contents = contents.Replace("[BillDate]", Bill.BillDate);
                contents = contents.Replace("[BillID]", Bill.BillID);
                contents = contents.Replace("[BillNO]", Bill.BillNO);
                contents = contents.Replace("[AccountNo]", Bill.AccountNo);
                contents = contents.Replace("[TemplateTelephone]", Bill.TemplateTelephone);
                contents = contents.Replace("[TemplateEmail]", Bill.TemplateEmail);
                contents = contents.Replace("[OpeningHour]", Bill.OpeningHour);
                contents = contents.Replace("[ClosingHour]", Bill.ClosingHour);
                contents = contents.Replace("[CurrentTariff]", Bill.CurrentTariff);
                contents = contents.Replace("[PaymentDueDate]", Bill.PaymentDueDate);
                contents = contents.Replace("[TemplateAddress]", Bill.TemplateAddress);
                contents = contents.Replace("[TemplateCity]", Bill.TemplateCity);
                contents = contents.Replace("[TemplateCounty]", Bill.TemplateCounty);
                contents = contents.Replace("[TemplateZipcode]", Bill.TemplateZipcode);
                contents = contents.Replace("[Fixedcharges]", Bill.Fixedcharges.ToString());
                //-------------------EnergyList----------------------

                StringBuilder Sbenergy = new StringBuilder();
                StringBuilder SbenergyList = new StringBuilder();
                StringBuilder PaymentList = new StringBuilder();
                StringBuilder Fixedcharge = new StringBuilder();
                StringBuilder Varcharge = new StringBuilder();
                foreach (var item in Consumption)
                {
                    Sbenergy.Append("<tr >");
                    Sbenergy.Append("<td>" + item.Engergy + "</td>");
                    Sbenergy.Append("<td>&nbsp;</td>");
                    Sbenergy.Append("<td align='right'>£" + item.TotalAmount + "</td></tr>");

                }

                foreach (var item in Fixcharges)
                {
                    Fixedcharge.Append("<tr>");
                    Fixedcharge.Append("<td>" + item.ChargeName + "</td>");
                    Fixedcharge.Append("<td align='center' >" + item.DailyCharge.ToString() + "</td>");
                    Fixedcharge.Append("<td align='center' >" + item.VatRate.ToString() + "</td></tr>");
                }

                foreach (var item in Vatcharges)
                {
                    Varcharge.Append("<tr>");
                    Varcharge.Append("<td> VAT " + item.VatRate + " %</td>");
                    Varcharge.Append("<td> </td>");
                    Varcharge.Append("<td align='right'> &pound;" + item.VatAmount.ToString() + "</td></tr>");
                }

                foreach (var item in Consumption)
                {
                    SbenergyList.Append("<tr>");
                    SbenergyList.Append("<td align='center'>" + item.Engergy + "</td>");
                    SbenergyList.Append("<td align='center'>" + item.DeviceID + "</td>");
                    SbenergyList.Append("<td align='center'>" + item.UnitCode + "</td>");
                    SbenergyList.Append("<td align='center'>" + item.StartMeterReading + "</td>");
                    SbenergyList.Append("<td align='center'>" + item.EndMeterReading + "</td>");
                    SbenergyList.Append("<td align='center'>" + item.DailyConsumption + "</td>");
                    SbenergyList.Append("<td align='center'>" + item.TariffRate + "</td>");
                    SbenergyList.Append("<td align='center'>" + item.TariffVAT + "</td>");
                    SbenergyList.Append("</tr>");

                }

                //--------------------------------------------------------------------------------------

                contents = contents.Replace("[EngergyRecordList]", Sbenergy.ToString());
                contents = contents.Replace("[BillConsumption]", SbenergyList.ToString());
                contents = contents.Replace("[FixedCharged]", Fixedcharge.ToString());
                contents = contents.Replace("[VatChargeList]", Varcharge.ToString());

                String SmilyImage = "<img src='" + Server.MapPath("~/Images/smily.jpg") + "' width='14' height='12' alt=' '>";
                contents = contents.Replace("[SmilyImage]", SmilyImage);

                if (Bill.DirectDebit.Trim() == "1")
                {
                   // String DirectDebitImg = "<img src='" + Server.MapPath("~/Images/direct_debit_pdf.png") + "'  height='30' align='center'  alt=' '>  ";
                    PaymentList.Append("<td align='center'  valign='top' ><table><tr><td align='center'  valign='top'> <img src='" + Server.MapPath("~/Images/img1.jpg") + "'  height='50' align='center'  alt=' '></td> </tr><tr><td align='center' >Please call us on " + Bill.TemplateTelephone + "  to set up or amend your fixed or variable Direct Debit </td></tr></table></td>");
                }
                if (Bill.PayPoint == "1")
                {

                    PaymentList.Append("<td  valign='top'  style='font-size:10px; text-align:center; padding:10px;'>");
                    String PayPointImg = "<img src='" + Server.MapPath("~/Images/pay_point_pdf.png") + "' height='30' alt=' '>";
                    PaymentList.Append(PayPointImg);
                    PaymentList.Append("<div style='clear:both'></div>");
                    PaymentList.Append(" Pay by Cash at any PayPoint outlet using your payment card</td>");
                }

                if (Bill.PayZone == "1")
                {

                    PaymentList.Append("<td  valign='top' style='font-size:10px; text-align:center; padding:10px;'>");
                    String PayZoneImg = "<img src='" + Server.MapPath("~/Images/pay_zone_pdf.png") + "'height='30'  alt=' '>";
                    PaymentList.Append(PayZoneImg);
                    PaymentList.Append("<div style='clear:both'></div>");
                    PaymentList.Append(" Pay by Cash at any PayZone outlet using your payment card</td>");
                }

                if (Bill.PostOffice == "1")
                {

                    PaymentList.Append("<td  valign='top' style='font-size:10px; text-align:center; padding:10px;'>");
                    String PostOfficeImg = "<img src='" + Server.MapPath("~/Images/payment_card_pdf.png") + "' height='30' alt=' '>";
                    PaymentList.Append(PostOfficeImg);
                    PaymentList.Append("<div style='clear:both'></div>");
                    PaymentList.Append(" Pay by Cash at any Post Office branch using your payment card</td>");
                }

                if (Bill.BankTransfer == "1")
                {

                    PaymentList.Append("<td  valign='top'>");
                    String BankTransferImg = "<img src='" + Server.MapPath("~/Images/bank_transfer_pdf.png") + "' height='30'  alt=' '>";
                    PaymentList.Append(BankTransferImg);
                    PaymentList.Append("<div style='clear:both'></div>");
                    PaymentList.Append("Our account details for Bank Transfers:     ");
                    if (Bill.SortCode != null)
                    {
                        PaymentList.Append("Sort Code " + Bill.SortCode);
                    }

                    if (Bill.ClientBankAccountNo != null)
                    {
                        PaymentList.Append("  Account Number   ");
                        PaymentList.Append(Bill.ClientBankAccountNo);
                    }
                    PaymentList.Append("</td>");
                }

                if (Bill.TelephonePay == "1")
                {

                    PaymentList.Append("<td  valign='top' align='center' style='font-size:10px; text-align:center; padding:10px;'>");
                    String telephonepaypngImg = "<img src='" + Server.MapPath("~/Images/telephone_pay_pdf.png") + "' height='30'  alt=' '>";
                    PaymentList.Append(telephonepaypngImg);
                    PaymentList.Append("<div style='clear:both'></div>");
                    PaymentList.Append("Pay by Credit or Debit Card by calling   ");
                    PaymentList.Append(Bill.TemplateTelephone);
                    PaymentList.Append("</td>");
                }
                if (Bill.OnlinePay == "1")
                {

                    PaymentList.Append("<td  valign='top' align='center' style='font-size:10px; text-align:center; padding:10px;'>");
                    String OnlinePaypngImg = "<img src='" + Server.MapPath("~/Images/online_pay_pdf.png") + "' height='30' alt=' '>";
                    PaymentList.Append(OnlinePaypngImg);
                    PaymentList.Append("<div style='clear:both'></div>");
                    PaymentList.Append("Pay by Credit or Debit Card. Visit your online account for App and SMS details");
                    PaymentList.Append("</td>");
                }

                if (Bill.OnlineNTelephonePay == "1")
                {

                    PaymentList.Append("<td  valign='top' style='font-size:10px; text-align:center; padding:10px;'>");
                    String OnlineNTelephonePayImg = "<img src='" + Server.MapPath("~/Images/telephone_online_pay_pdf.png") + "'  height='30' alt=' '>";
                    PaymentList.Append(OnlineNTelephonePayImg);
                    PaymentList.Append("<div style='clear:both'></div>");
                    PaymentList.Append("Pay by Credit or Debit Card calling    ");
                    PaymentList.Append(Bill.TemplateTelephone);
                    PaymentList.Append("    visit www.mysycous.com</td>");
                }

                contents = contents.Replace("[PaymentOption]", PaymentList.ToString());
                // document.NewPage();
                // Step 4: Parse the HTML string into a collection of elements...
                var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), styles);
                // Enumerate the elements, adding each one to the Document...
                foreach (var htmlElement in parsedHtmlElements)
                {
                    document.Add(htmlElement as IElement);
                }

                // writer.CloseStream = false;
                document.Close();
                writer.Close();
                byte[] file = workStream.ToArray();
                MemoryStream output = new MemoryStream();
                output.Write(file, 0, file.Length);
                output.Position = 0;
                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AppendHeader("Content-disposition", "attachment; filename=" + PDFName + ""); // open in a new window
                Response.OutputStream.Write(output.GetBuffer(), 0, output.GetBuffer().Length);
                Response.Flush();

            }
            catch (Exception ex)
            {
                //workStream.Dispose();
                //output.Dispose();
                document.Dispose();
            }
        }
예제 #8
0
        public ActionResult GenerateEmail(String BillNO)
        {
            if (Session["Login"] != null)
            {
                LoginSession loginsession = (LoginSession)Session["Login"];
                String actionName = this.ControllerContext.RouteData.Values["action"].ToString();
                String controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
                ViewBag.Menu = BAL.Common.GetActiveMenu(controllerName, BAL.Common.LayoutType(loginsession.UserType));

                try
                {

                    if (BillNO != null)
                    {
                        String DecBill = BAL.Security.URLDecrypt(BillNO);

                        DAL.BillLayoutMaster Bill = null;
                        IEnumerable<DAL.BillConsumption> Consumption = null;
                        IEnumerable<DAL.BillFixchargesList> Fixcharges = null;
                        IEnumerable<DAL.BiLLVatChargeList> Vatcharges = null;
                        Bill = BAL.BillModel.GetBillHeader(BillNO);
                        Consumption = BAL.BillModel.BillConsumptionRecordList(BillNO);
                        Fixcharges = BAL.BillModel.BillFixedChargeConsumptionRecordList(BillNO);
                        Vatcharges = BAL.BillModel.BillVarChargedList(BillNO);
                      //  ------------------------------------------------------pdf-----------------------------------

                       var document = new Document(PageSize.A4,10, 10, 10, 10);
                      //  var document = new Document();
                        String PDFName = DecBill + ".pdf";
                        var filePath = Path.Combine(Server.MapPath("~/PdfContent/Bill"), PDFName);
                        //  var output = new MemoryStream();
                        var output = new FileStream(filePath, FileMode.Create);
                        var writer = PdfWriter.GetInstance(document, output);
                        try
                        {
                            document.Open();
                            String contents = System.IO.File.ReadAllText(Server.MapPath("~/HTMLTemplate/BillTemplate.htm"));

                            //---------------------------------style -------------------------------------------
                           StyleSheet styles = new StyleSheet();
                          // styles.LoadTagStyle(HtmlTags.TABLE, HtmlTags.COLOR, "left");
                           styles.LoadStyle("maintable", "color", "#ff0000");

                            //--------------------------------End -style -------------------------------------------

                           String clientLogo = String.Empty;
                           // Replace the placeholders with the user-specified text
                           if (!(String.IsNullOrEmpty(Bill.CompanyLogo)) && (Bill.CompanyLogo != ""))
                           {

                               clientLogo = "<img border='0' src='" + Server.MapPath("~/UserPicture/" + Bill.CompanyLogo) + "' width='190' height='46'>";
                           }
                           else
                           {
                               clientLogo = "<img border='0' src='" + Server.MapPath("~/Images/logo.png") + "' width='190' height='46'>";
                           }
                           contents = contents.Replace("[ClientImage]", clientLogo);
                           contents = contents.Replace("[ConsumerName]", Bill.ConsumerName.Trim());
                           contents = contents.Replace("[PropertyNO]", Bill.PropertyNo.Trim());
                           contents = contents.Replace("[ConsumerAddress]", Bill.ConsumerAddress);
                           contents = contents.Replace("[ConsumerCity]", Bill.ConsumerCity);
                           contents = contents.Replace("[ConsumerCountry]", Bill.ConsumerCounty);
                           contents = contents.Replace("[ConsumerZipCode]", Bill.ConsumerZipCode);
                           contents = contents.Replace("[ClientName]", Bill.Client);
                           if (Bill.FixedBillNotice == "Yes")
                           {
                               contents = contents.Replace("[FixedBillNote]", Bill.FixedBillNote);
                           }
                           else
                           {
                               contents = contents.Replace("[FixedBillNote]", "");
                           }
                           contents = contents.Replace("[PropertyAddress]", Bill.PropertyAddress);
                           contents = contents.Replace("[PaymentDate]", Bill.paymentDate);
                           contents = contents.Replace("[GrossAmount]", Bill.GrossAmount != null ? Bill.GrossAmount.ToString() : "");
                           contents = contents.Replace("[BillFromDate]", Bill.BillFromDate);
                           contents = contents.Replace("[BillToDate]", Bill.BillToDate);
                           contents = contents.Replace("[previousBalance]", Bill.previousBalance != null ? Bill.previousBalance.ToString() : "");
                           contents = contents.Replace("[EngergyList]", "");
                           contents = contents.Replace("[NoofDays]", Bill.NoofDays);
                           contents = contents.Replace("[Othercharges]", Bill.Othercharges.ToString());
                           contents = contents.Replace("[NetAmount]", Bill.NetAmount != null ? Bill.NetAmount.ToString() : "");
                           contents = contents.Replace("[VATNumber]", Bill.VATNumber);
                           contents = contents.Replace("[VatAmount]", Bill.VatAmount != null ? Bill.VatAmount.ToString() : "");
                           contents = contents.Replace("[GrossAmount]", Bill.GrossAmount != null ? Bill.GrossAmount.ToString() : "");
                           contents = contents.Replace("[paymentReceived]", Bill.paymentReceived != null ? Bill.paymentReceived.ToString() : "");
                           contents = contents.Replace("[NewBalance]", Bill.NewBalance != null ? Bill.NewBalance.ToString() : "");
                           contents = contents.Replace("[Client]", Bill.Client);
                           contents = contents.Replace("[ClientAddress]", Bill.ClientAddress);
                           //contents = contents.Replace("[ClientAddress2]", Bill.ClientAddress2);
                           contents = contents.Replace("[paymentDate]", Bill.paymentDate);
                           contents = contents.Replace("[ClientCity]", Bill.ClientCity);
                           contents = contents.Replace("[ClientCounty]", Bill.ClientCounty);
                           contents = contents.Replace("[ClientZipCode]", Bill.ClientZipCode);
                           contents = contents.Replace("[CompRegistrationNo]", Bill.CompRegistrationNo);
                           contents = contents.Replace("[BillDate]", Bill.BillDate);
                           contents = contents.Replace("[BillDate]", Bill.BillDate);
                           contents = contents.Replace("[BillID]", Bill.BillID);
                           contents = contents.Replace("[BillNO]", Bill.BillNO);
                           contents = contents.Replace("[AccountNo]", Bill.AccountNo);
                           contents = contents.Replace("[TemplateTelephone]", Bill.TemplateTelephone);
                           contents = contents.Replace("[TemplateEmail]", Bill.TemplateEmail);
                           contents = contents.Replace("[OpeningHour]", Bill.OpeningHour);
                           contents = contents.Replace("[ClosingHour]", Bill.ClosingHour);
                           contents = contents.Replace("[CurrentTariff]", Bill.CurrentTariff);
                           contents = contents.Replace("[PaymentDueDate]", Bill.PaymentDueDate);
                           contents = contents.Replace("[TemplateAddress]", Bill.TemplateAddress);
                           contents = contents.Replace("[TemplateCity]", Bill.TemplateCity);
                           contents = contents.Replace("[TemplateCounty]", Bill.TemplateCounty);
                           contents = contents.Replace("[TemplateZipcode]", Bill.TemplateZipcode);
                           //-------------------EnergyList----------------------

                           StringBuilder Sbenergy = new StringBuilder();
                           StringBuilder SbenergyList = new StringBuilder();
                           StringBuilder PaymentList = new StringBuilder();
                           StringBuilder Fixedcharge = new StringBuilder();
                           StringBuilder Varcharge = new StringBuilder();
                           foreach (var item in Consumption)
                           {
                               Sbenergy.Append("<tr>");
                               Sbenergy.Append("<td>" + item.Engergy + "</td>");
                               Sbenergy.Append("<td>&nbsp;</td>");
                               Sbenergy.Append("<td align='right'>£" + item.TotalAmount + "</td></tr>");
                           }

                           foreach (var item in Fixcharges)
                           {
                               Fixedcharge.Append("<tr>");
                               Fixedcharge.Append("<td>" + item.ChargeName + "</td>");

                               Fixedcharge.Append("<td >" + item.DailyCharge.ToString() + "</td></tr>");
                           }

                           foreach (var item in Vatcharges)
                           {
                               Varcharge.Append("<tr>");
                               Varcharge.Append("<td> VAT " + item.VatRate + " %</td>");
                               Varcharge.Append("<td> </td>");
                               Varcharge.Append("<td align='right'> &pound;" + item.VatAmount.ToString() + "</td></tr>");
                           }

                           foreach (var item in Consumption)
                           {
                               SbenergyList.Append("<tr>");
                               SbenergyList.Append("<td align='center'>" + item.Engergy + "</td>");
                               SbenergyList.Append("<td align='center'>" + item.DeviceID + "</td>");
                               SbenergyList.Append("<td align='center'>" + item.UnitCode + "</td>");
                               SbenergyList.Append("<td align='center'>" + item.StartMeterReading + "</td>");
                               SbenergyList.Append("<td align='center'>" + item.EndMeterReading + "</td>");
                               SbenergyList.Append("<td align='center'>" + item.DailyConsumption + "</td>");
                               SbenergyList.Append("<td align='center'>" + item.TariffRate + "</td>");
                               SbenergyList.Append("</tr>");

                           }

                           //--------------------------------------------------------------------------------------

                           contents = contents.Replace("[EngergyRecordList]", Sbenergy.ToString());
                           contents = contents.Replace("[BillConsumption]", SbenergyList.ToString());
                           contents = contents.Replace("[FixedCharged]", Fixedcharge.ToString());
                           contents = contents.Replace("[VatChargeList]", Varcharge.ToString());

                           String SmilyImage = "<img src='" + Server.MapPath("~/Images/smily.jpg") + "' width='14' height='12' alt=' '>";
                           contents = contents.Replace("[SmilyImage]", SmilyImage);

                           if (Bill.DirectDebit.Trim() == "1")
                           {
                               PaymentList.Append("<td align='center'  valign='top' ><div id='headerdiv'> ");
                               String DirectDebitImg = "<img src='" + Server.MapPath("~/Images/direct_debit_pdf.png") + "'  height='30'  alt=' '> </div>";
                               PaymentList.Append(DirectDebitImg);
                               PaymentList.Append("<div style='clear:both'>Please call us on </div>");
                               PaymentList.Append(Bill.TemplateTelephone);
                               PaymentList.Append("  to set up your Direct Debit  </td>");
                           }
                           if (Bill.PayPoint == "1")
                           {

                               PaymentList.Append("<td  valign='top'  style='font-size:10px; text-align:center; padding:10px;'>");
                               String PayPointImg = "<img src='" + Server.MapPath("~/Images/pay_point_pdf.png") + "' height='30' alt=' '>";
                               PaymentList.Append(PayPointImg);
                               PaymentList.Append("<div style='clear:both'></div>");
                               PaymentList.Append(" Pay by Cash at any PayPoint outlet using your payment card</td>");
                           }

                           if (Bill.PayZone == "1")
                           {

                               PaymentList.Append("<td  valign='top' style='font-size:10px; text-align:center; padding:10px;'>");
                               String PayZoneImg = "<img src='" + Server.MapPath("~/Images/pay_zone_pdf.png") + "'height='30'  alt=' '>";
                               PaymentList.Append(PayZoneImg);
                               PaymentList.Append("<div style='clear:both'></div>");
                               PaymentList.Append(" Pay by Cash at any PayZone outlet using your payment card</td>");
                           }

                           if (Bill.PostOffice == "1")
                           {

                               PaymentList.Append("<td  valign='top' style='font-size:10px; text-align:center; padding:10px;'>");
                               String PostOfficeImg = "<img src='" + Server.MapPath("~/Images/payment_card_pdf.png") + "' height='30' alt=' '>";
                               PaymentList.Append(PostOfficeImg);
                               PaymentList.Append("<div style='clear:both'></div>");
                               PaymentList.Append(" Pay by Cash at any Post Office branch using your payment card</td>");
                           }

                           if (Bill.BankTransfer == "1")
                           {

                               PaymentList.Append("<td  valign='top'>");
                               String BankTransferImg = "<img src='" + Server.MapPath("~/Images/bank_transfer_pdf.png") + "' height='30'  alt=' '>";
                               PaymentList.Append(BankTransferImg);
                               PaymentList.Append("<div style='clear:both'></div>");
                               PaymentList.Append("Our account details for Bank Transfers:     ");
                               if (Bill.SortCode != null)
                               {
                                   PaymentList.Append("Sort Code " + Bill.SortCode);
                               }

                               if (Bill.ClientBankAccountNo != null)
                               {
                                   PaymentList.Append("  Account Number   ");
                                   PaymentList.Append(Bill.ClientBankAccountNo);
                               }
                               PaymentList.Append("</td>");
                           }

                           if (Bill.TelephonePay == "1")
                           {

                               PaymentList.Append("<td  valign='top' align='center' style='font-size:10px; text-align:center; padding:10px;'>");
                               String telephonepaypngImg = "<img src='" + Server.MapPath("~/Images/telephone_pay_pdf.png") + "' height='30'  alt=' '>";
                               PaymentList.Append(telephonepaypngImg);
                               PaymentList.Append("<div style='clear:both'></div>");
                               PaymentList.Append("Pay by Credit or Debit Card by calling   ");
                               PaymentList.Append(Bill.TemplateTelephone);
                               PaymentList.Append("</td>");
                           }
                           if (Bill.OnlinePay == "1")
                           {

                               PaymentList.Append("<td  valign='top' align='center' style='font-size:10px; text-align:center; padding:10px;'>");
                               String OnlinePaypngImg = "<img src='" + Server.MapPath("~/Images/online_pay_pdf.png") + "' height='30' alt=' '>";
                               PaymentList.Append(OnlinePaypngImg);
                               PaymentList.Append("<div style='clear:both'></div>");
                               PaymentList.Append("Pay by Credit or Debit Card. Visit your online account for App and SMS details");
                               PaymentList.Append("</td>");
                           }

                           if (Bill.OnlineNTelephonePay == "1")
                           {

                               PaymentList.Append("<td  valign='top' style='font-size:10px; text-align:center; padding:10px;'>");
                               String OnlineNTelephonePayImg = "<img src='" + Server.MapPath("~/Images/telephone_online_pay_pdf.png") + "'  height='30' alt=' '>";
                               PaymentList.Append(OnlineNTelephonePayImg);
                               PaymentList.Append("<div style='clear:both'></div>");
                               PaymentList.Append("Pay by Credit or Debit Card calling    ");
                               PaymentList.Append(Bill.TemplateTelephone);
                               PaymentList.Append("    visit www.mysycous.com</td>");
                           }

                              contents = contents.Replace("[PaymentOption]", PaymentList.ToString());
                           // document.NewPage();
                            // Step 4: Parse the HTML string into a collection of elements...
                            var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), styles);
                            // Enumerate the elements, adding each one to the Document...
                            foreach (var htmlElement in parsedHtmlElements)
                            {
                                document.Add(htmlElement as IElement);
                            }

                            writer.CloseStream = false;
                            document.Close();
                            output.Dispose();
                            BAL.BillModel.BillSendByMail(DecBill);
                        }
                        catch (Exception ex)
                        {
                            output.Dispose();
                            document.Dispose();
                            return Content(ex.Message.ToString());
                        }
                     //-------------------------------------------------------------------------------
                        return RedirectToAction("Index", "Bill");
                    }
                    else
                    { return Content("Select View Of Bill "); }
                }
                catch (Exception ex)
                {
                    return Content("ERROR :" + ex.Message);
                }

            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
    protected void CreartePdf()
    {
        string filname = Server.MapPath("../Admin/InvoicePdf/" + lblInvoiceNoMail.Text + ".pdf");

        if (System.IO.File.Exists(filname))
        {
            System.IO.File.Delete(filname);
        }

        iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
        styles.LoadStyle("wdth20", "width", "30");
        styles.LoadStyle("wdth80", "width", "80");
        styles.LoadStyle("wdth50", "width", "50");
        styles.LoadStyle("wdth140", "width", "140");
        styles.LoadStyle("wdth100", "width", "100");
        styles.LoadStyle("wdth200", "width", "200");
        styles.LoadStyle("wdth400", "width", "400");
        styles.LoadStyle("wdth51", "width", "51");
        styles.LoadStyle("wdth40", "width", "40");
        styles.LoadStyle("wdth60", "width", "60");
        styles.LoadStyle("wdth65", "width", "65");
        styles.LoadStyle("wdth55", "width", "55");

        styles.LoadStyle("hght200", "height", "200");
        styles.LoadStyle("border-left", "border-left-width", "1");
        styles.LoadStyle("borderright", "BorderWidthRight ", "1f");


        //for header
        StringWriter   swheader = new StringWriter();
        HtmlTextWriter hwheader = new HtmlTextWriter(swheader);

        pnlHeader.RenderControl(hwheader);
        StringReader srheader = new StringReader(swheader.ToString());

        PdfPCell cellLeft = new PdfPCell();

        StyleSheet style = new StyleSheet();

        style.LoadStyle("wdth20", "width", "30");
        style.LoadStyle("wdth40", "width", "40");
        style.LoadStyle("wdth60", "width", "60");
        style.LoadStyle("wdth80", "width", "80");
        style.LoadStyle("wdth81", "width", "81");
        style.LoadStyle("wdth100", "width", "100");
        style.LoadStyle("wdth50", "width", "50");
        style.LoadStyle("wdth51", "width", "51");
        style.LoadStyle("wdth140", "width", "140");
        style.LoadStyle("wdth600", "width", "552");
        style.LoadStyle("wdth200", "width", "220");
        style.LoadStyle("wdth400", "width", "331");

        style.LoadStyle("wdth550", "width", "551");
        style.LoadStyle("wdth541", "width", "551");
        style.LoadStyle("wdth65", "width", "65");
        style.LoadStyle("wdth55", "width", "55");

        List <IElement> objects = HTMLWorker.ParseToList(new StringReader(swheader.ToString()), style);  //This transforms your HTML to a list of PDF compatible objects

        for (int k = 0; k < objects.Count; ++k)
        {
            cellLeft.AddElement((IElement)objects[k]);

            //if (k == 1)
            //{
            //    cellLeft.FixedHeight = 500f;
            //    cellLeft.GetMaxHeight();//Add these objects to cell one by one
            //}
        }
        //header ends

        //for content

        StringWriter   sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        pnlMail.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());


        float    topmrg = cellLeft.GetMaxHeight() + 22;
        Document pdfDoc = new Document(PageSize.A4, 22, 22, topmrg, 40);

        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

        htmlparser.SetStyleSheet(styles);
        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(filname, FileMode.Create));

        pdfDoc.Open();

        writer.PageEvent = new HeaderFooter1(cellLeft);
        htmlparser.Parse(sr);
        pdfDoc.Close();
        pdfDoc.Dispose();
        sr.Close();
        sr.Dispose();
        srheader.Close();
        sr.Dispose();
        writer.Close();
        writer.Dispose();


        Mail(filname);
    }
        /// <summary> Gets the CSS classes. </summary>
        /// <returns> The CSS classes. </returns>
        public static StyleSheet GetStyleSheet()
        {
            string pdfStyleSheet = OutputSettings.Instance.StyleSheet;

            if (string.IsNullOrWhiteSpace(pdfStyleSheet))
            {
                return null;
            }

            StylesheetParser ssp = new StylesheetParser();
            string css = File.ReadAllText(HttpContext.Current.Server.MapPath(pdfStyleSheet));
            Stylesheet stylesheet = ssp.Parse(css);

            StyleSheet styles = new StyleSheet();

            foreach (RuleSet ruleSet in stylesheet.RuleSets)
            {
                Dictionary<string, string> attributes =
                    ruleSet.Declarations.ToDictionary(
                        declaration => declaration.Name,
                        declaration => declaration.Expression.ToString());

                foreach (Selector selector in ruleSet.Selectors)
                {
                    if (selector.ToString().StartsWith(".", StringComparison.OrdinalIgnoreCase))
                    {
                        styles.LoadStyle(selector.ToString(), attributes);
                    }
                    else
                    {
                        styles.LoadTagStyle(selector.ToString(), attributes);
                    }
                }
            }

            return styles;
        }
예제 #11
-1
// ---------------------------------------------------------------------------    
    public override void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        HtmlMovies2 movies = new HtmlMovies2();
        // create a StyleSheet
        StyleSheet styles = new StyleSheet();
        styles.LoadTagStyle("ul", "indent", "10");
        styles.LoadTagStyle("li", "leading", "14");
        styles.LoadStyle("country", "i", "");
        styles.LoadStyle("country", "color", "#008080");
        styles.LoadStyle("director", "b", "");
        styles.LoadStyle("director", "color", "midnightblue");
        movies.SetStyles(styles);
        // create extra properties
        Dictionary<String,Object> map = new Dictionary<String, Object>();
        map.Add(HTMLWorker.FONT_PROVIDER, new MyFontFactory());
        map.Add(HTMLWorker.IMG_PROVIDER, new MyImageFactory());
        movies.SetProviders(map);
        // creates HTML and PDF (reusing a method from the super class)
        byte[] pdf = movies.CreateHtmlAndPdf(stream);
        zip.AddEntry(HTML, movies.Html.ToString());
        zip.AddEntry(RESULT1, pdf);
        zip.AddEntry(RESULT2, movies.CreatePdf());
        // add the images so the static html file works
        foreach (Movie movie in PojoFactory.GetMovies()) {
          zip.AddFile(
            Path.Combine(
              Utility.ResourcePosters, 
              string.Format("{0}.jpg", movie.Imdb)
            ), 
            ""
          );
        }
        zip.Save(stream);             
      }
    }