LoadTagStyle() public method

public LoadTagStyle ( String tag, Hashtable props ) : void
tag String
props System.Collections.Hashtable
return void
        public byte[] Render(string htmlText, string pageTitle)
        {
            byte[] renderedBuffer;

            // BaseFont baseFont = BaseFont.CreateFont(@"D:\ProfholodDevelop\ProfholodSite\ProfholodSite\fonts\arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            //iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);
            string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.ttf");

            //Register the font with iTextSharp
            iTextSharp.text.FontFactory.Register(arialuniTff);

            iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet();
            //Set the default body font to our registered font's internal name
            ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial");
            //Set the default encoding to support Unicode characters
            ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);

            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            using (var outputMemoryStream = new MemoryStream())
            {
                using (var pdfDocument = new Document(PageSize.A4.Rotate(), HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin))
                {
                    PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream);
                    pdfWriter.CloseStream = false;
                    pdfWriter.PageEvent   = new PrintHeaderFooter {
                        Title = pageTitle
                    };

                    pdfDocument.Open();

                    using (var htmlViewReader = new StringReader(htmlText))
                    {
                        using (var htmlWorker = new HTMLWorker(pdfDocument))
                        {
                            htmlWorker.SetStyleSheet(ST);

                            //string HJ = "Привет !!!!!!!!!!!!!!! Привет";
                            //Chunk c1 = new Chunk(HJ,font);
                            // pdfDocument.Add(c1);

                            htmlWorker.Parse(htmlViewReader);
                        }
                    }
                }

                renderedBuffer = new byte[outputMemoryStream.Position];
                outputMemoryStream.Position = 0;
                outputMemoryStream.Read(renderedBuffer, 0, renderedBuffer.Length);
            }

            return(renderedBuffer);
        }
        public byte[] Render(string htmlText, string pageTitle)
        {
            byte[] renderedBuffer;

            using (var outputMemoryStream = new MemoryStream())
            {
                using (var pdfDocument = new Document(PageSize.A4, HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin))
                {
                    string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
                    FontFactory.Register(arialuniTff);

                    PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream);

                    pdfWriter.CloseStream = false;
                    pdfWriter.PageEvent = new PrintHeaderFooter { Title = pageTitle };
                    pdfDocument.Open();

                    using (var htmlViewReader = new StringReader(htmlText))
                    {
                        using (var htmlWorker = new HTMLWorker(pdfDocument))
                        {
                            StyleSheet styleSheet = new StyleSheet();
                            styleSheet.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS");
                            styleSheet.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);
                            htmlWorker.SetStyleSheet(styleSheet);
                            htmlWorker.Parse(htmlViewReader);
                        }
                    }
                }

                renderedBuffer = new byte[outputMemoryStream.Position];
                outputMemoryStream.Position = 0;
                outputMemoryStream.Read(renderedBuffer, 0, renderedBuffer.Length);
            }

            return renderedBuffer;
        }
Example #3
0
        private void createPDF(string html)
        {
            //MemoryStream msOutput = new MemoryStream();
            TextReader reader   = new StringReader(html);// step 1: creation of a document-object
            Document   document = new Document(PageSize.A4, 30, 30, 30, 30);

            Response.ContentType = "Application/pdf";
            // step 2:
            // we create a writer that listens to the document
            // and directs a XML-stream to a file
            PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);//new FileStream("Test.pdf", FileMode.Create));

            // step 3: we create a worker parse the document
            HTMLWorker worker = new HTMLWorker(document);

            // step 4: we open document and start the worker on the document
            document.Open();

            // step 4.1: register a unicode font and assign it an allias
            FontFactory.Register("C:\\Windows\\Fonts\\ARIALUNI.TTF", "arial unicode ms");

            // step 4.2: create a style sheet and set the encoding to Identity-H
            iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet();
            ST.LoadTagStyle("body", "encoding", "Identity-H");

            // step 4.3: assign the style sheet to the html parser
            worker.SetStyleSheet(ST);

            worker.StartDocument();

            // step 5: parse the html into the document
            worker.Parse(reader);

            // step 6: close the document and the worker
            worker.EndDocument();
            worker.Close();
            document.Close();
            Response.End();
        }
Example #4
0
        private void CreatePDFFromHTMLFile(string html, string FileName)
        {
            TextReader reader = new StringReader(html);
            // step 1: creation of a document-object
            Document document = new Document(PageSize.A3, 30, 30, 30, 30);

            // step 2:
            // we create a writer that listens to the document
            // and directs a XML-stream to a file
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(FileName, FileMode.Create));

            // step 3: we create a worker parse the document
            HTMLWorker worker = new HTMLWorker(document);

            // step 4: we open document and start the worker on the document
            document.Open();

            // step 4.1: register a unicode font and assign it an allias
            FontFactory.Register("C:\\Windows\\Fonts\\ARIALUNI.TTF", "arial unicode ms");

            // step 4.2: create a style sheet and set the encoding to Identity-H
            iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet();
            ST.LoadTagStyle("body", "encoding", "Identity-H");

            // step 4.3: assign the style sheet to the html parser
            worker.Style = ST;

            worker.StartDocument();

            // step 5: parse the html into the document
            worker.Parse(reader);

            // step 6: close the document and the worker
            worker.EndDocument();
            worker.Close();
            document.Close();
        }
Example #5
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);
        }
    }
Example #6
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;
        }
        public static void ExportData(System.Data.DataTable dt, string ExportFileName)
        {
            //if (sfd.FilterIndex == 1)
            //{
            //    bool ExcelImport = false;
            //    if (W.Show("Will this file be Imported into MS EXCEL?", "EXCEL", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
            //        ExcelImport = true;

            //    using (StreamWriter sw = new StreamWriter(sfd.FileName))
            //    {
            //        StringBuilder sb = new StringBuilder();
            //        foreach (DataColumn dc in dt.Columns)
            //        {
            //            sb.Append(dc.ColumnName + ",");
            //        }
            //        sw.WriteLine(sb.ToString().Substring(0, sb.ToString().Length - 1));

            //        foreach (DataRow dr in dt.Rows)
            //        {
            //            sb = new StringBuilder();
            //            string rec = "";
            //            foreach (DataColumn dc in dt.Columns)
            //            {
            //                if (ExcelImport)
            //                    rec = @"=" + "\"" + dr[dc.ColumnName].ToString() + "\"";
            //                else
            //                    rec = dr[dc.ColumnName].ToString();

            //                sb.Append(rec + ",");
            //            }

            //            sw.WriteLine(sb.ToString().Substring(0, sb.ToString().Length - 1));
            //        }
            //    }
            //}
            //else if (sfd.FilterIndex == 2)
            //{
            //Document is inbuilt class, available in iTextSharp
            Document      document = new Document(PageSize.A4, 80, 50, 30, 65);
            StringBuilder strData  = new StringBuilder(string.Empty);

            try
            {
                StringWriter sw = new StringWriter();
                sw.WriteLine(Environment.NewLine);
                sw.WriteLine(Environment.NewLine);
                sw.WriteLine(Environment.NewLine);
                sw.WriteLine(Environment.NewLine);
                StreamWriter strWriter = new StreamWriter(ExportFileName, false, Encoding.UTF8);
                //strWriter.Write("<html><head><link href=Style.css rel=stylesheet type=text/css /></head><body>" + htw.InnerWriter.ToString() + "</body></html>");
                #region Write in StreamWriter

                string sError           = string.Empty;
                int    iNoOfColsinaPage = 7;
                int    iRunningColCount = 0;
                strWriter.Write("<HTML><BODY><TABLE>");
                foreach (DataColumn dc in dt.Columns)
                {
                    if (iRunningColCount % iNoOfColsinaPage == 0)
                    {
                        strWriter.Write("<TR>");
                    }
                    strWriter.Write("<TD>&nbsp;" + dc.ColumnName + "&nbsp;</TD>");

                    iRunningColCount++;

                    if (iRunningColCount % iNoOfColsinaPage == 0)
                    {
                        strWriter.Write("</TR>");
                    }
                }

                foreach (DataRow dr in dt.Rows)
                {
                    iRunningColCount = 0;
                    foreach (DataColumn dc in dt.Columns)
                    {
                        if (iRunningColCount % iNoOfColsinaPage == 0)
                        {
                            strWriter.Write("<TR>");
                        }
                        strWriter.Write("<TD>" + dr[dc.ColumnName].ToString() + "&nbsp;</TD>");
                        iRunningColCount++;
                        if (iRunningColCount % iNoOfColsinaPage == 0)
                        {
                            strWriter.Write("</TR>");
                        }
                    }
                }

                strWriter.Write("</TABLE></BODY></HTML>");
                //sb = strWriter.to .Replace("</TD><TR>", "</TD></TR><TR>");

                #endregion
                strWriter.Close();
                strWriter.Dispose();
                iTextSharp.text.html.simpleparser.
                StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
                styles.LoadTagStyle("ol", "leading", "16,0");
                List <IElement> objects;
                styles.LoadTagStyle("li", "face", "garamond");
                styles.LoadTagStyle("span", "size", "8px");
                styles.LoadTagStyle("body", "font-family", "times new roman");
                styles.LoadTagStyle("body", "font-size", "10px");
                StreamReader sr = new StreamReader(ExportFileName, Encoding.Default);
                objects = HTMLWorker.ParseToList(sr, styles);
                sr.Close();
                PdfWriter.GetInstance(document, new FileStream(ExportFileName, FileMode.Create));

                document.Add(new Header("stylesheet", "Style.css"));
                document.Open();
                document.NewPage();
                for (int k = 0; k < objects.Count; k++)
                {
                    document.Add((IElement)objects[k]);
                }
            }
            catch (Exception ex)
            {
                //throw ex;
            }
            finally
            {
                document.Close();
            }
        }
Example #8
0
        public void BillPDF(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);
            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");

                //--------------------------------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();
                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();
            }
        }
Example #9
0
        //12.-Funcion para crear el pdf y guardarlo en el servidor y en la maquina local.
        private void crearPDF()
        {
            try
            {
               
                string temp = System.IO.Path.GetTempPath();

                //For para crear la tabla de descripciones para luego agragarla al pdf
                string tabla = "<table  cellspacing='0' width='100%' border='0' style='font-family:Courier New, Courier, monospace;line-height:6pt;font-size:6px  !important;'>";
                tabla += "<tr><td width='5%'><p align='center'><strong>(1)NUM</strong></p></td><td width='5%'><p align='center'><strong>(2)CLASE</strong></p></td><td><p align='center' width='17%'><strong>(3)QUE SE DICE QUE CONTIENE</strong></p></td><td width='5%'><p align='center'><strong>(4)PESO</strong></p></td><td width='5%'><p align='center'><strong>MTS 3</strong></p></td><td width='10%'><p align='center'><strong>PESO ESTIMADO</strong></p></td></tr>";
                for (int i = 0; i < gridDescripciones.Rows.Count-1; i++)
                {
                    tabla += "<tr>";

                    for (int k = 0; k < gridDescripciones.Columns.Count; k++)
                    {
                       
                        if (gridDescripciones[k, i].Value != null)
                        {

                            if (k == 0)
                            {
                                tabla += "<td width='3%'><p align='center'>" + gridDescripciones[k, i].Value.ToString() + "</p></td>";
                            }
                            if (k == 2)
                            {
                                tabla += "<td width='20%'><p align='center'>" + gridDescripciones[k, i].Value.ToString() + "</p></td>";
                            }

                            if (k == 1)
                            {
                                tabla += "<td width='3%'><p align='center'>" + gridDescripciones[k, i].Value.ToString() + "</p></td>";

                            }
                            if (k == 3)
                            {
                                string peso = gridDescripciones[k, i].Value.ToString();
                                if (peso == "0.00") { peso = ""; }
                                tabla += "<td width='3%'><p align='center'>" + peso + "</p></td>";
                            }
                            if (k == 4)
                            {
                                string peso = gridDescripciones[k, i].Value.ToString();
                                if (peso == "0.00") { peso = ""; }
                                tabla += "<td width='3%'><p align='center'>" + peso + "</p></td>";
                            }
                            if (k == 5)
                            {
                                string peso = gridDescripciones[k, i].Value.ToString();
                                if (peso == "0.00") { peso = ""; }

                                tabla += "<td width='5%'><p align='center'>" + peso + "</p></td>";

                            }
                        }
                    }
                    tabla += "</tr>";

                } tabla += "</table>"+viajFactCP;

               
                //For para crear la tabla de conceptos para luego agragarla al pdf
                string tablaC = "<table  style='font-size:6px' border='0' cellspacing='0' cellpadding='0' align='left' width='100%'>";
                //tabla += "<tr><td width='5%'><p align='center'><strong>(1)NUM</strong></p></td><td width='5%'><p align='center'><strong>(2)CLASE</strong></p></td><td><p align='center' width='17%'><strong>(3)QUE SE DICE QUE CONTIENE</strong></p></td><td width='5%'><p align='center'><strong>(4)PESO</strong></p></td><td width='5%'><p align='center'><strong>MTS 3</strong></p></td><td width='10%'><p align='center'><strong>PESO ESTIMADO</strong></p></td></tr>";
                for (int i = 0; i < gridConceptos.Rows.Count - 1; i++)
                {
                    if (gridConceptos[1, i].Value.ToString() != "0.00")
                    {
                        tablaC += "<tr>";
                        decimal moneda = Convert.ToDecimal(gridConceptos[1, i].Value.ToString());
                        tablaC += "<td width='51%' valign='top'><p>" + gridConceptos[0, i].Value.ToString() + "</p></td>" + "<td width='49%'   valign='top'><p align='right'>" + moneda.ToString("C") + "</p></td>";
                        tablaC += "</tr>";
                    }
                    else
                    {

                        tablaC += "<tr>";
                        tablaC += "<td width='51%' valign='top'><p>" + "." + "</p></td>" + "<td width='49%'   valign='top'><p align='right'>" + "" + "</p></td>";
                        tablaC += "</tr>";
                    }
                } tablaC += "</table>";             
              

                StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
                styles.LoadTagStyle("table", "style", "font-family:Courier New, Courier, monospace;line-height:7pt;");
                
                string html = "<html xmlns='http://www.w3.org/1999/xhtml'><body><table id='contenedor' width='100%' border='0' height='100%' cellspacing='0'><tr><td width='6%' height='165'></td><td width='84%' valign='top'><table   width='130%' height='70' border='0' align='left' cellpadding='0' cellspacing='0' id='razonSocial' style='font-size:8px;'><tr><td width='46%' height='100%'   align='center' valign='top'><p align='center'><strong><h4>" + de + "</h4></strong></p></td></tr><tr><td width='46%' valign='top'><p   align='center'>" + direccion + numeroExterior + "</p></td></tr><tr><td width='46%' valign='top'><p align='center'>" + coloniaE + "</p></td></tr><tr><td width='46%' valign='top'><p align='center'>" + municipioE + estadoE + cpE + "</p></td></tr><tr><td width='46%' valign='top'><p   align='center'>" + tel1 + tel2 + "</p></td></tr><tr><td valign='top'><p align='center'>" + rfcE + "<br><br><br><a href=\"www.grupocalafia.com.mx\">www.grupocalafia.com.mx</a></p></td></tr><tr><td width='46%' valign='baseline'><br/><br/>EXPEDIDA  EN: " + label[42]/*lblDireccion.Text*/ + "<br/>  Tels.:" + label[47]/*lblTelefono1.Text*/ + ", " + label[48]/*lblTelefono2.Text*/ + "</td></tr><tr><td align='right' valign='bottom'></td></tr><tr></tr></table></td><td width='10%'><table id='factura' style='font-size:8px ¡important;'  border='1' cellspacing='0' cellpadding='2' align='right' width='75%' height='70%'><tr><td colspan='2' valign='top'><p align='center'><strong>CARTA   PORTE</strong></p></td></tr><tr><td width='45%' valign='top'><p align='center'><strong>SERIE</strong><br/>" + label[0] + "</p></td><td width='55%' valign='middle'><p   align='center'><strong>NUMERO</strong><br/>" + label[1] + "</p></td></tr><tr><td colspan='2' valign='top'><p align='center'><strong>NO.   CERTIFICADO</strong><br/>" + lblCertificado.Text + "</p></td></tr><tr><td colspan='2' align='center' valign='top'><strong>FECHA Y HORA DE CERTIFICACIÓN</strong><br/>" + fechaTim + "</td></tr><tr><td colspan='2' valign='top'><p   align='center'><strong>CERTIFICADO SAT</strong><br />" + lblCSAT.Text + "</p></td></tr><tr><td   colspan='2' valign='top'><p align='center'><strong>FOLIO FISCAL</strong><br />" + lblFF.Text + "</p></td></tr><tr><td colspan='2' valign='top'><p><strong>TIPO COMPROBANTE:</strong>" + lblComprobante.Text + "</p></td></tr><tr><td colspan='2'   valign='top'><p align='center'><strong>FECHA EXPEDICIÓN</strong><br />" + label[33]/*lblFecha.Text*/ + "</p></td></tr></table></td></tr><tr><td height='10' colspan='4' valign='top' style='font-size:8px ¡important'></td></tr><tr><td height='199' colspan='3' valign='middle'><table width='100%' height='598' border='1'   align='left' cellpadding='0' cellspacing='0' style='font-size:6px'><tr><td height='596' colspan='2' valign='top'><table style='font-size:6px' border='1'   cellspacing='0' cellpadding='0' align='left' width='100%'><tr><td height='444' colspan='4' valign='top'><table id='remitente' style='font-size:8px   ¡important;' border='1' cellspacing='0' cellpadding='0' align='left' width='100%'><tr><td height='8' valign='top'><p   align='center'><strong>REMITENTE</strong></p></td><td align='center' valign='top'><strong>DESTINATARIO</strong></td></tr><tr><td  height='25' valign='top'><table  id='remitente' style='font-size:7px   ¡important;' border='0' cellspacing='0' cellpadding='2' align='left' width='100%'><tr><td colspan='2' valign='top'><p>Número " + label[3]/*lblIdClienteRemitente.Text*/ + " - " + label[4]/*lblPlazaRemitente.Text*/ + "</p></td></tr><tr><td colspan='2' valign='top'><p><strong>" + label[5]/*lblNombrePlazaRemitente.Text*/ + "</strong></p></td></tr><tr><td   colspan='2' valign='top'><p>Calle:" + label[7] + label[52] + label[53]/*lblDireccionRemitente.Text*/ + " Col." + label[8]/*lblColoniaRemitente.Text*/ + "</p></td></tr><tr><td colspan='2'   valign='top'><p>Ciudad:" + label[9]/*lblCiudadRemitente.Text*/ + "  Estado:" + label[10]/*lblEstadoRemitente.Text*/ + "  Pais:" + label[11]/*lblPaisRemitente.Text*/ + " C.P:" + label[12]/*lblCPRemitente.Text*/+ "</p></td></tr><tr><td width='64%'   valign='top'><p>Tels.:" + label[13]/*lblTelefono1Remitente.Text*/ + "</p></td><td width='36%' valign='top'><p>R.F.C.:" + label[6]/*lblRFCRemitente.Text*/ + "</p></td></tr><tr><td height='6' colspan='2' valign='top'><p>RECOGER EN:" + label[14]/*lblRecoger.Text*/ + "</p></td></tr></table></td><td valign='top'><table   id='destinatario' border='0' style='font-size:7px ¡important' cellspacing='0' cellpadding='2' align='left' width='100%'><tr><td colspan='2'   valign='top'><p>Número " + label[15]/*lblIdClienteDestinatario.Text*/ + " - " + label[16]/*lblPlazaDestinatario.Text*/ + "</p></td></tr><tr><td colspan='2'   valign='top'><p><strong>" + label[17]/*lblNombrePlazaDestinatario.Text*/ + "</strong></p></td></tr><tr><td colspan='2' valign='top'><p>Calle:" + label[19] + label[54] + label[55]/*lblDiereccionDestinatario.Text*/ + " Col." + label[20]/*lblColoniaDestinatario.Text*/ + "</p></td></tr><tr><td colspan='2' valign='top'><p>Ciudad:" + label[21]/*lblCiudadDestinatario.Text*/ + " Estado:" + label[22]/*lblEstadoDestinatario.Text*/ + " Pais:" + label[23]/*lblPaisDestinatario.Text*/ + " C.P:" + label[24]/*lblCPDestinatario.Text*/+ "</p></td></tr><tr><td width='63%'   valign='top'><p>Tels.:" + label[25]/*lblTelefono1Destinatario.Text*/ + "</p></td><td width='37%' valign='top'><p>R.F.C.:" + label[18]/*lblRFCDestinatario.Text*/ + "</p></td></tr><tr><td colspan='2' valign='top'><p>ENTREGAR EN:" + label[26]/*lblEntrega.Text*/ + "</p></td></tr></table></td></tr><tr><td   height='20' colspan='3' valign='top'><table style='font-size:6px' border='1' cellspacing='0' cellpadding='0' align='left' width='100%'><tr><td width='20%'   valign='top'><p align='center'><strong>(6) FRACCIÓN NUM</strong></p></td><td width='29%' valign='top'><p align='center'><strong>(7)   CLASE</strong></p></td><td width='27%' valign='top'><p align='center'><strong>(8) CUOTA POR TONELADA</strong><br />" + label[34]/*lblValor1.Text*/ + "</p></td><td width='22%' valign='top'><p   align='center'><strong>VALOR DECLARADO</strong><br />" + label[35]/*lblValor2.Text*/ + "</p></td></tr><tr><td align='center' valign='middle'><strong>BULTOS</strong></td><td valign='top'>&nbsp;</td><td align='center'   valign='middle'><strong>(5) VOLUMEN</strong></td><td align='center' valign='top'><table style='font-size:6px' border='1' cellspacing='0' cellpadding='0' align='right' width='100%'><tr><td width='8%' rowspan='2' valign='top'><p   align='center'><strong>&nbsp;</strong><strong>CONCEPTO</strong></p></td><td width='13%' valign='top'><p align='center'><strong>(9) MOD.   PAGO</strong></p></td></tr><tr><td width='13%' height='8' valign='top'><p align='center'>" + label[27]/*lblPago.Text*/ + "</p></td></tr></table></td></tr><tr></tr></table></td></tr><tr><td height='23'   colspan='3' valign='top'><div align='left'><table width='100%' border='0' align='left' cellspacing='0'><tr><td width='80%' height='50'>" + tabla + "</td><td width='20%'>" + tablaC + "</td></tr></table></div></td></tr><tr><td height='61'   colspan='3' valign='top'><table width='100%' border='0' cellspacing='0'><tr><td width='77%' height='64'><table style='font-size:6px' border='1'   cellspacing='0' cellpadding='0' align='left' width='100%' height='100%'><tr><td width='64%'  valign='top'><p><strong>IMPORTE CON LETRA:</strong>" + label[51]/*lblImportLetra.Text*/ + "</p><br /><p><strong>RETENEDOR: </strong>" + retenedor/*lblRetenedor.Text*/ + "</p></td></tr></table></td><td width='23%'><table border='0' style='font-size:6px'   cellspacing='0' cellpadding='0' align='left' width='100%'><tr><td width='21%' valign='top'><p><strong>SUB-TOTAL</strong></p></td><td width='13%'   valign='top'><p align='right'>$ " + label[37]/*lblSubtotal.Text*/ + "</p></td></tr><tr><td width='21%' valign='top'><p><strong>%I.V.A " + label[38]/*lblIvaActual.Text*/ + "</strong></p></td><td width='13%'   valign='top'><p align='right'>$ " + label[39]/*lblIva.Text*/ + "</p></td></tr><tr><td width='21%' valign='top'><p><strong>RET I.V.A . " + label[40]/*lblPorcentajeR.Text*/ + "</strong></p></td><td   width='13%' valign='top'><p align='right'>$ " + label[41]/*lblRetIva.Text*/ + "</p></td></tr><tr><td width='21%' valign='top'><p><strong>TOTAL</strong></p></td><td width='13%'   valign='top'><p align='right'>$ " + label[28]/*lblTotal.Text*/ + "</p></td></tr></table></td></tr></table></td></tr><tr><td height='10' colspan='3' valign='top'><table style='font-  size:6px' width='100%' border='0' cellspacing='0'><tr><td width='50%'><div align='right'><strong>OBSERVACIONES</strong></div></td><td width='50%'><div   align='right'>Impuesto retenido con la ley del Impuesto al Valor Agregado</div></td></tr></table></td></tr><tr><td height='10' colspan='3'   valign='top'><table style='font-size:6px' cellpadding='2' width='100%' border='1' cellspacing='0'><tr><td width='28%'><table style='font-size:6px; monospace;line-height:1pt !important;' border='0' cellspacing='0'   cellpadding='2' align='left' width='100%'><tr><td width='17%' valign='top'><p><strong>TOTAL CARTA PORTE</strong></p></td><td width='9%' valign='top'><p>$   " + label[29]/*lblTotalCartaPorte.Text*/ + "</p></td></tr><tr><td width='17%' valign='top'><p><strong>OTRAS LINEAS</strong></p></td><td width='9%' valign='top'><p>$   " + label[30]/*lblOtrasLineas.Text*/ + "</p></td></tr><tr><td width='17%' valign='top'><p><strong>TOTAL A COBRAR</strong></p></td><td width='9%' valign='top'><p>$   " + label[31]/*lblTotalCobrar.Text*/ + "</p></td></tr><tr><td width='27%' colspan='2' valign='top'><p><strong>DOCUMENTÓ: </strong>" + label[32] /*lblDocumento.Text*/ + "</p></td></tr></table></td><td width='72%' valign='top'>" + label[36]/*lblObservacines.Text*/ + "</td></tr></table></td></tr><tr><td height='36' colspan='3'   valign='top'><table id='cadenas' style='font-size:7px ¡important; line-height:5pt !important' border='1' cellspacing='0' cellpadding='2' align='left' width='100%'><tr><td height='37' align='center'   valign='top'><strong>SELLO DEL SAT</strong><p style='top:1px' align='left'>" + lblSSAT.Text + "</p></td></tr><tr><td width='100%' align='center' valign='top'><strong>CADENA ORIGINAL DEL COMPLEMENTO DE CERTIFICACIÓN  DIGITAL DEL SAT</strong><p align='left'>" + lblCCS.Text + "</p></td></tr><tr><td width='100%'   valign='top' align='center'><strong>SELLO DIGITAL DEL CFDi</strong><p align='left'>" + lblSCFDI.Text + "</p></td></tr><tr><td width='100%' height='2' valign='top' nowrap></td></tr></table></td></tr><tr><td height='10' colspan='3' valign='top'><table style='font-size:6px; line-height:5pt !important' border='0' cellspacing='0' cellpadding='0' align='left' width='100%'><tr><td width='82%'   valign='top'><p><strong>CONDICIONES DEL CONTRATO DE TRANSPORTE QUE AMPARA ESTA CARTA DE PORTE</strong></p></td></tr><tr><td width='82%' valign='top'   nowrap><p align='justify'>PRIMERA.- Para los efectos del presente contrato de transporte se denomina \'Porteador\' al transportista y \'Remitente\' al   usuario que contrate el servicio.</p></td></tr><tr><td width='82%' valign='top' nowrap><p align='justify'>SEGUNDA.- El \'Remitente\' es responsable de que la   información proporcionada al \'Porteador\' sea veraz y que la documentación que entregue para efectos del transporte sea la correcta.</p></td></tr><tr><td   width='82%' valign='top' nowrap><p align='justify'>TERCERA.- El \'remitente\' debe declarar al “Porteador” el tipo de mercancía o efectos de que se trate,   peso, medidas y/o numero de la carga que entrega para su transporte y, en su caso, el valor de la misma. La carga que se entregue a granel será pesada por el   “Porteador\' en el primer punto donde haya báscula apropiada o, en su defecto, aforada en metros cúbicos con la conformidad del   “Remitente”.</p></td></tr><tr><td height='6' style='margin-right:40px' valign='top' nowrap><p align='justify'>CUARTA.- Para efectos del transporte, el “remitente” deberá entregar al   “Porteador” los documentos que las leyes y reglamentos exijan para llevar a cabo el servicio, en caso de no cumplirse con estos requisitos el “Porteador\'   está obligado a rehusar el transporte de las mercancías.</p> </td></tr><tr><td height='8' valign='top' nowrap> <p align='justify'>QUINTA.- Si por sospecha de   falsedad en la declaración del contenido de un bulto el “Porteador” deseare proceder a su reconocimiento, podrá hacerlo ante testigos y con asistencia del   “Remitente” o del consignatario, si este último no concurriere, se solicitará la presencia de un inspector de la Secretaría de Comunicaciones y Transportes,   y se levantará el acta correspondiente. El “Porteador” tendrá en todo caso la obligación de dejar los bultos en el estado en que se encontraban antes del   reconocimiento.</p></td></tr><tr><td height='8' valign='top' nowrap><p align='justify'>SEXTA.- El “Porteador” deberá recoger y entregar la carga precisamente   en los domicilios que señale el “Remitente”, ajustándose a los términos y condiciones convenidos. El “Porteador” sólo está obligado a llevar la carga la   domicilio del consignatario para su entrega una sola vez. Si está no fuera recibida, se dejará aviso de que la mercancía queda a disposición del interesado   en las bodegas que indique el “Porteador”.</p></td></tr><tr><td width='82%' height='6' valign='top' nowrap><p align='justify'>SEPTIMA.- si la carga no fuera   retirada dentro de los 30 días siguientes a aquel en que hubiese sido puesta a disposición del consignatario, el ”Porteador” podrá solicitar la venta en   pública subasta con arreglo a lo que dispone el Código de Comercio.</p></td></tr><tr><td height='6' valign='top' nowrap><p align='justify'>OCTAVA.- El   “Porteador” y el “Remitente” negociarán libremente el precio del servicio, tomando en cuenta su tipo, característica de los embarques, volumen, regularidad,   clase de carga y sistema de pago. </p></td></tr><tr><td height='9' valign='top' nowrap><p align='justify'>NOVENA.- Si el “Remitente” desea que el “Porteador”   asuma la responsabilidad por el valor de la mercancía o efectos que él declare o cubra toda clase de riesgos, inclusive los derivados en caso fortuito o de   fuerza mayor, las partes deberán convenir un cargo adicional, equivalente al valor de la prima del seguro que se contrate, el cual se deberá expresar en la   carta de porte electrónica o factura electrónica. </p></td></tr><tr><td height='8' valign='top' nowrap><p align='justify'>DECIMA.- cuando el importe del   flete no incluya el cargo adicional, la responsabilidad del “Porteador” queda expresamente limitada a la cantidad equivalente a 15 días del salario mínímo   vigente en el distrito Federal por tonelada o cuando se trate de embarques cuyo peso sea mayor a 200 Kg pero menor a 1000 Kg; y a 4 días de salario mínimo   por remesa cuando se trate de embarques con peso hasta de 200 Kg. </p></td></tr><tr><td height='9' valign='top' nowrap><p align='justify'>DECIMA PRIMERA.- El   precio del transporte deberá pagarse en origen, salvo convenio entre las partes de pago en destino. Cuando el transporte se hubiere concertado “Flete por   Cobrar”, la entrega de las mercancías o efectos se hará contra el pago del flete y el “Porteador” tendrá derecho a retenerlos mientras no se cubra el precio   convenido. </p></td></tr><tr><td height='9' valign='top' nowrap><p align='justify'>DECIMA SEGUNDA.- si al momento de la entrega resultare algún faltante o   avería, el consignatario deberá hacerla constar en ese acto en la carta de porte electrónica o factura electrónica y formular su reclamación por escrito al   “Porteador”, dentro de las 24 horas siguientes. </p></td></tr><tr><td height='8' valign='top' nowrap><p align='justify'>DECIMA TERCERA.- El “Porteador” queda   eximido de la obligación de recibir mercancías o efectos para su transporte, en los siguientes casos a) Cuando se trate de carga que por su naturaleza, peso,   volumen, embalaje defectuoso o cualquier otra circunstancia no pueda transportarse sin destruirse o sin causar daño a las demás artículos o al material   rodante, salvo que la empresa de que se trate tenga el equipo adecuado. b)Las mercancías cuyo transporte haya sido prohibido por disposiciones legales o   reglamentarias. Cuando tales disposiciones no prohíban precisamente el transporte de determinadas mercancías, pero si ordenen la presentación de ciertos   documentos para que puedan ser transportadas, el “Remitente estará obligado a entregar al “Porteador” los documentos correspondientes.</p> </td></tr><tr><td   height='11' valign='top' nowrap><p align='justify'>DECIMA CUARTA.- Los casos no previstos en las presentes condiciones y las quejas derivadas de su   aplicación se someterán por la vía administrativa a la Secretaría de comunicaciones y transporte.</p></td></tr><tr><td height='14' valign='top'   nowrap>.</td></tr><tr><td height='24' valign='top' nowrap><p align='justify'>POR ESTE PAGARE RECONOZCO(EMOS) DEBER Y ME(NOS) OBLIGO(AMOS) A PAGAR   INCONDICIONALMENTE A LA ORDEN DE TRANSPORTES CALAFIA S.A. DE C.V., EN SUS OFICINAS EN LA CIUDAD DE  GUADALAJARA, JAL., O EN EL LUGAR QUE ESTE ME(NOS) SEÑALE   EL DIA DE	    DE	LA CANTIDAD DE  $	VALOR RECIBIDO EN SERVICIOS A MI(NUESTRA) ENTERA SATISFACCIÓN. EN CASO DE MORA EL SALDO INSOLITO CAUSARA   INTERESES A RAZÓN DE % MENSUAL HASTA SU TOTAL LIQUIDACIÓN HACIENDO EXIGIBLE ESTA CANTIDAD EN EL MOMENTO DE HACER EL PAGO PRINCIPAL A DE __________ FIRMA DE   CONFORMIDAD </p></td></tr></table></td></tr><tr><td height='95' colspan='3' valign='middle' style='border:0   ¡important'><table style='font-size:7px ¡important;' cellspacing='0' cellpadding='2' hspace='0' vspace='0' align='center'><tr><td valign='top'   align='left'><p align='center'>" + label[44]/*lblLeyenda.Text*/ + "<br>METODO DE PAGO: " + label[45]/*lblMetodoPago.Text*/ + ", TERMINACIÓN: " + label[46]/*lblTerminacion.Text*/ + "<br>" + "RÉGIMEN FISCAL: " + leyenda + "<br><strong>Este  Documento es una representación impresa de un CFDi</strong></p></td> </tr>   </table></td></tr></table></td></tr></table></td></tr></table></td></tr><tr><td colspan='3'></td></tr></table></body></html>";
                
                Document pdf = new Document(PageSize.LETTER, 9, 8, 5, 5);

                PdfWriter.GetInstance(pdf, new FileStream(temp + nomenclatura + label[0] + label[1] + ".pdf", FileMode.OpenOrCreate));
                try
                {
                    PdfWriter.GetInstance(pdf, new FileStream(@directorioGuardarCP + "\\" + label[0] + "\\" + label[49] + "\\" + label[50] + "\\" + nomenclatura + label[0] + label[1] + ".pdf", FileMode.Create));
                }
                catch (Exception e)
                {
                    MessageBox.Show("No se puede guardar el PDF en el servidortqp \n" + e, "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                PdfWriter.GetInstance(pdf, new FileStream(@"\STC R2\CFDi\CartasPorte\" + "\\" + label[0] + "\\" + label[49] + "\\" + label[50] + "\\" + nomenclatura + label[0] + label[1] + ".pdf", FileMode.Create));
                pdf.Open();

                //Get the assembly.
                System.Reflection.Assembly CurrAssembly = System.Reflection.Assembly.LoadFrom(System.Windows.Forms.Application.ExecutablePath);
                //MyShortcut.IconLocation = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace.IconFilename.ico");

                //System.IO.Stream stream = CurrAssembly.GetManifestResourceStream("logocalafia.JPG");
                if (File.Exists(@"\STC R2\CFDi VB\logocalafia.JPG"))
                {
                    iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(@"\STC R2\CFDi VB\logocalafia.JPG");
                    logo.ScalePercent(25f);
                    logo.Alignment = iTextSharp.text.Image.UNDERLYING;
                    logo.SetAbsolutePosition(10, pdf.PageSize.Height - 77f);
                    pdf.Add(logo);
                }
                else
                {
                    MessageBox.Show("logocalafia.jpg No existe en "+ directorioRaiz+@"STC R2\CFDi VB\" , "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }                
                
                iTextSharp.text.Image cbb = iTextSharp.text.Image.GetInstance(@temp + nomenclatura + label[0] + label[1] + ".png");
                cbb.ScalePercent(42f);
                cbb.Alignment = iTextSharp.text.Image.UNDERLYING;
                cbb.SetAbsolutePosition(pdf.PageSize.Width - 601, pdf.PageSize.Height - 158f);
                pdf.Add(cbb);
                
                foreach (IElement E in HTMLWorker.ParseToList(new StringReader(html), styles))
                pdf.Add(E); 
                
                pdf.Close();

                //Valida si quieren enviar el xml o el pdf
                if (chbPdf.Checked || chbXml.Checked)
                {
                    enviarCorreo();
                }

            }
            catch (Exception)
            {

                MessageBox.Show("El PDF " + nomenclatura + label[0] + label[1] + " esta siendo utilizado por otro proceso", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


            try
            {
                //Process.Start(temp + nomenclatura + label[0] + label[1] + ".pdf");
                Process.Start( @"\STC R2\CFDi\CartasPorte\" + label[0] + "\\" + label[49] + "\\" + label[50] + "\\" + nomenclatura + label[0] + label[1] +".pdf");

                if (System.IO.File.Exists(@temp + nomenclatura + label[0] + label[1] + ".pdf"))
                {
                    
                    try
                    {
                        System.IO.File.Delete(@temp + nomenclatura + label[0] + label[1] + ".pdf");
                        System.IO.File.Delete(@temp + nomenclatura + label[0] + label[1] + ".txt");
                           
                        System.IO.File.Delete(@temp + nomenclatura + label[0] + label[1] + ".png");
                        System.IO.File.Delete(@temp + nomenclatura + label[0] + label[1] + ".xml");
                        //System.IO.File.Delete(@temp + nomenclatura + label[0] + label[1] + "timbre.xml");

                    }
                    catch (System.IO.IOException e)
                    {
                        MessageBox.Show("excepcion "+e);
                    }
                }
               
            }
            catch (Exception e)
            {
                MessageBox.Show("El PDF no se puede mostrar \n" + e, "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {                
                 this.Close();
                 Dispose();
            }

        }
Example #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="HtmlTemp"></param>
        /// <param name="FileName"></param>
        public static void MyPaymentReport(string FileName, string UserImg, string mycontent)
        {
            // Create a Document object
            HttpContext context  = HttpContext.Current;
            var         document = new Document(PageSize.A4, 50, 50, 25, 25);
            HTMLWorker  worker   = new HTMLWorker(document);
            // Create a new PdfWriter object, specifying the output stream
            //  var output = new FileStream(context.Server.MapPath("~/MyFirstPDF.pdf"), FileMode.Create);
            var output = new MemoryStream();
            var writer = PdfWriter.GetInstance(document, output);

            try
            {
                //string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
                //iTextSharp.text.FontFactory.Register(arialuniTff);

                string fontpath = System.Web.HttpContext.Current.Server.MapPath("~/Content/ARIALUNI.ttf");
                //  BaseFont bf = BaseFont.CreateFont(fontpath + "ARIALUNI.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                iTextSharp.text.FontFactory.Register(fontpath, "CustomAriel");
                //   Font f = new Font(bf, 10, Font.NORMAL);
            }catch (Exception objEx) {
            }

            // Open the Document for writing
            document.Open();

            //... Step 3: Add elements to the document! ...


            var titleFont         = FontFactory.GetFont("Arial", 18, Font.BOLD);
            var subTitleFont      = FontFactory.GetFont("Arial", 14, Font.BOLD);
            var boldTableFont     = FontFactory.GetFont("Arial", 12, Font.BOLD);
            var endingMessageFont = FontFactory.GetFont("Arial", 10, Font.ITALIC);
            var bodyFont          = FontFactory.GetFont("Arial", 12, Font.NORMAL);

            //document.Add(new Paragraph("IFind - Asia", titleFont));
            iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet();
            //Set the default body font to our registered font's internal name
            ST.LoadTagStyle("body", "face", "Arial Unicode MS");
            //Set the default encoding to support Unicode characters
            ST.LoadTagStyle("body", "encoding", "Identity-H");


            // step 4.3: assign the style sheet to the html parser
            worker.SetStyleSheet(ST);
            //List<IElement> list = HTMLWorker.ParseToList(new StringReader(mycontent), ST);


            //add logo
            //var logo = iTextSharp.text.Image.GetInstance(context.Server.MapPath("~/Img/Users/ducnguyen.jpg"));
            //Image logo = iTextSharp.text.Image.GetInstance(context.Server.MapPath(UserImg));
            //logo.ScaleToFit(80, 80);
            ////logo.SetAbsolutePosition(50, 700);
            //document.Add(logo);

            // Read in the contents of the Receipt.htm file...
            //string contents = File.ReadAllText(context.Server.MapPath("~/html/" + HtmlTemp + ".html"));
            //string contents = LoadWebtoHTML(context.Server.MapPath("~/PersonInfo/MyPdfReport"));
            string contents = getImage(mycontent);

            // Step 4: Parse the HTML string into a collection of elements...
            var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), ST);

            // Enumerate the elements, adding each one to the Document...
            foreach (var htmlElement in parsedHtmlElements)
            {
                document.Add(htmlElement as IElement);
            }


            // Close the Document - this saves the document contents to the output stream
            document.Close();

            context.Response.ContentType = "application/pdf";
            context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=MyPayment-{0}.pdf", FileName));
            context.Response.ContentEncoding = Encoding.UTF8;
            context.Response.HeaderEncoding  = Encoding.UTF8;
            context.Response.BinaryWrite(output.ToArray());
            context.Response.Flush();
            context.Response.End();
        }
        public void ProcessRequest(HttpContext context)
        {
            pedido = Convert.ToString(context.Request.QueryString["pedido"]);
            LogoAvant = "http://portalvendas.avantsp.com.br/avant-teste/img/acompanhe.png";

            HttpResponse Response = HttpContext.Current.Response;
            Response.ContentType = "application/pdf";

            HttpClient client = null;
            string retorno = string.Empty;

            if (client == null)
            {
                client = new HttpClient();
                client.BaseAddress = new Uri(ConfigurationManager.AppSettings["url_servidor"]);
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage resultado = client.GetAsync("AVANT/Pedido/WMS/" + pedido).Result;
                retorno = resultado.Content.ReadAsStringAsync().Result;

                if (resultado.StatusCode != System.Net.HttpStatusCode.NotFound)
                {
                    if (retorno != "[]")
                    {
                        JArray usuarioarrray = JArray.Parse(retorno);
                        foreach (JObject obj in usuarioarrray.Children<JObject>())
                        {
                            PedidoRealizado = Convert.ToString(obj.SelectToken("pedidoRealizado").ToString());
                            PedidoCredito = Convert.ToString(obj.SelectToken("pedidoCredito").ToString());
                            PedidoConferencia = Convert.ToString(obj.SelectToken("pedidoConferencia").ToString());
                            PedidoFaturado = Convert.ToString(obj.SelectToken("pedidoFaturado").ToString());
                            PedidoTransporte = Convert.ToString(obj.SelectToken("pedidoTransportadora").ToString());
                        }
                    }
                }

                if (PedidoConferencia == string.Empty)
                    PedidoConferencia = "Pedido sem WMS";
                if (PedidoEntregue != string.Empty)
                {
                    PedidoEntregue = PedidoEntregue.Substring(0, 18);
                    MensagemEntrege = PedidoEntregue.Substring(18, PedidoEntregue.Length - PedidoEntregue.Length);

                }
                else
                    PedidoEntregue = "Sem WMS"; MensagemEntrege = "Pedido sem WMS";

                if (PedidoRealizado != string.Empty)
                    ImgPedidoRealizado = "http://portalvendas.avantsp.com.br/avant-teste/img/sprite-suba_green.png"; // img
                else
                    ImgPedidoRealizado = "http://portalvendas.avantsp.com.br/avant-teste/img/sprite-suba_gray.png"; // gray

                if (PedidoCredito != string.Empty)
                    ImgPedidoCredito = "http://portalvendas.avantsp.com.br/avant-teste/img/sprite-suba_green.png";
                else
                    ImgPedidoCredito = "http://portalvendas.avantsp.com.br/avant-teste/img/sprite-suba_gray.png";

                if (PedidoConferencia != string.Empty)
                    ImgPedidoConferencia = "http://portalvendas.avantsp.com.br/avant-teste/img/sprite-suba_green.png";
                else
                    ImgPedidoConferencia = "http://portalvendas.avantsp.com.br/avant-teste/img/sprite-suba_gray.png";

                if (PedidoFaturado != string.Empty)
                    ImgPedidoFaturado = "http://portalvendas.avantsp.com.br/avant-teste/img/sprite-suba_green.png";
                else
                    ImgPedidoFaturado = "http://portalvendas.avantsp.com.br/avant-teste/img/sprite-suba_gray.png";

                if (PedidoTransporte != string.Empty)
                    ImgPedidoTransporte = "http://portalvendas.avantsp.com.br/avant-teste/img/sprite-suba_green.png";
                else
                    ImgPedidoTransporte = "http://portalvendas.avantsp.com.br/avant-teste/img/sprite-suba_gray.png";

                if (PedidoEntregue != string.Empty)
                    ImgPedidoEntregue = "http://portalvendas.avantsp.com.br/avant-teste/img/sprite-suba_green.png";
                else
                    ImgPedidoEntregue = "http://portalvendas.avantsp.com.br/avant-teste/img/sprite-suba_gray.png";

                //  dt = acompanhe.DadosPedidoWMS(Pedido);
                sb.Append("<html>");
                sb.Append("<body>");
                sb.Append("<span>");
                sb.Append("Pedido No." + pedido + "<br /> ");
                sb.Append("<img src='http://portalvendas.avantsp.com.br/avant-teste/img/acompanhe.png'  alt='Acompanhe seu pedido' /><br /><br /> ");

                sb.Append("<table>");
                sb.Append("<tbody>");
                sb.Append("<tr>");
                sb.Append(" <td> ");
                sb.Append("<table > ");
                sb.Append("<tr> ");
                sb.Append("<td>Realizado</td> ");
                sb.Append("<td></td> ");
                sb.Append("<td >Crédito</td> ");
                sb.Append("<td></td> ");
                sb.Append("<td >Conferido</td> ");
                sb.Append("<td></td> ");
                sb.Append("<td >Faturado</td> ");
                sb.Append("<td></td> ");
                sb.Append("<td >Transporte</td> ");
                sb.Append("<td></td> ");
                sb.Append("<td >Entregue</td> ");
                sb.Append("<td></td> ");
                sb.Append("</tr>");
                sb.Append("<tr>");
                sb.Append("<td colspan=\"12\" > ");
                sb.Append("<table>");
                sb.Append("<tr>");
                sb.Append("<td><img src=\"" + ImgPedidoRealizado + "\"  alt=\"acompanhe seu pedido\" id=\"pedidorealizado\" /></td><td ><img src=\"http://portalvendas.avantsp.com.br/avant-teste/img/green_line.png\"  /></td> ");
                sb.Append("<td><img src=\"" + ImgPedidoCredito + "\" id=\"pedidocredito\" alt=\"acompanhe seu pedido\"></td><td ><img src=\"http://portalvendas.avantsp.com.br/avant-teste/img/green_line.png\"  /></td> ");
                sb.Append("<td><img src=\"" + ImgPedidoConferencia + "\" alt=\"acompanhe seu pedido\" id=\"pedidoseparado\" /></td><td ><img src=\"http://portalvendas.avantsp.com.br/avant-teste/img/green_line.png\"  /></td> ");
                sb.Append("<td><img src=\"" + ImgPedidoFaturado + "\" alt=\"acompanhe seu pedido\" id=\"pedidofaturado\" /></td><td ><img src=\"http://portalvendas.avantsp.com.br/avant-teste/img/green_line.png\"  /></td> ");
                sb.Append("<td><img src=\"" + ImgPedidoTransporte + "\" alt=\"acompanhe seu pedido\" id=\"pedidotransporte\" /></td><td><img src=\"http://portalvendas.avantsp.com.br/avant-teste/img/green_line.png\"  /></td> ");
                sb.Append("<td><img src=\"" + ImgPedidoEntregue + "\" alt=\"acompanhe seu pedido\" id=\"pedidoentregue\" /></td>");
                sb.Append("</tr>");
                sb.Append("</table>");
                sb.Append("</td>");
                sb.Append("</tr>");
                sb.Append("<tr>");
                sb.Append("<td  colspan=\"2\" valign=\"top\">" + PedidoRealizado + "</td> ");
                sb.Append("<td  colspan=\"2\" valign=\"top\">" + PedidoCredito + "</td> ");
                sb.Append("<td  colspan=\"2\" valign=\"top\">" + PedidoConferencia + "</td> ");
                sb.Append("<td  colspan=\"2\" valign=\"top\">" + PedidoFaturado + "</td> ");
                sb.Append("<td  colspan=\"2\" valign=\"top\">" + PedidoTransporte + "</td> ");
                sb.Append("<td  colspan=\"2\" valign=\"top\">" + PedidoEntregue + "</td> ");
                sb.Append("</tr>");
                sb.Append("</table> ");
                sb.Append("</td>");
                sb.Append("</tr> ");
                sb.Append("</tbody>");
                sb.Append("</table>");
                sb.Append("<br /><br />");
                sb.Append(" Caso já tenha recebido o(s) produto(s), pedimos que desconsidere esta mensagem, ");
                sb.Append(" <br /><br /><br /> ");

                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow rw in dt.Rows)
                    {
                        sb.Append("<b>Endereço:</b> " + rw["ENDERECO"].ToString() + "<br />");
                        sb.Append("<b>Bairro:</b> " + rw["BAIRRO"].ToString() + " Municipio: " + rw["MUNICIPIO"].ToString() + "<br />");
                        sb.Append("<b>CEP:</b> " + rw["CEP"].ToString() + " Est:" + rw["ESTADO"].ToString() + "<br />");
                        sb.Append("<b>Telefone:</b> " + rw["TELEFONE"].ToString() + "Loja: " + rw["LOJA"].ToString());
                        sb.Append("<br /><br />");
                    }
                }

                sb.Append("<b>Política de entrega da Avant</b><br /><br /> ");
                sb.Append("- Em caso de Avarias, Desacordo com o Pedido, etc. gentileza anotar no Comprovante de Entrega o motivo da recusa.<br /><br /> ");
                sb.Append("- Recuse a entrega se a embalagem estiver aberta ou danificada.<br /><br /> ");
                sb.Append("- Ao receber suas mercadorias assinar, carimbar e datar o Comprovante de Entrega.<br /><br /><br /> ");
                sb.Append("<b>Para garantir a satisfação da sua compra, recomendamos:</b><br /><br /> ");
                sb.Append("- Preserve a embalagem do(s) produto(s) e o DANFE (Documento Auxiliar da Nota Fiscal Eletrônica) do pedido. Em caso de troca, eles serão necessários. ");
                sb.Append("STATUS DO SEU PEDIDO: ");
                sb.Append("</span> ");
                sb.Append("</body>");
                sb.Append("</html>");

                StyleSheet styles = new StyleSheet();
                styles.LoadTagStyle(HtmlTags.TABLE, HtmlTags.BORDER, "0");
                styles.LoadTagStyle(HtmlTags.TD, HtmlTags.ALIGN, "center");
                styles.LoadTagStyle(HtmlTags.TD, HtmlTags.FONTFAMILY, "Verdana");
                styles.LoadTagStyle(HtmlTags.TD, HtmlTags.FONTSIZE, "5");

                using (Document document = new Document())
                {
                    PdfWriter.GetInstance(document, Response.OutputStream);
                    document.Open();
                    List<IElement> objects = HTMLWorker.ParseToList(
                      new StringReader(sb.ToString()), styles
                    );
                    foreach (IElement element in objects)
                    {
                        document.Add(element);
                    }
                }

            }
        }
        public System.Web.Mvc.FileResult ExportPdf(long DocumentID)
        {
            iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 50, 50, 20, 70);
            MemoryStream output = new MemoryStream();
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, output);
            long userId = Convert.ToInt64(HttpContext.User.Identity.Name);
            OpenBookSystemMVC.OBISReference.Document doc = null;
            OBSDataSource.GetDocument(DocumentID, out doc);
            AccountInfo ai = null;
            OBSDataSource.GetUserProfile(userId, out ai);
            if (doc == null || ai == null)
            {
                return null;
            }

            string returnContent = doc.SimplifiedContent;
            if (ai.Preferences.DocumentFontSize == 0)
            {
                returnContent = returnContent.ToUpper();
            }

            pdfDoc.Open();

            iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet();

            if (ai.Preferences != null)
            {
                iTextSharp.text.FontFactory.Register(Server.MapPath("/Content/fonts/verdana.ttf"), "Verdana");
                iTextSharp.text.FontFactory.Register(Server.MapPath("/Content/fonts/times.ttf"), "Times New Roman");
                iTextSharp.text.FontFactory.Register(Server.MapPath("/Content/fonts/calibri.ttf"), "Calibri");
                iTextSharp.text.FontFactory.Register(Server.MapPath("/Content/fonts/tahoma.ttf"), "Tahoma");

                iTextSharp.text.Font font = iTextSharp.text.FontFactory.GetFont(
                    ai.Preferences.DocumentFontName,
                    ai.Preferences.DocumentFontSize > 0 ? ai.Preferences.DocumentFontSize : 18);

                ST.LoadTagStyle(iTextSharp.text.html.HtmlTags.BODY, iTextSharp.text.html.HtmlTags.FACE, ai.Preferences.DocumentFontName);
            }
            else
            {
                ST.LoadTagStyle(iTextSharp.text.html.HtmlTags.BODY, iTextSharp.text.html.HtmlTags.FACE, "Times New Roman");
            }

            ST.LoadTagStyle(iTextSharp.text.html.HtmlTags.BODY, iTextSharp.text.html.HtmlTags.ENCODING, BaseFont.IDENTITY_H);

            List<iTextSharp.text.IElement> htmlElements = HTMLWorker.ParseToList(new StringReader(returnContent), ST);

            FormatImgElements(htmlElements);

            foreach (var item in htmlElements)
            {

                pdfDoc.Add(item);
            }

            pdfDoc.Close();

            var bytes = output.ToArray();

            return File(bytes, "application/pdf", string.Format("{0}.pdf", doc.Title));
        }
    private bool CreatePDF(string HTMLContent, string OutputFilePath, out string ErrorIfAny)
    {
        bool IsSuccess = false;

        ErrorIfAny = string.Empty;
        Document document = new Document();

        try
        {
            StringWriter SW = new StringWriter();
            SW.Write(HTMLContent);
            MyPage   tmpPage = new MyPage();
            HtmlForm form    = new HtmlForm();
            form.Controls.Add(new LiteralControl(""));
            tmpPage.Controls.Add(form);
            HtmlTextWriter htmlWriter = new HtmlTextWriter(SW);
            form.Controls[0].RenderControl(htmlWriter);
            string htmlContent = SW.ToString();
            PdfWriter.GetInstance(document, new FileStream(OutputFilePath, FileMode.Create));

            HTMLWorker worker = new HTMLWorker(document);
            document.Open();
            using (TextReader sReader = new StringReader(htmlContent))
            {
                FontFactory.Register(@"[Your font file location].ttf", "OpenSans-Regular");
                string fontpath = @"[Your font file location].ttf";
                //"simsun.ttf" file was downloaded from web and placed in the folder
                BaseFont bf = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                //create new font based on BaseFont
                Font fontContent = new Font(bf, 11);
                Font fontHeader  = new Font(bf, 12);
                // step 4.2: create a style sheet and set the encoding to Identity-H
                iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet();
                ST.LoadTagStyle("body", "encoding", "Identity-H");
                worker.SetStyleSheet(ST);
                worker.StartDocument();
                worker.Parse(sReader);
                worker.EndDocument();
                worker.Close();
                document.Close();
            }
            IsSuccess = true;
        }
        catch (Exception eX)
        {
            IsSuccess  = false;
            ErrorIfAny = eX.Message;
        }
        finally
        {
            try
            {
                if (document != null && document.IsOpen())
                {
                    document.Close();
                }
            }
            catch { }
        }
        return(IsSuccess);
    }
        /// <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;
        }
Example #15
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();
        }
        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;
               }
        }
Example #17
0
        public String GeneratePdfFromHtml(String html, String numero)
        {
            //var document = new Document(PageSize.A4, 5, 5, 5, 5);
            var document = new Document(PageSize.A4, 50, 25, 15, 10);
            var output = new MemoryStream();
            var writer = PdfWriter.GetInstance(document, output);
            document.Open();
            var contents = html;
            contents = contents.Replace("<hr />", "____________________________________________________________________________________________________________________");

            var styles = new StyleSheet();
            styles.LoadTagStyle("body", "face", "Arial");
            styles.LoadTagStyle("body", "size", "7px");
            styles.LoadTagStyle("body", "background-color", "#000000");

            var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), styles);

            foreach (var parsedHtmlElement in parsedHtmlElements)
                document.Add(parsedHtmlElement);

            document.Close();

            byte[] content = output.ToArray();

            var pathPDf = Path.GetTempPath() + "cotizacion_" + numero + ".pdf";
            using (FileStream fs = File.Create(pathPDf))
            {
                fs.Write(content, 0, (int)content.Length);
            }

            return pathPDf;
        }
Example #18
-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);             
      }
    }