コード例 #1
0
ファイル: PdfHelper.cs プロジェクト: lanicon/iExportEngine
        /// <summary>
        /// Creates a new font from model.
        /// </summary>
        /// <param name="font">Font to create.</param>
        /// <returns>
        /// A new <see cref="T:iTextSharp.text.Font" /> that contains specified font from model.
        /// </returns>
        public static Font CreateFont(FontModel font)
        {
            if (font == null)
            {
                font = FontModel.Default;
            }

            var registeredFonts = FontFactory.RegisteredFonts.Count;

            if (registeredFonts <= 14)
            {
                FontFactory.RegisterDirectories();
            }

            var style = Font.NORMAL;

            if (font.Italic == YesNo.Yes)
            {
                style = Font.ITALIC;
            }

            if (font.Bold == YesNo.Yes)
            {
                style = style | Font.BOLD;
            }

            if (font.Underline == YesNo.Yes)
            {
                style = style | Font.UNDERLINE;
            }

            return(FontFactory.GetFont(font.Name, font.Size, style, new BaseColor(font.GetColor())));
        }
コード例 #2
0
ファイル: PdfRenderer.cs プロジェクト: trailmax/Homoiconicity
        public override MemoryStream CreateDocument(IEnumerable <IResumeSection> resumeSections, ResumeData data)
        {
            byte[] resultBytes;

            FontFactory.RegisterDirectories();

            var fontPath = mapperPathMapper.MapPath(InconsolataTtf);

            FontFactory.Register(fontPath, PdfConverter.Verdana);

            var pdfOutputStream = new MemoryStream();

            document = new Document(PageSize.A4);
            document.SetMargins(20, 20, 20, 20);



            PdfWriter.GetInstance(document, pdfOutputStream);

            document.AddTitle(data.DocumentTitle);
            document.Open();

            base.RenderElements(resumeSections, data);

            document.Close();
            resultBytes = pdfOutputStream.ToArray();
            pdfOutputStream.Close();
            pdfOutputStream.Dispose();
            return(new MemoryStream(resultBytes));
        }
コード例 #3
0
        public CustomFontFactory(
            string defaultFontFilePath,
            string defaultFontEncoding = BaseFont.IDENTITY_H,
            bool defaultFontEmbedding  = BaseFont.EMBEDDED,
            float?defaultFontSize      = null,
            int?defaultFontStyle       = null,
            BaseColor defaultFontColor = null,
            bool automaticalySetReplacementForNullables = true)
        {
            //set default font properties
            DefaultFontPath      = defaultFontFilePath;
            DefaultFontEncoding  = defaultFontEncoding;
            DefaultFontEmbedding = defaultFontEmbedding;
            DefaultFontColor     = defaultFontColor ?? DEFAULT_FONT_COLOR;
            DefaultFontSize      = defaultFontSize ?? DEFAULT_FONT_SIZE;
            DefaultFontStyle     = defaultFontStyle ?? DEFAULT_FONT_STYLE;

            //set default replacement options
            ReplaceFontWithDefault      = false;
            ReplaceEncodingWithDefault  = true;
            ReplaceEmbeddingWithDefault = false;

            if (automaticalySetReplacementForNullables)
            {
                ReplaceSizeWithDefault  = defaultFontSize.HasValue;
                ReplaceStyleWithDefault = defaultFontStyle.HasValue;
                ReplaceColorWithDefault = defaultFontColor != null;
            }

            //define default font
            DefaultBaseFont = BaseFont.CreateFont(DefaultFontPath, DefaultFontEncoding, DefaultFontEmbedding);

            //register system fonts
            FontFactory.RegisterDirectories();
        }
コード例 #4
0
        /// <summary>
        /// Must use this after calling document.Open()
        /// </summary>
        /// <param name="writer"></param>
        /// <returns></returns>
        public static PdfWriter RegisterFonts(this PdfWriter writer)
        {
            FontFactory.RegisterDirectories();
            var icc = ICC_Profile.GetInstance((byte[])Properties.Resources.ResourceManager.GetObject("icc_profile"));

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            return(writer);
        }
コード例 #5
0
 public SingleSheetLabelCreator(LabelDefinition labelDefinition, Enums.Alignment hAlign)
 {
     FontFactory.RegisterDirectories();             //Register all local fonts
     _labelDefinition    = labelDefinition;
     _creator            = new CustomLabelCreator(labelDefinition);
     _label              = new Label(hAlign);
     IncludeLabelBorders = false;
 }
コード例 #6
0
        public CustomLabelCreator(LabelDefinition labelDefinition)
        {
            FontFactory.RegisterDirectories(); //Register all local fonts

            _labelDefinition    = labelDefinition;
            _labels             = new List <Label>();
            IncludeLabelBorders = false;
        }
コード例 #7
0
        /// <summary>
        /// Creates a new font from model.
        /// </summary>
        /// <param name="font">Font to create.</param>
        /// <returns>
        /// A new <see cref="Font"/> that contains specified font from model.
        /// </returns>
        public static Font CreateFont(FontModel font)
        {
            Logger.Instance.Debug("");
            Logger.Instance.Debug(" Assembly: iTin.Utilities.Pdf, Namespace: iTin.Utilities.Pdf.Helpers, Class: PdfHelper");
            Logger.Instance.Debug($" Creates a new font from model");
            Logger.Instance.Debug($" > Signature: ({typeof(Font)}) CreateFont({typeof(FontModel)})");
            Logger.Instance.Debug($"   > font: {font}");

            if (font == null)
            {
                font = FontModel.DefaultFont;
            }

            int registeredFonts = FontFactory.RegisteredFonts.Count;

            if (registeredFonts <= 14)
            {
                FontFactory.RegisterDirectories();
            }

            int style = Font.NORMAL;

            if (font.Italic.AsBoolean())
            {
                style = Font.ITALIC;
            }

            if (font.Bold.AsBoolean())
            {
                style |= Font.BOLD;
            }

            if (font.Underline.AsBoolean())
            {
                style |= Font.UNDERLINE;
            }

            Font validFont;
            var  isFontRegistered = FontFactory.IsRegistered(font.Name);

            if (isFontRegistered)
            {
                validFont = FontFactory.GetFont(
                    font.Name,
                    BaseFont.IDENTITY_H,
                    BaseFont.EMBEDDED,
                    font.Size,
                    style,
                    new BaseColor(font.GetColor()));
            }
            else
            {
                var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, FontFactory.DefaultEncoding, BaseFont.EMBEDDED);
                validFont = new Font(baseFont, font.Size, style, new BaseColor(font.GetColor()));
            }

            return(validFont);
        }
コード例 #8
0
ファイル: BillPdf.cs プロジェクト: SKDon/Tracker
        static BillPdf()
        {
            FontFactory.RegisterDirectories();

            SmallFont   = FontFactory.GetFont("Arial", BaseFont.IDENTITY_H, 8);
            DefaultFont = FontFactory.GetFont("Arial", BaseFont.IDENTITY_H, 9.5f);
            TitleFont   = FontFactory.GetFont("Arial Bold", BaseFont.IDENTITY_H, 13.5f);
            BoldFont    = FontFactory.GetFont("Arial Bold", BaseFont.IDENTITY_H, 9.5f);
        }
コード例 #9
0
        public LabelCreator(Label label)
        {
            FontFactory.RegisterDirectories();             //Register all local fonts

            _label              = label;
            _images             = new List <byte[]>();
            _textChunks         = new List <TextChunk>();
            IncludeLabelBorders = false;
        }
コード例 #10
0
        private Font GetBaseFont()
        {
            const float  FONT_SIZE = 7.0f;
            const string FONT_NAME = "MS Gothic"; //"MS Micho";

            FontFactory.RegisterDirectories();
            Font retFont = FontFactory.GetFont(FONT_NAME, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED, FONT_SIZE);

            return(retFont);
        }
コード例 #11
0
ファイル: Utilities.cs プロジェクト: ebsilva/FinanceiroDemo
        /*--------------------------------------------------------
         * Exportar um HTML fornecido.
         *    - O HTML.
         *    - Nome do Arquivo.
         * - Link para o CSS.
         * ----------------------------------------------------------*/


        public static void Export(string html, string fileName, string linkCss)
        {
            ////reset response
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "application/pdf";

            ////define pdf filename
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + fileName);



            //Gera o arquivo PDF
            using (var document = new Document(PageSize.A4, 40, 40, 40, 40))
            {
                //html = FormatImageLinks(html);

                //define o  output do  HTML
                var        memStream = new MemoryStream();
                TextReader xmlString = new StringReader(html);

                PdfWriter writer = PdfWriter.GetInstance(document, memStream);
                writer.PageEvent = new PDFWriteEvents();

                document.Open();


                //Registra todas as fontes no computador cliente.
                FontFactory.RegisterDirectories();

                // Set factories
                var htmlContext = new HtmlPipelineContext(null);
                htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

                // Set css
                ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                cssResolver.AddCssFile(HttpContext.Current.Server.MapPath(linkCss), true);

                // Exporta
                IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
                var       worker   = new XMLWorker(pipeline, true);
                var       xmlParse = new XMLParser(true, worker);
                xmlParse.Parse(xmlString);
                xmlParse.Flush();

                document.Close();
                document.Dispose();

                HttpContext.Current.Response.BinaryWrite(memStream.ToArray());
            }

            HttpContext.Current.Response.End();
            HttpContext.Current.Response.Flush();
        }
コード例 #12
0
        public override void Start()
        {
            base.Start();
            this.document         = (this.reportSettings.Landscape)? new Document(PageSize.A4.Rotate(), 0, 0, 0, 0) : new Document(PageSize.A4, 0, 0, 0, 0);
            this.pdfUnitConverter = new PdfUnitConverter(this.document.PageSize, this.reportSettings);
            this.pdfWriter        = PdfWriter.GetInstance(document, new FileStream(this.fileName, FileMode.Create));
            document.AddCreator(GlobalValues.ResourceString("ApplicationName"));
            FontFactory.RegisterDirectories();
            MyPageEvents events = new MyPageEvents();

            this.pdfWriter.PageEvent = events;
        }
コード例 #13
0
        public byte[] Render(string htmlText, string pageTitle, string linkCss, bool horizontal)
        {
            byte[] renderedBuffer;
            using (var outputMemoryStream = new MemoryStream())
            {
                using (var pdfDocument = new Document(PageSize.A4, HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin))
                {
                    if (horizontal)
                    {
                        pdfDocument.SetPageSize(PageSize.A4.Rotate());
                    }
                    PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream);
                    pdfWriter.CloseStream = false;
                    pdfWriter.PageEvent   = new PrintHeaderFooter {
                        Title = pageTitle
                    };
                    pdfDocument.Open();

                    // register all fonts in current computer
                    FontFactory.RegisterDirectories();


                    // Set factories
                    var htmlContext = new HtmlPipelineContext(null);
                    htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                    // Set css
                    ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                    cssResolver.AddCssFile(HttpContext.Current.Server.MapPath(linkCss), true);
                    cssResolver.AddCss(".shadow {background-color: #ebdddd; }", true);


                    //Export
                    IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDocument, pdfWriter)));

                    using (var xmlString = new StringReader(htmlText))
                    {
                        var worker   = new XMLWorker(pipeline, true);
                        var xmlParse = new XMLParser(true, worker);
                        xmlParse.Parse(xmlString);
                        xmlParse.Flush();
                    }
                }

                renderedBuffer = new byte[outputMemoryStream.Position];
                outputMemoryStream.Position = 0;
                outputMemoryStream.Read(renderedBuffer, 0, renderedBuffer.Length);
            }
            return(renderedBuffer);
        }
コード例 #14
0
ファイル: BasePdfResult.cs プロジェクト: xtjatswc/FlexibleMVC
 private static void HtmlToPdf(StringBuilder sbHtml, HttpResponseBase httpResponse)
 {
     using (Document document = new Document(PageSize.A4, 4, 4, 4, 4))
     {
         using (PdfWriter pdfWriter = PdfWriter.GetInstance(document, httpResponse.OutputStream))
         {
             document.Open();
             FontFactory.RegisterDirectories();//注册系统中所支持的字体
             XMLWorkerHelper worker = XMLWorkerHelper.GetInstance();
             //UnicodeFontFactory 自定义实现解决itextsharp.xmlworker 不支持中文的问题
             string html = sbHtml.ToString();
             worker.ParseXHtml(pdfWriter, document, new MemoryStream(Encoding.UTF8.GetBytes(html)), null, Encoding.UTF8, new UnicodeFontFactory());
             document.Close();
         }
     }
 }
コード例 #15
0
        public static void SaveDataGridViewToPDF(DataGridView Dv, string FilePath)
        {
            FontFactory.RegisterDirectories();
            iTextSharp.text.Font myfont = FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
            Document             pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

            pdfDoc.Open();
            PdfWriter wri = PdfWriter.GetInstance(pdfDoc, new FileStream(FilePath + "DataGridViewExport.pdf", FileMode.Create));

            pdfDoc.Open();
            PdfPTable _mytable = new PdfPTable(Dv.ColumnCount - 1);

            for (int j = 0; j < Dv.Columns.Count; ++j)
            {
                if (Dv.Columns[j].HeaderText != "CODIGO")
                {
                    Phrase   p    = new Phrase(Dv.Columns[j].HeaderText, myfont);
                    PdfPCell cell = new PdfPCell(p);
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.RunDirection        = PdfWriter.RUN_DIRECTION_RTL;
                    _mytable.AddCell(cell);
                }
            }
            //-------------------------
            for (int i = 0; i < Dv.Rows.Count - 1; ++i)
            {
                for (int j = 0; j < Dv.Columns.Count; ++j)
                {
                    if (Dv.Columns[j].HeaderText != "CODIGO")
                    {
                        Phrase   p    = new Phrase(Dv.Rows[i].Cells[j].Value.ToString(), myfont);
                        PdfPCell cell = new PdfPCell(p);
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.RunDirection        = PdfWriter.RUN_DIRECTION_RTL;
                        _mytable.AddCell(cell);
                    }
                }
            }
            //------------------------
            pdfDoc.Add(_mytable);
            pdfDoc.Close();
            System.Diagnostics.Process.Start(FilePath);
        }
コード例 #16
0
        protected string kreirajPDF()
        {
            Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
            //putanja je hardkodirana
            string fullPath     = @"C:\Pdf\Ponuda" + Session["korIme"].ToString() + ".pdf";
            int    count        = 1;
            string fileNameOnly = Path.GetFileNameWithoutExtension(fullPath);
            string extension    = Path.GetExtension(fullPath);
            string path         = Path.GetDirectoryName(fullPath);
            string newFullPath  = fullPath;

            while (File.Exists(newFullPath))
            {
                string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
                newFullPath = Path.Combine(path, tempFileName + extension);
                fullPath    = newFullPath;
            }

            FontFactory.RegisterDirectories();
            Font fontBoldArial = new Font(FontFactory.GetFont("Arial", 16, Font.BOLD));

            FontFactory.RegisterDirectories();
            Font fontBoldArial12 = new Font(FontFactory.GetFont("Arial", 12, Font.BOLD));

            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(fullPath, FileMode.Create));

            doc.Open();

            //putanja je hardkodirana
            string imagepath = @"C:\Users\Luka\Desktop\HopSamonikBlazek\E-nabava\E-nabava\img\logo.png";

            iTextSharp.text.Image slika = iTextSharp.text.Image.GetInstance(imagepath);
            slika.Alignment = Element.ALIGN_CENTER;
            doc.Add(slika);

            Paragraph naslov = new Paragraph("Kreirana ponuda za Metalsku industriju Varazdin d.d.\n", fontBoldArial);

            naslov.Alignment = Element.ALIGN_CENTER;
            doc.Add(naslov);

            DateTime izdavanje = DateTime.Now;

            Baza   baza    = new Baza();
            string naziv   = baza.DohvatiVrijednost("SELECT naziv FROM korisnici WHERE korisnicko_ime ='" + Session["korIme"] + "'");
            string brojTel = baza.DohvatiVrijednost("SELECT broj_telefona FROM korisnici WHERE korisnicko_ime ='" + Session["korIme"] + "'");
            string email   = baza.DohvatiVrijednost("SELECT email FROM korisnici WHERE korisnicko_ime ='" + Session["korIme"] + "'");


            Paragraph gore = new Paragraph("Podaci o izdavacu: \n", fontBoldArial12);

            doc.Add(gore);

            Paragraph paragraph = new Paragraph(
                "Ponuda od " + Session["korIme"] + "\n" +
                "Izdao: " + naziv + "\n" +
                "Korisnicko ime izdavaca: " + Session["korIme"] + "\n" +
                "Email: " + email + "\n" +
                "Broj telefona: " + brojTel + "\n" +
                "Datum izdavanja: " + izdavanje + "\n\n");

            doc.Add(paragraph);


            Paragraph naslovStavke = new Paragraph("Stavke ponude: \n\n", fontBoldArial);

            naslovStavke.Alignment = Element.ALIGN_CENTER;
            doc.Add(naslovStavke);

            PdfPTable table = new PdfPTable(10);

            table.AddCell(new Phrase("Red. br."));
            table.AddCell(new Phrase("Artikl"));
            table.AddCell(new Phrase("Kol"));
            table.AddCell(new Phrase("Cijena"));
            table.AddCell(new Phrase("Rok placanja"));
            table.AddCell(new Phrase("Rok isporuke"));
            table.AddCell(new Phrase("Nacin placanja"));
            table.AddCell(new Phrase("Kvaliteta"));
            table.AddCell(new Phrase("Napomena"));
            table.AddCell(new Phrase("Alt"));
            table.HeaderRows = 1;

            float[] widths = new float[] { 1f, 3f, 1f, 2f, 2f, 2f, 2f, 2f, 2f, 1f };
            table.SetWidths(widths);

            for (int i = 0; i < gwPonuda.Rows.Count; i++)
            {
                table.AddCell(new Phrase((i + 1).ToString()));

                for (int j = 1; j < 10; j++)
                {
                    table.AddCell(new Phrase(gwPonuda.Rows[i].Cells[j].Text));
                }

                /*table.AddCell(new Phrase(gwPonuda.Rows[i].Cells[1].Text));
                *  table.AddCell(new Phrase(gwPonuda.Rows[i].Cells[2].Text));
                *  table.AddCell(new Phrase(gwPonuda.Rows[i].Cells[3].Text));
                *  table.AddCell(new Phrase(gwPonuda.Rows[i].Cells[4].Text));
                *  table.AddCell(new Phrase(gwPonuda.Rows[i].Cells[5].Text));
                *  table.AddCell(new Phrase(gwPonuda.Rows[i].Cells[6].Text));
                *  table.AddCell(new Phrase(gwPonuda.Rows[i].Cells[7].Text));
                *  table.AddCell(new Phrase(gwPonuda.Rows[i].Cells[8].Text));
                *  table.AddCell(new Phrase(gwPonuda.Rows[i].Cells[9].Text));*/

                table.WidthPercentage = 100;
            }
            doc.Add(table);
            doc.Close();
            return(fullPath);
        }
コード例 #17
0
        protected string kreirajPDF(int idProjekta)
        {
            Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
            //putanja je hardkodirana
            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(@"C:\Pdf\Investicijski_projekt_ALT" + idProjekta + ".pdf", FileMode.Create));

            doc.Open();

            FontFactory.RegisterDirectories();
            Font fontBoldArial = new Font(FontFactory.GetFont("Arial", 16, Font.BOLD));

            FontFactory.RegisterDirectories();
            Font fontBoldArial12 = new Font(FontFactory.GetFont("Arial", 12, Font.BOLD));

            //putanja je hardkodirana
            string imagepath = @"C:\Users\Luka\Desktop\HopSamonikBlazek\E-nabava\E-nabava\img\logo.png";

            iTextSharp.text.Image slika = iTextSharp.text.Image.GetInstance(imagepath);
            slika.Alignment = Element.ALIGN_CENTER;
            doc.Add(slika);

            Paragraph naslov = new Paragraph("Alternativa investicijskog projekta za Metalsku industriju Varazdin d.d.\n\n", fontBoldArial);

            naslov.Alignment = Element.ALIGN_CENTER;
            doc.Add(naslov);

            DateTime izdavanje = DateTime.Now;

            Paragraph gore = new Paragraph("Podaci o izmjenjenom investicijskom projektu: \n\n", fontBoldArial12);

            Paragraph paragraph = new Paragraph(
                "Naziv projekta: " + txtNazivProjekta.Text + "\n" +
                "Opis projekta: " + txtOpisProjekta.Text + "\n" +
                "Izdao: " + Session["korIme"] + "\n" +
                "Datum izdavanja: " + izdavanje + "\n" +
                "Rok: " + txtRokProjekta.Text + "\n\n");

            string stariNaziv = baza.DohvatiVrijednost("SELECT naziv FROM investicijski_projekt WHERE id_inv_projekt=" + txtIDProjekta.Text);
            string stariOpis  = baza.DohvatiVrijednost("SELECT projekt FROM investicijski_projekt WHERE id_inv_projekt=" + txtIDProjekta.Text);
            string stariIzdao = baza.DohvatiVrijednost("SELECT izdao FROM investicijski_projekt WHERE id_inv_projekt=" + txtIDProjekta.Text);
            string stariRok   = baza.DohvatiVrijednost("SELECT rok FROM investicijski_projekt WHERE id_inv_projekt=" + txtIDProjekta.Text);

            Paragraph gore2 = new Paragraph("Podaci o starom investicijskom projektu: \n\n", fontBoldArial12);

            Paragraph paragraph2 = new Paragraph(
                "Investicijski_projekt" + txtIDProjekta.Text + "\n" +
                "Naziv projekta: " + stariNaziv + "\n" +
                "Opis projekta: " + stariOpis + "\n" +
                "Izdao: " + stariIzdao + "\n" +
                "Rok: " + stariRok + "\n\n");

            PdfPCell cell = new PdfPCell();

            cell.AddElement(gore);
            cell.AddElement(paragraph);
            cell.Padding = 0;
            cell.Border  = PdfPCell.NO_BORDER;

            PdfPCell cellPRazna = new PdfPCell(new Phrase(""));

            cellPRazna.Padding = 0;
            cellPRazna.Border  = PdfPCell.NO_BORDER;


            PdfPCell cell2 = new PdfPCell();

            cell2.AddElement(gore2);
            cell2.AddElement(paragraph2);
            cell2.Padding = 0;
            cell2.Border  = PdfPCell.NO_BORDER;

            float[]   sirine = new float[] { 3f, 1f, 3f };
            PdfPTable opisi  = new PdfPTable(3);

            opisi.SetWidths(sirine);
            opisi.WidthPercentage = 100;
            opisi.AddCell(cell);
            opisi.AddCell(cellPRazna);
            opisi.AddCell(cell2);
            doc.Add(opisi);


            Paragraph naslovStavke = new Paragraph("Stavke projekta: \n\n", fontBoldArial);

            naslovStavke.Alignment = Element.ALIGN_CENTER;
            doc.Add(naslovStavke);

            PdfPTable table = new PdfPTable(6);

            float[] widths = new float[] { 1f, 6f, 2f, 2f, 2f, 2f };
            table.SetWidths(widths);
            table.AddCell(new Phrase("Red. br."));
            table.AddCell(new Phrase("Opis stavke"));
            table.AddCell(new Phrase("Jed. mj."));
            table.AddCell(new Phrase("Kolicina"));
            table.AddCell(new Phrase("Jed. cijena(kn)"));
            table.AddCell(new Phrase("Iznos (kn)"));
            table.HeaderRows      = 1;
            table.WidthPercentage = 100;
            double ukupno = 0;

            for (int i = 0; i < gwProjekt.Rows.Count; i++)
            {
                table.AddCell(new Phrase((i + 1).ToString()));
                table.AddCell(new Phrase(gwProjekt.Rows[i].Cells[1].Text));
                table.AddCell(new Phrase(gwProjekt.Rows[i].Cells[2].Text));
                table.AddCell(new Phrase(gwProjekt.Rows[i].Cells[3].Text));
                table.AddCell(new Phrase(gwProjekt.Rows[i].Cells[4].Text));
                float iznos = float.Parse(gwProjekt.Rows[i].Cells[3].Text) * float.Parse(gwProjekt.Rows[i].Cells[4].Text);
                table.AddCell(new Phrase(iznos.ToString()));
                ukupno += iznos;
            }

            doc.Add(table);

            double    pdv        = ukupno * 0.25;
            double    sveukupno  = ukupno + pdv;
            Paragraph paragraph1 = new Paragraph(
                "\nUkupno: " + ukupno + " kn\n" +
                "PDV 25%: " + pdv + " kn\n" +
                "Sveukupno: " + sveukupno + " kn\n");

            doc.Add(paragraph1);
            doc.Close();

            return(@"C:\Pdf\Investicijski_projekt_ALT" + idProjekta + ".pdf");
        }
コード例 #18
0
    public static void PDF(string VisitaId)
    {
        var Bpdf    = Database.Open("IDDVisitas");
        var DataPDF = Bpdf.QuerySingle(@"SELECT * FROM [Visitantes] WHERE IdVisita = @0", VisitaId);

        Bpdf.Close();

        // Creamos el documento con el tamaño de página tradicional
        Document doc = new Document(iTextSharp.text.PageSize.LETTER, 11, 11, 5, 5);
        // Indicamos donde vamos a guardar el documento
        //Path.Combine(Server.MapPath)
        FileStream fs2    = new FileStream(Path.Combine(HttpContext.Current.Server.MapPath(@"~/PDF/IDDVisitas.pdf")), FileMode.Create, FileAccess.Write, FileShare.None);
        PdfWriter  writer = PdfWriter.GetInstance(doc, fs2);

        writer.Open();
        doc.Open();
        var content = writer.DirectContent;
        var page    = new Rectangle(doc.PageSize);

        page.Left   += doc.LeftMargin;
        page.Right  -= doc.RightMargin;
        page.Top    -= doc.TopMargin;
        page.Bottom += doc.BottomMargin;
        FontFactory.RegisterDirectories();
        Font fuente      = FontFactory.GetFont("Times New Roman");
        Font letraBlanca = FontFactory.GetFont("Times New Roman");

        letraBlanca.SetColor(255, 255, 255);
        Font letraVerde = FontFactory.GetFont("Times New Roman");

        letraVerde.SetColor(0, 153, 51);
        Font letraRoja = FontFactory.GetFont("Times New Roman");

        letraRoja.SetColor(255, 0, 0);
        Font negrita = FontFactory.GetFont("Times New Roman", 11, Font.BOLD);
        Font cursiva = FontFactory.GetFont("Times New Roman", 11, Font.ITALIC);
        Font ambos   = FontFactory.GetFont("Times New Roman", Font.BOLD, Font.ITALIC);

        iTextSharp.text.Image IM = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath(@"~/img/EncabezadoDePDF.png"));
        IM.BorderWidth = 0;
        IM.Alignment   = Element.ALIGN_CENTER;

        PdfPTable tablaEncabezado = new PdfPTable(1);

        tablaEncabezado.WidthPercentage = 95;
        tablaEncabezado.TotalWidth      = page.Width - 65;
        tablaEncabezado.LockedWidth     = true;
        tablaEncabezado.SetWidths(new float[] { 1f });
        PdfPCell celdaEncabezado = new PdfPCell(IM, true);

        IM.WidthPercentage = 100;
        tablaEncabezado.AddCell(celdaEncabezado);
        doc.Add(tablaEncabezado);

        /*TABLA SECCION1*/
        PdfPTable tableSeccion1 = new PdfPTable(1);

        tableSeccion1.WidthPercentage = 95;
        tableSeccion1.TotalWidth      = page.Width - 65;
        tableSeccion1.LockedWidth     = true;
        tableSeccion1.SetWidths(new float[] { 1f });
        Phrase   titulo1     = new Phrase("SECCION 1: COMPLETADA POR VISITANTE O POR ANFITRION ZLS ESTORNUDA CON MOCASINO", letraBlanca);
        PdfPCell celdaTitulo = new PdfPCell(new Phrase(titulo1));

        celdaTitulo.BackgroundColor = new BaseColor(0, 85, 128);
        tableSeccion1.AddCell(celdaTitulo);
        doc.Add(tableSeccion1);

        /*PRIMERA TABLA*/
        PdfPTable table1 = new PdfPTable(3);

        table1.WidthPercentage = 95;
        table1.TotalWidth      = page.Width - 65;
        table1.LockedWidth     = true;
        table1.SetWidths(new float[] { 2f, 1f, 1.25f });
        Phrase Unot1 = new Phrase("Nombre del Anfitrion Empleado de ZLS: ", fuente);

        Unot1.Add(new Phrase(new Chunk(DataPDF["nombreEmple"] + " " + DataPDF["apellido1"] + " " + DataPDF["apellido2"] + " " + "(" + DataPDF["No.Empleado_Requi"] + ")")));
        Phrase Unot2 = new Phrase("Num. de telefono: ", fuente);

        Unot2.Add(new Phrase(new Chunk(DataPDF["No.Telefono"])));
        Phrase Unot3 = new Phrase("Fecha: ", fuente);

        Unot3.Add(new Phrase(new Chunk(returnString(DataPDF["Fecha_requi"]))));
        PdfPCell celdaT1 = new PdfPCell(Unot1);
        PdfPCell celdaT2 = new PdfPCell(Unot2);
        PdfPCell celdaT3 = new PdfPCell(Unot3);

        table1.AddCell(celdaT1);
        table1.AddCell(celdaT2);
        table1.AddCell(celdaT3);
        doc.Add(table1);

        /*SEGUNDA TABLA*/
        PdfPTable table2 = new PdfPTable(1);

        table2.WidthPercentage = 95;
        table2.TotalWidth      = page.Width - 65;
        table2.LockedWidth     = true;
        table2.SetWidths(new float[] { 1f });
        Phrase Dost2 = new Phrase("Nombre completo del visitante: ", fuente);

        Dost2.Add(new Phrase(new Chunk(DataPDF["Nombre_Visitante"])));
        PdfPCell celdaUnoT1 = new PdfPCell(new Phrase(Dost2));

        table2.AddCell(celdaUnoT1);
        doc.Add(table2);


        /*TERCERA TABLA*/
        PdfPTable table3 = new PdfPTable(2);

        table3.WidthPercentage = 95;
        table3.TotalWidth      = page.Width - 65;
        table3.LockedWidth     = true;
        table3.SetWidths(new float[] { 1f, 1f });
        Phrase tresT1 = new Phrase("Estatus de ciudadania o pais de residencia permanente: ", fuente);

        tresT1.Add(new Phrase(new Chunk(DataPDF["Estatus_ciudadania"])));
        Phrase tresT2 = new Phrase("Identificacion verificada: ", fuente);

        if (DataPDF["Identificacion_verificada"])
        {
            tresT2.Add(new Phrase(new Chunk("Identificacion verificada")));
        }
        else
        {
            tresT2.Add(new Phrase(new Chunk("Identificacion NO verificada")));
        }
        PdfPCell celdaTresT1 = new PdfPCell(new Phrase(tresT1));
        PdfPCell celdaTresT2 = new PdfPCell(new Phrase(tresT2));

        table3.AddCell(celdaTresT1);
        table3.AddCell(celdaTresT2);
        doc.Add(table3);

        /*CUARTA TABLA*/
        PdfPTable table4 = new PdfPTable(2);

        table4.WidthPercentage = 95;
        table4.TotalWidth      = page.Width - 65;
        table4.LockedWidth     = true;
        table4.SetWidths(new float[] { 1f, 1f });
        Phrase cuatroT1 = new Phrase("Nombre de la compania: ", fuente);

        cuatroT1.Add(new Phrase(new Chunk(DataPDF["Nombre_compania"])));
        Phrase cuatroT2 = new Phrase("Ciudad, estado (compania o residencia): ", fuente);

        cuatroT2.Add(new Phrase(new Chunk(DataPDF["Ciudad"])));
        PdfPCell celdaCuatroT1 = new PdfPCell(new Phrase(cuatroT1));
        PdfPCell celdaCuatroT2 = new PdfPCell(new Phrase(cuatroT2));

        table4.AddCell(celdaCuatroT1);
        table4.AddCell(celdaCuatroT2);
        doc.Add(table4);

        /*QUINTA TABLA*/
        PdfPTable table5 = new PdfPTable(3);

        table5.WidthPercentage = 95;
        table5.TotalWidth      = page.Width - 65;
        table5.LockedWidth     = true;
        table5.SetWidths(new float[] { 1.25f, 1f, 1f });
        Phrase cincoT1 = new Phrase("Fecha(s) de la visita: ", fuente);

        cincoT1.Add(new Phrase(new Chunk(returnString(DataPDF["Fecha_inicio_Visita"]))));
        Phrase cincoT2 = new Phrase("Hasta: ", fuente);

        if (DataPDF["Fecha_final_Visita"] == null)
        {
            cincoT2.Add(new Phrase(new Chunk("No aplica una fecha final")));
        }
        else
        {
            cincoT2.Add(new Phrase(new Chunk(returnString(DataPDF["Fecha_final_Visita"]))));
        }
        Phrase cincoT3 = new Phrase();

        if (!DataPDF["Abierto"])
        {
            cincoT3.Add(new Phrase(new Chunk("Terminado")));
        }
        else
        {
            cincoT3.Add(new Phrase(new Chunk("Abierto")));
        }
        PdfPCell celdaCincoT1 = new PdfPCell(new Phrase(cincoT1));
        PdfPCell celdaCincoT2 = new PdfPCell(new Phrase(cincoT2));
        PdfPCell celdaCincoT3 = new PdfPCell(new Phrase(cincoT3));

        table5.AddCell(celdaCincoT1);
        table5.AddCell(celdaCincoT2);
        table5.AddCell(celdaCincoT3);
        doc.Add(table5);

        /*SEXTA TABLA*/
        PdfPTable table6 = new PdfPTable(1);

        table6.WidthPercentage = 95;
        table6.TotalWidth      = page.Width - 65;
        table6.LockedWidth     = true;
        table6.SetWidths(new float[] { 1f });
        Phrase seisT1 = new Phrase("Explicar proposito de la visita: ", fuente);

        seisT1.Add(new Phrase(new Chunk(DataPDF["Proposito_Visita"])));
        PdfPCell celdaSeisT1 = new PdfPCell(new Phrase(seisT1));

        table6.AddCell(celdaSeisT1);
        doc.Add(table6);

        /*SEPTIMA TABLA*/
        PdfPTable table7 = new PdfPTable(1);

        table7.WidthPercentage = 95;
        table7.TotalWidth      = page.Width - 65;
        table7.LockedWidth     = true;
        table7.SetWidths(new float[] { 1f });
        Phrase sieteT1 = new Phrase("Empleados de ZLS a ser visitados: ", fuente);

        sieteT1.Add(new Phrase(new Chunk(DataPDF["Empleados_Visitados"])));
        PdfPCell celdaSieteT1 = new PdfPCell(new Phrase(sieteT1));

        table7.AddCell(celdaSieteT1);
        doc.Add(table7);

        /*OCTAVA TABLA*/
        PdfPTable table8 = new PdfPTable(1);

        table8.WidthPercentage = 95;
        table8.TotalWidth      = page.Width - 65;
        table8.LockedWidth     = true;
        table8.SetWidths(new float[] { 1f });
        Phrase   ochoT1      = new Phrase("Areas de IDD por visitar: ", fuente);
        Phrase   Admin       = new Phrase("-Administrativo", fuente);
        Phrase   Inge        = new Phrase("-Ingenieria", fuente);
        Phrase   Fabri       = new Phrase("-Fabrica", fuente);
        Phrase   Otross      = new Phrase("-" + DataPDF["Otro"], fuente);
        PdfPCell celdaOchoT1 = new PdfPCell();

        celdaOchoT1.AddElement(new Phrase(ochoT1));
        if (DataPDF["Administrativo"])
        {
            celdaOchoT1.AddElement(new Phrase(Admin));
        }
        if (DataPDF["Ingenieria"])
        {
            celdaOchoT1.AddElement(new Phrase(Inge));
        }
        if (DataPDF["Fabrica"])
        {
            celdaOchoT1.AddElement(new Phrase(Fabri));
        }
        if (DataPDF["Otro"] != "")
        {
            celdaOchoT1.AddElement(new Phrase(Otross));
        }
        table8.AddCell(celdaOchoT1);
        doc.Add(table8);

        /*NOVENA TABLA*/
        PdfPTable table9 = new PdfPTable(1);

        table9.WidthPercentage = 95;
        table9.TotalWidth      = page.Width - 65;
        table9.LockedWidth     = true;
        table9.SetWidths(new float[] { 1f });
        Phrase   nueveT1      = new Phrase("Por favor lea y complete la sección de abajo", negrita);
        PdfPCell celdaNueveT1 = new PdfPCell(new Phrase(nueveT1));

        table9.AddCell(celdaNueveT1);
        doc.Add(table9);

        /*DECIMA TABLA*/
        PdfPTable table10 = new PdfPTable(1);

        table10.WidthPercentage = 95;
        table10.TotalWidth      = page.Width - 65;
        table10.LockedWidth     = true;
        table10.SetWidths(new float[] { 1f });
        Phrase diezT1 = new Phrase("El/los anfitrión(es) de ZLS entienden que él/ella es responsable de salvaguardar y gestionar adecuadamente cualquier divulgación de" +
                                   " información técnica según las Políticas y Procedimientos de Control de Exportaciones de ZLS. ", fuente);

        diezT1.Add(new Phrase(new Chunk("Favor de llenar la sección de abajo.", cursiva)));
        PdfPCell celdaDiezT1 = new PdfPCell(new Phrase(diezT1));

        table10.AddCell(celdaDiezT1);
        doc.Add(table10);

        /*ONCEAVA TABLA*/
        PdfPTable table11 = new PdfPTable(1);

        table11.WidthPercentage = 95;
        table11.TotalWidth      = page.Width - 65;
        table11.LockedWidth     = true;
        table11.SetWidths(new float[] { 1f });
        Phrase onceT1 = new Phrase("¿Exportara la información  técnica controlada será analizada y/o divulgada? ", fuente);

        if (DataPDF["Exportara_informacion"])
        {
            onceT1.Add(new Phrase(new Chunk("Si")));
        }
        else
        {
            onceT1.Add(new Phrase(new Chunk("No")));
        }
        PdfPCell celdaOnceT1 = new PdfPCell(new Phrase(onceT1));

        table11.AddCell(celdaOnceT1);
        doc.Add(table11);

        /*DOCEAVA TABLA*/
        PdfPTable table12 = new PdfPTable(1);

        table12.WidthPercentage = 95;
        table12.TotalWidth      = page.Width - 65;
        table12.LockedWidth     = true;
        table12.SetWidths(new float[] { 1f });
        Phrase   doceT1     = new Phrase("En caso de contestar si, favor de revisar con Control de Exportaciones de ZLS para saber si tiene una licencia de exportación que cubra el propósito específico de esta visita", fuente);
        PdfPCell celdDoceT1 = new PdfPCell(new Phrase(doceT1));

        table12.AddCell(celdDoceT1);
        doc.Add(table12);

        /*TRECEAVA TABLA*/
        PdfPTable table13 = new PdfPTable(2);

        table13.WidthPercentage = 95;
        table13.TotalWidth      = page.Width - 65;
        table13.LockedWidth     = true;
        table13.SetWidths(new float[] { 1.50f, 1f });
        Phrase treceT1 = new Phrase("En caso de ser Si, proveer  Num de licencia: ", fuente);

        if (DataPDF["No.Licencia_control_exportaciones"] != null)
        {
            treceT1.Add(new Phrase(DataPDF["No.Licencia_control_exportaciones"]));
        }
        else
        {
            treceT1.Add(new Phrase("No aplica"));
        }
        Phrase treceT2 = new Phrase("Fecha de expiracion: ", fuente);

        if (DataPDF["Fecha_expiracion_licencia"] == null)
        {
            treceT2.Add(new Phrase(new Chunk("No aplica")));
        }
        else
        {
            treceT2.Add(new Phrase(new Chunk(returnString(DataPDF["Fecha_expiracion_licencia"]))));
        }
        PdfPCell celdaTreceT1 = new PdfPCell(new Phrase(treceT1));
        PdfPCell celdaTreceT2 = new PdfPCell(new Phrase(treceT2));

        table13.AddCell(celdaTreceT1);
        table13.AddCell(celdaTreceT2);
        doc.Add(table13);

        /*TABLA SECCION2*/
        PdfPTable tableSeccion2 = new PdfPTable(1);

        tableSeccion2.WidthPercentage = 95;
        tableSeccion2.TotalWidth      = page.Width - 65;
        tableSeccion2.LockedWidth     = true;
        tableSeccion2.SetWidths(new float[] { 1f });
        Phrase   titulo_1     = new Phrase("SECCION 2: COMPLETADA POR VISITANTE O POR ANFITRION ZLS", letraBlanca);
        PdfPCell celda_Titulo = new PdfPCell(new Phrase(titulo_1));

        celda_Titulo.BackgroundColor = new BaseColor(0, 85, 128);
        tableSeccion2.AddCell(celda_Titulo);
        doc.Add(tableSeccion2);

        /*TABLA UNO*/
        PdfPTable table_1 = new PdfPTable(2);

        table_1.WidthPercentage = 95;
        table_1.TotalWidth      = page.Width - 65;
        table_1.LockedWidth     = true;
        table_1.SetWidths(new float[] { 1f, 1f });
        Phrase UnoT_1 = new Phrase("Nombre del revisor: ", fuente);

        UnoT_1.Add(new Phrase(new Chunk(DataPDF["NombreAprobador"] + " " + DataPDF["Apellido1Apro"] + " " + DataPDF["Apellido2Apro"] + " " + "(" + DataPDF["No.Empleado_Aprobador"] + ")")));
        Phrase UnoT_2 = new Phrase("Fecha de investigacion: ", fuente);

        UnoT_2.Add(new Phrase(new Chunk(returnString(DataPDF["Fecha_investigacion"]))));
        PdfPCell celda_UnoT1 = new PdfPCell(new Phrase(UnoT_1));
        PdfPCell celda_UnoT2 = new PdfPCell(new Phrase(UnoT_2));

        table_1.AddCell(celda_UnoT1);
        table_1.AddCell(celda_UnoT2);
        doc.Add(table_1);

        if (DataPDF["Aprobado"])
        {
            /*TABLE DOS*/
            PdfPTable table_2 = new PdfPTable(1);
            table_2.WidthPercentage = 95;
            table_2.TotalWidth      = page.Width - 65;
            table_2.LockedWidth     = true;
            table_2.SetWidths(new float[] { 1f });
            Phrase   DosT_1      = new Phrase("PASA El Anfitrión de ZLS provee el tipo de credencial apropiada. Las personas extranjeras (incluidos los empleados de Zodiac) no están autorizadas a ir a zonas de exportación controladas. Notifique a los supervisores antes de cualquier recorrido de la compañía para permitir el suficiente tiempo para retirar/cubrir los artículos controlados.", letraVerde);
            PdfPCell celda_DosT1 = new PdfPCell(new Phrase(DosT_1));
            table_2.AddCell(celda_DosT1);
            doc.Add(table_2);

            /*TABLA TRES*/
            PdfPTable table_3 = new PdfPTable(1);
            table_3.WidthPercentage = 95;
            table_3.TotalWidth      = page.Width - 65;
            table_3.LockedWidth     = true;
            table_3.SetWidths(new float[] { 1f });
            Phrase   TresT_1      = new Phrase("Credencial autorizada: ", fuente);
            Phrase   AR           = new Phrase("- “V” Acompañante Requerido", fuente);
            Phrase   VC           = new Phrase("- “A” Vendedor/Contratista Aprobado (Sin Acompañante)", fuente);
            Phrase   Ex           = new Phrase("- “FN” Extranjero, Acompañante Requerido ", fuente);
            Phrase   Otros        = new Phrase("-" + DataPDF["Otra_credencial"], fuente);
            PdfPCell celda_TresT1 = new PdfPCell();

            celda_TresT1.AddElement(new Phrase(TresT_1));
            if (DataPDF["Acompanante_requerido"])
            {
                celda_TresT1.AddElement(new Phrase(AR));
            }
            if (DataPDF["Vendedor_contratista"])
            {
                celda_TresT1.AddElement(new Phrase(VC));
            }
            if (DataPDF["Extranjero"])
            {
                celda_TresT1.AddElement(new Phrase(Ex));
            }
            if (DataPDF["Otra_credencial"] != "")
            {
                celda_TresT1.AddElement(new Phrase(Otros));
            }

            table_3.AddCell(celda_TresT1);
            doc.Add(table_3);
        }
        else
        {
            /*TABLA CUATRO*/
            PdfPTable table_4 = new PdfPTable(1);
            table_4.WidthPercentage = 95;
            table_4.TotalWidth      = page.Width - 65;
            table_4.LockedWidth     = true;
            table_4.SetWidths(new float[] { 1f });
            Phrase   CuatroT_1      = new Phrase("NO PASA NO SE LE PERMITE al Visitante ir más allá del vestíbulo de la planta.", letraRoja);
            PdfPCell celda_CuatroT1 = new PdfPCell(new Phrase(CuatroT_1));
            table_4.AddCell(celda_CuatroT1);
            doc.Add(table_4);
        }

        PdfPTable pie = new PdfPTable(3);

        pie.WidthPercentage = 95;
        pie.TotalWidth      = page.Width - 65;
        pie.LockedWidth     = true;
        pie.SetWidths(new float[] { 1f, 1f, 1f });
        Phrase   pieTitulo1 = new Phrase("10/27/2017", cursiva);
        Phrase   pieFrase   = new Phrase("Formato de identificacion", cursiva);
        Phrase   pieFrase2  = new Phrase("Pagina 1", cursiva);
        PdfPCell celdaPie   = new PdfPCell(new Phrase(pieTitulo1));

        celdaPie.BorderWidth = 0;
        PdfPCell celdaPie2 = new PdfPCell(new Phrase(pieFrase));

        celdaPie2.BorderWidth = 0;
        PdfPCell celdaPie3 = new PdfPCell(new Phrase(pieFrase2));

        celdaPie3.BorderWidth = 0;
        pie.AddCell(celdaPie);
        pie.AddCell(celdaPie2);
        pie.AddCell(celdaPie3);
        doc.Add(pie);

        PdfPTable PIE2 = new PdfPTable(3);

        PIE2.WidthPercentage = 95;
        PIE2.TotalWidth      = page.Width - 65;
        PIE2.LockedWidth     = true;
        PIE2.SetWidths(new float[] { 1f, 1f, 1f });
        Phrase   frase11 = new Phrase("REV N", cursiva);
        Phrase   frase12 = new Phrase("EC-260", cursiva);
        Phrase   frase13 = new Phrase("N:/Formato de control de acceso de visitantesS", cursiva);
        PdfPCell celda11 = new PdfPCell(new Phrase(frase11));

        celda11.BorderWidth = 0;
        PdfPCell celda12 = new PdfPCell(new Phrase(frase12));

        celda12.BorderWidth = 0;
        PdfPCell celda13 = new PdfPCell(new Phrase(frase13));

        celda13.BorderWidth = 0;
        PIE2.AddCell(celda11);
        PIE2.AddCell(celda12);
        PIE2.AddCell(celda13);
        doc.Add(PIE2);


        /*Cerrar documento, escritor y filestream*/
        doc.Close();
        writer.Close();
        fs2.Close();

        /*Crear y descargar pdf*/
        HttpContext.Current.Response.TransmitFile(Path.Combine(HttpContext.Current.Server.MapPath(@"~/PDF/IDDVisitas.pdf")));
        HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=Visita.pdf");
        HttpContext.Current.Response.ContentType = "application/octet-stream";
        HttpContext.Current.Response.Flush();
        File.Delete(Path.Combine(HttpContext.Current.Server.MapPath(@"~/PDF/IDDVisitas.pdf")));
    }
コード例 #19
0
 public static void InitializeFontFactory()
 {
     FontFactory.RegisterDirectories();
 }
コード例 #20
0
 static Setup()
 {
     LoggerFactory.GetInstance().SetLogger(new SysoLogger());
     FontFactory.RegisterDirectories();
 }
コード例 #21
0
        public void getPdfPartitura(Partitura partitura)
        {
            if (!FontFactory.IsRegistered("Night-Braille"))
            {
                FontFactory.RegisterFamily("Night-Braille", "Night-Braille", @"C:\Windows\Fonts");
                FontFactory.RegisterDirectories();
            }
            Font fontBraille = FontFactory.GetFont("Night-Braille", 30, 0);

            if (!FontFactory.IsRegistered("LASSUS"))
            {
                FontFactory.RegisterFamily("LASSUS", "ttfNormal", @"C:\Windows\Fonts");
                FontFactory.RegisterDirectories();
            }
            Font fontPartitura = FontFactory.GetFont("LASSUS", 60, 0);
            Font fontArial     = FontFactory.GetFont("Arial", 15, 1);
            Font fontArial2    = FontFactory.GetFont("Arial", 15, 0);


            Document doc = new Document(iTextSharp.text.PageSize.A4, 20, 20, 20, 20);

            string exeFile  = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
            string exeDir   = Path.GetDirectoryName(exeFile);
            string fullPath = Path.Combine(exeDir, "..\\..\\pdf\\file.pdf");

            FileStream arquivo = new FileStream(fullPath, FileMode.Create);
            PdfWriter  writer  = PdfWriter.GetInstance(doc, arquivo);

            doc.Open();
            doc.AddAuthor("Cleiton de Sousa, Raphael Duarte, Douglas Rodrigues, e DEUS, só ele sabe como isso funciona");
            doc.AddCreator("Partitura Braille");
            doc.AddKeywords("PDF partitura Braille");
            doc.AddTitle(partitura.Titulo);


            Paragraph para = new Paragraph(new Phrase("Partitura: " + partitura.Titulo, fontArial));

            doc.Add(para);
            para = new Paragraph(new Phrase(partitura.TextoPartitura + "=", fontPartitura));
            doc.Add(para);
            para = new Paragraph(new Phrase(" ", fontArial));
            doc.Add(para);
            para = new Paragraph(new Phrase(" ", fontArial));
            doc.Add(para);
            para = new Paragraph(new Phrase(" ", fontArial));
            doc.Add(para);

            para = new Paragraph(new Phrase("Partitura: " + partitura.Titulo, fontBraille));
            doc.Add(para);
            para = new Paragraph(new Phrase(partitura.BraillePartitura, fontBraille));
            doc.Add(para);

            doc.NewPage();
            para = new Paragraph(new Phrase("Letra da Partitura: " + partitura.Titulo, fontArial));
            doc.Add(para);
            para = new Paragraph(new Phrase(" ", fontArial));
            doc.Add(para);
            para = new Paragraph(new Phrase(partitura.LetraPartitura, fontArial2));
            doc.Add(para);
            para = new Paragraph(new Phrase(" ", fontArial));
            doc.Add(para);
            para = new Paragraph(new Phrase(" ", fontArial));
            doc.Add(para);
            para = new Paragraph(new Phrase(" ", fontArial));
            doc.Add(para);
            para = new Paragraph(new Phrase(" ", fontArial));
            doc.Add(para);
            para = new Paragraph(new Phrase("Letra da Partitura em Braille: " + partitura.Titulo, fontBraille));
            doc.Add(para);
            para = new Paragraph(new Phrase(partitura.LetraPartitura, fontBraille));
            doc.Add(para);


            doc.Close();
            arquivo.Close();
            System.Diagnostics.Process.Start(fullPath);
        }
コード例 #22
0
        public void print()
        {
            string rpthtml = bindheader();
            // string rpthtml = "";
            string filename = System.DateTime.UtcNow.ToFileTimeUtc() + ".pdf";
            string html     = readHTML();

            html = rpthtml + html;
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "application/pdf";

            ////define pdf filename
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + filename);


            //Generate PDF
            using (var document = new Document(iTextSharp.text.PageSize.B4))
            {
                //define output control HTML
                var        memStream = new MemoryStream();
                TextReader xmlString = new StringReader(html);

                PdfWriter writer = PdfWriter.GetInstance(document, memStream);

                //open doc
                document.Open();

                // register all fonts in current computer
                FontFactory.RegisterDirectories();

                // Set factories
                var htmlContext = new HtmlPipelineContext(null);
                htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

                // Set css
                ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);



                //cssResolver.AddCss("th{background-color:#1caf9a;color:#ffffff;font-size:12px;padding:4px;}", true);
                cssResolver.AddCss("th{font-size:12px;padding:4px;color:#1caf9a;}", true);
                cssResolver.AddCss("td{font-size:12px;padding:4px;}", true);

                //  cssResolver.AddCss("table{border-left: solid 1px #dadada;border-top:solid 1px #ffffff;}", true);
                cssResolver.AddCss("img{display:none;}", true);
                cssResolver.AddCss("a{color:#1caf9a;font-size:12px;}", true);
                cssResolver.AddCss("h3{font-size:15px;float:right;text-align:right;width:20%;font-waight:bold;border:2px solid #1caf9a;}", true);
                cssResolver.AddCss("h2{font-size:16px;text-align:left;font-waight:bold;color:#1caf9a;}", true);
                cssResolver.AddCss("h5{font-size:12px;}", true);

                if (Session["css"] != null)
                {
                    if (Session["css"].ToString() == "invlist")
                    {
                        cssResolver.AddCss(".odd td{border-bottom:solid 1px #e0e0e0;padding:4px;}", true);
                        cssResolver.AddCss(".gridheader th{border-bottom:solid 1px #e0e0e0;}", true);
                        cssResolver.AddCss(".even td{border-bottom:solid 1px #e0e0e0;padding:4px;}", true);
                        cssResolver.AddCss(".bordercss{border-left:solid 1px #e0e0e0;}", true);
                        cssResolver.AddCss(".bordercss1{border-right:solid 1px #e0e0e0;}", true);
                    }
                    if (Session["css"].ToString() == "timeexp")
                    {
                        // cssResolver.AddCss(".aright{text-align:right;}", true);
                    }
                }



                // Export
                IPipeline pipeline = new CssResolverPipeline(cssResolver,
                                                             new HtmlPipeline(htmlContext,
                                                                              new PdfWriterPipeline(document, writer)));
                var worker   = new XMLWorker(pipeline, true);
                var xmlParse = new XMLParser(true, worker);
                xmlParse.Parse(xmlString);
                xmlParse.Flush();

                document.Close();
                document.Dispose();

                HttpContext.Current.Response.BinaryWrite(memStream.ToArray());
            }

            HttpContext.Current.Response.End();
            HttpContext.Current.Response.Flush();
        }
コード例 #23
0
// ===========================================================================
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                PdfWriter.GetInstance(document, stream);
                // step 3
                document.Open();
                // step 4
                Font font = FontFactory.GetFont("Times-Roman");
                document.Add(new Paragraph("Times-Roman", font));
                Font fontbold = FontFactory.GetFont("Times-Roman", 12, Font.BOLD);
                document.Add(new Paragraph("Times-Roman, Bold", fontbold));
                document.Add(Chunk.NEWLINE);
                FontFactory.Register("c:/windows/fonts/garabd.ttf", "my_bold_font");
                Font     myBoldFont = FontFactory.GetFont("my_bold_font");
                BaseFont bf         = myBoldFont.BaseFont;
                document.Add(new Paragraph(bf.PostscriptFontName, myBoldFont));
                String[][] name = bf.FullFontName;
                for (int i = 0; i < name.Length; i++)
                {
                    document.Add(new Paragraph(
                                     name[i][3] + " (" + name[i][0]
                                     + "; " + name[i][1] + "; " + name[i][2] + ")"
                                     ));
                }
                Font myBoldFont2 = FontFactory.GetFont("Garamond vet");
                document.Add(new Paragraph("Garamond Vet", myBoldFont2));
                document.Add(Chunk.NEWLINE);
                document.Add(new Paragraph("Registered fonts:"));
                FontFactory.RegisterDirectory(Utility.ResourceFonts);

/*
 *      string fontDirectory = Utility.ResourceFonts;
 *      FontFactory.RegisterDirectory(
 *        fontDirectory.Substring(0, fontDirectory.Length - 3
 *      ));
 */
                foreach (String f in FontFactory.RegisteredFonts)
                {
                    document.Add(new Paragraph(
                                     f, FontFactory.GetFont(f, "", BaseFont.EMBEDDED
                                                            )));
                }
                document.Add(Chunk.NEWLINE);
                Font cmr10 = FontFactory.GetFont("cmr10");
                cmr10.BaseFont.PostscriptFontName = "Computer Modern Regular";
                Font computerModern = FontFactory.GetFont(
                    "Computer Modern Regular", "", BaseFont.EMBEDDED
                    );
                document.Add(new Paragraph("Computer Modern", computerModern));
                document.Add(Chunk.NEWLINE);
                FontFactory.RegisterDirectories();
                foreach (String f in FontFactory.RegisteredFamilies)
                {
                    document.Add(new Paragraph(f));
                }
                document.Add(Chunk.NEWLINE);
                Font garamond = FontFactory.GetFont(
                    "garamond", BaseFont.WINANSI, BaseFont.EMBEDDED
                    );
                document.Add(new Paragraph("Garamond", garamond));
                Font garamondItalic = FontFactory.GetFont(
                    "Garamond", BaseFont.WINANSI, BaseFont.EMBEDDED, 12, Font.ITALIC
                    );
                document.Add(new Paragraph("Garamond-Italic", garamondItalic));
            }
        }
コード例 #24
0
        public void GenerarBoleta(List <IBoleta> ListaCabecera, List <TBoleta> ListaDetalle, string Ruta)
        {
            foreach (var cabecera in ListaCabecera)
            {
                var Detalles = ListaDetalle.Where(x => x.CodigoTrabajador == cabecera.CodigoTrabajador).ToList();

                using (Document oDocument = new Document())
                {
                    oDocument.SetPageSize(PageSize.A4.Rotate());
                    using (FileStream oFileStream = new FileStream(string.Format(@"{0}\{1}.pdf", Ruta, cabecera.CodigoTrabajador), FileMode.OpenOrCreate))
                    {
                        //Definimos la fuente y el tamaño
                        // BaseFont bfTimes = BaseFont.CreateFont(BaseFont., BaseFont.CP1252, false);
                        FontFactory.RegisterDirectories();
                        Font fontArialBold   = new Font(FontFactory.GetFont("Arial", 7, Font.BOLD));
                        Font fontArialNormal = new Font(FontFactory.GetFont("Arial", 7, Font.NORMAL));
                        // Font times = new Font(bfTimes, 7);
                        //-->

                        PdfWriter.GetInstance(oDocument, oFileStream);
                        oDocument.Open();

                        string rutaImagen = @"E:\BoletasPdf\Logo.png";
                        // Creamos la imagen y le ajustamos el tamaño
                        Image imagen = Image.GetInstance(rutaImagen);
                        imagen.BorderWidth = 0;
                        imagen.Alignment   = Element.ALIGN_LEFT;
                        float percentage = 0.0f;
                        percentage = 150 / imagen.Width;
                        imagen.ScalePercent(percentage * 100);
                        oDocument.Add(imagen);

                        PdfPTable Boleta = new PdfPTable(2);
                        //Medidas de la tabla
                        float[] medidaCeldas = { 303f, 500f };
                        Boleta.TotalWidth  = 803f;
                        Boleta.LockedWidth = true;
                        Boleta.SetWidths(medidaCeldas);

                        //8 columnas para la Primera Fila
                        PdfPTable PrimerFila = new PdfPTable(8);
                        //Medidas de columnas primera fila
                        float[] medidaPrimeraFila = { 40f, 40f, 30f, 247f, 70f, 100f, 60f, 216f };
                        PrimerFila.TotalWidth  = 803f;
                        PrimerFila.LockedWidth = true;
                        PrimerFila.SetWidths(medidaPrimeraFila);

                        //
                        PdfPCell cell;
                        //
                        cell = new PdfPCell(new Phrase("C. COSTO", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("CÓDIGO", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("TIPO", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("APELLIDOS Y NOMBRES", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("FECHA INGRESO", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("CÓDIGO AFP", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("L.E. / DNI", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("DOMICILIO", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);

                        //->Detalles Primera Fila
                        cell = new PdfPCell(new Phrase(String.Format(cabecera.CodCentroCosto), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.CodigoTrabajador), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.TipoPlanilla), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.DesTrabajador), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.FeIngreso.ToShortDateString()), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.Afp), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.NumeroDoc), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.Direccion), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        PrimerFila.AddCell(cell);
                        //->

                        //Segunda Fila
                        cell                     = new PdfPCell(PrimerFila);
                        cell.Colspan             = 2;
                        cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                        Boleta.AddCell(cell);


                        //10 columnas para la Primera Fila
                        PdfPTable SegundaFila = new PdfPTable(10);
                        //Medidas de columnas segunda fila
                        float[] medidaSegundaFila = { 150f, 50f, 50f, 100f, 100f, 100f, 95f, 30f, 75f, 53f };
                        SegundaFila.TotalWidth  = 803f;
                        SegundaFila.LockedWidth = true;
                        SegundaFila.SetWidths(medidaSegundaFila);

                        //---
                        cell = new PdfPCell(new Phrase("CARGO", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("D. TRAB", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("H. TRAB", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("REMUNER. BASICA", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("VAC. SALIDA", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("VAC. RETORNO", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("CARNET ESSALUD", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("EDAD", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("FECHA CESE", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("CONDICIÓN", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        //->Agregamos detalles de la segunda fila

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.CargoTrabajador), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.DiasTrabajados.ToString("###,##0.00")), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.HorasTrabajadas.ToString("###,##0.00")), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.SueldoBasico.ToString("###,##0.00")), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.FeSalidaVac.ToShortDateString()), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.FeIngresoVac.ToShortDateString()), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.Ips), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.Edad.ToString()), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.FeCese.ToShortDateString()), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(String.Format(cabecera.Situacion), fontArialNormal));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = Rectangle.RIGHT_BORDER;
                        SegundaFila.AddCell(cell);

                        //->


                        cell                     = new PdfPCell(SegundaFila);
                        cell.Colspan             = 2;
                        cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                        Boleta.AddCell(cell);
                        //------------------Tercera Fila
                        PdfPTable TerceraFila       = new PdfPTable(2);
                        float[]   medidaTerceraFila = { 303f, 500f };
                        TerceraFila.TotalWidth  = 803f;
                        TerceraFila.LockedWidth = true;
                        TerceraFila.SetWidths(medidaCeldas);

                        cell = new PdfPCell(new Phrase("REMUNERACIONES", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        TerceraFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("RETENCIONES", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER; //0=Left, 1=Centre, 2=Right
                        TerceraFila.AddCell(cell);

                        cell                     = new PdfPCell(TerceraFila);
                        cell.Colspan             = 2;
                        cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                        Boleta.AddCell(cell);
                        //-----------------------------------------------
                        //Cuarta Fila
                        PdfPTable CuartaFila = new PdfPTable(8);

                        float[] medidaCuartaFila = { 163f, 70f, 70f, 160f, 80f, 80f, 80f, 100f };
                        CuartaFila.TotalWidth  = 803f;
                        CuartaFila.LockedWidth = true;
                        CuartaFila.SetWidths(medidaCuartaFila);

                        //Aqui se insertan los detalles
                        cell = new PdfPCell(new Phrase("CONCEPTO", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        cell.Rowspan             = 2;
                        CuartaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("TIEMPO", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        cell.Rowspan             = 2;
                        CuartaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("MONTO", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.VerticalAlignment   = Element.ALIGN_MIDDLE;;
                        cell.Rowspan             = 2;
                        CuartaFila.AddCell(cell);

                        cell                     = new PdfPCell(new Phrase("CONCEPTO", fontArialBold));
                        cell.Rowspan             = 2;
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.VerticalAlignment   = Element.ALIGN_MIDDLE;;
                        CuartaFila.AddCell(cell);

                        //CUARTA SUB TABLA
                        cell = new PdfPCell(new Phrase("CUENTAS CORRIENTES", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Colspan             = 3;
                        CuartaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("DESCUENTO", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        CuartaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("CARGO", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        CuartaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("AMORTIZACIÓN", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        CuartaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("SALDO", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        CuartaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("MONTO", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        CuartaFila.AddCell(cell);


                        //->Detalles del cuerpo de la boleta
                        var DetallesRemuneraciones = Detalles.Where(x => x.TipoConcepto == "1").ToList();
                        var DetallesRetenciones    = Detalles.Where(x => x.TipoConcepto == "2").ToList();

                        int count = Detalles.Count;

                        for (int i = 0; i < Detalles.Count; i++)
                        {
                            if (i < DetallesRemuneraciones.Count)
                            {
                                cell = new PdfPCell(new Phrase(DetallesRemuneraciones[i].DesConcepto, fontArialNormal));
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                cell.Border = Rectangle.RIGHT_BORDER;
                                CuartaFila.AddCell(cell);

                                cell = new PdfPCell(new Phrase(string.Format(DetallesRemuneraciones[i].DiasHoras.ToString("###,##0.00")), fontArialNormal));
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                cell.Border = Rectangle.RIGHT_BORDER;
                                CuartaFila.AddCell(cell);

                                cell = new PdfPCell(new Phrase(string.Format(DetallesRemuneraciones[i].ImporteConcepto.ToString("###,##0.00")), fontArialNormal));
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                cell.Border = Rectangle.RIGHT_BORDER;
                                CuartaFila.AddCell(cell);
                            }
                            else
                            {
                                for (int j = 0; j < 3; j++)
                                {
                                    cell = new PdfPCell(new Phrase(" ", fontArialNormal));
                                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                    cell.Border = Rectangle.RIGHT_BORDER;
                                    CuartaFila.AddCell(cell);
                                }
                            }

                            if (i < DetallesRetenciones.Count)
                            {
                                cell = new PdfPCell(new Phrase(DetallesRetenciones[i].DesConcepto, fontArialNormal));
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                cell.Border = Rectangle.RIGHT_BORDER;
                                CuartaFila.AddCell(cell);

                                cell = new PdfPCell(new Phrase(string.Format(DetallesRetenciones[i].Cargo.ToString("###,##0.00")), fontArialNormal));
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                cell.Border = Rectangle.RIGHT_BORDER;
                                CuartaFila.AddCell(cell);

                                cell = new PdfPCell(new Phrase(string.Format(DetallesRetenciones[i].Amortizacion.ToString("###,##0.00")), fontArialNormal));
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                cell.Border = Rectangle.RIGHT_BORDER;
                                CuartaFila.AddCell(cell);

                                cell = new PdfPCell(new Phrase(string.Format(DetallesRetenciones[i].Saldo.ToString("###,##0.00")), fontArialNormal));
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                cell.Border = Rectangle.RIGHT_BORDER;
                                CuartaFila.AddCell(cell);

                                cell = new PdfPCell(new Phrase(string.Format(DetallesRetenciones[i].ImporteConcepto.ToString("###,##0.00")), fontArialNormal));
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                cell.Border = Rectangle.RIGHT_BORDER;
                                CuartaFila.AddCell(cell);
                            }
                            else
                            {
                                for (int j = 0; j < 5; j++)
                                {
                                    cell = new PdfPCell(new Phrase(" ", fontArialNormal));
                                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                    cell.Border = Rectangle.RIGHT_BORDER;
                                    CuartaFila.AddCell(cell);
                                }
                            }
                        }

                        CuartaFila.Rows.Count();
                        int filasRestantes = 20 - CuartaFila.Rows.Count();
                        for (int i = 0; i < filasRestantes; i++)
                        {
                            for (int j = 0; j < 8; j++)
                            {
                                cell = new PdfPCell(new Phrase(" ", fontArialNormal));
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                cell.Border = Rectangle.RIGHT_BORDER;
                                CuartaFila.AddCell(cell);
                            }
                        }
                        //->Fin de los detalles de cuerpo

                        cell                     = new PdfPCell(CuartaFila);
                        cell.Colspan             = 2;
                        cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                        Boleta.AddCell(cell);
                        //----------


                        //-----Quinta Fila
                        PdfPTable QuintaFila       = new PdfPTable(3);
                        float[]   medidaQuintaFila = { 303f, 390f, 110f };
                        QuintaFila.TotalWidth  = 803f;
                        QuintaFila.LockedWidth = true;
                        QuintaFila.SetWidths(medidaQuintaFila);

                        cell = new PdfPCell(new Phrase("TOTAL REMUNERACIONES", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        QuintaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("TOTAL RETENCIONES", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        QuintaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(""));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        QuintaFila.AddCell(cell);

                        cell                     = new PdfPCell(QuintaFila);
                        cell.Colspan             = 2;
                        cell.HorizontalAlignment = 1;

                        Boleta.AddCell(cell);
                        //-------

                        //------Sexta Fila
                        PdfPTable SextaFila       = new PdfPTable(7);
                        float[]   medidaSextaFila = { 75.75f, 75.75f, 75.75f, 75.75f, 166.6666666666667f, 166.6666666666667f, 166.6666666666667f };
                        SextaFila.TotalWidth  = 803f;
                        SextaFila.LockedWidth = true;
                        SextaFila.SetWidths(medidaSextaFila);

                        cell                     = new PdfPCell(new Phrase("CONTRIBUCIONES PATRONALES", fontArialBold));
                        cell.Colspan             = 4;
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        SextaFila.AddCell(cell);

                        cell                     = new PdfPCell(new Phrase(""));
                        cell.Rowspan             = 2;
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        SextaFila.AddCell(cell);

                        cell                     = new PdfPCell(new Phrase("RECIBI CONFORME", fontArialBold));
                        cell.Rowspan             = 2;
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        SextaFila.AddCell(cell);

                        cell                     = new PdfPCell(new Phrase("S/.", fontArialBold));
                        cell.Rowspan             = 3;
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        cell.VerticalAlignment   = Element.ALIGN_BOTTOM;
                        SextaFila.AddCell(cell);

                        //---
                        cell = new PdfPCell(new Phrase("ESSALUD", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        SextaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("ONP", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        SextaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(""));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        SextaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("IMP SOLES", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        SextaFila.AddCell(cell);

                        //----

                        cell = new PdfPCell(new Phrase(""));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        SextaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(""));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        SextaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(""));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        SextaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase(""));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        SextaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("FIRMA DEL REPRESENTANTE", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        SextaFila.AddCell(cell);

                        cell = new PdfPCell(new Phrase("FIRMA DEL TRABAJADOR", fontArialBold));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        SextaFila.AddCell(cell);

                        //----
                        cell                     = new PdfPCell(SextaFila);
                        cell.Colspan             = 2;
                        cell.HorizontalAlignment = 1;
                        Boleta.AddCell(cell);
                        //-------

                        oDocument.Add(Boleta);

                        oDocument.Close();
                    }
                }
            }
        }
コード例 #25
0
        public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
        {
            base.OnEndPage(writer, document);

            iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

            iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);

            Phrase p1Header = new Phrase(null, null);

            //removing Header HTML COntent
            if (HeaderText != null)
            {
                FontFactory.RegisterDirectories();
                List <IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(HeaderText), null);
                for (int k = 0; k < htmlarraylist.Count; k++)
                {
                    p1Header.Add((IElement)htmlarraylist[k]);
                }
            }

            Phrase p1Footer = new Phrase(null, null);

            //removing Footer HTML COntent
            if (FooterText != null)
            {
                FontFactory.RegisterDirectories();
                List <IElement> htmlarrayFooterlist = HTMLWorker.ParseToList(new StringReader(FooterText), null);
                for (int m = 0; m < htmlarrayFooterlist.Count; m++)
                {
                    p1Footer.Add((IElement)htmlarrayFooterlist[m]);
                }
            }
            //Create PdfTable object
            PdfPTable pdfTab = new PdfPTable(3);

            pdfTab.WidthPercentage = 90;

            float[] tblDescWidth52 = new float[3];
            tblDescWidth52[0] = 25;
            tblDescWidth52[1] = 72;
            tblDescWidth52[2] = 2;

            pdfTab.SetWidths(tblDescWidth52);
            String text = "Page " + writer.PageNumber + " of ";

            //We will have to create separate cells to include image logo and 2 separate strings
            //Row 1
            if (HeaderRequired)
            {
                PdfPCell pdfCell1 = new PdfPCell();
                PdfPCell pdfCell2 = new PdfPCell(p1Header);
                PdfPCell pdfCell3 = new PdfPCell();

                //  iTextSharp.text.Image imgLogo = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/Images/customer Images/ReportLogo/" + LogoPath));

                //  iTextSharp.text.Image imgLogo = iTextSharp.text.Image.GetInstance("F:/MAIN V10/Sharda_Hospital/Sharda_12_08_2016/WinApps/ReportLogo/Win7645logo3.PNG");

                //  imgLogo.ScaleToFit(80, 60);
                //  pdfCell1.AddElement(imgLogo);

                string base64Image = LogoPath;                                                         // new 18-08
                Regex  regex       = new Regex(@"^data:image/(?<mediaType>[^;]+);base64,(?<data>.*)"); // new 18-08
                Match  match       = regex.Match(base64Image);                                         // new 18-08

                Image image = Image.GetInstance(                                                       // new 18-08
                    Convert.FromBase64String(match.Groups["data"].Value)                               // new 18-08
                    );

                image.ScaleToFit(80, 60);   // new 18-08
                pdfCell1.AddElement(image); // new 18-08


                //Row 2
                PdfPCell pdfCell4 = new PdfPCell(new Phrase(null, baseFontNormal));
                //Row 3

                //set the alignment of all three cells and set border to 0
                pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER;
                pdfCell2.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER;
                pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER;

                pdfCell2.VerticalAlignment = Element.ALIGN_CENTER;
                pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
                pdfCell4.VerticalAlignment = Element.ALIGN_TOP;

                pdfCell4.Colspan = 3;

                pdfCell1.Border = 0;
                pdfCell2.Border = 0;
                pdfCell3.Border = 0;
                pdfCell4.Border = 0;

                //add all three cells into PdfTable
                pdfTab.AddCell(pdfCell1);
                pdfTab.AddCell(pdfCell2);
                pdfTab.AddCell(pdfCell3);
                pdfTab.AddCell(pdfCell4);

                pdfTab.TotalWidth      = document.PageSize.Width - 80f;
                pdfTab.WidthPercentage = 70;

                //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
                //first param is start row. -1 indicates there is no end row and all the rows to be included to write
                //Third and fourth param is x and y position to start writing
                pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent);

                //Move the pointer and draw line to separate header section from rest of page
                if (BorderRequired)
                {
                    cb.MoveTo(40, document.PageSize.Height - 100);
                    cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100);
                    cb.Stroke();
                }
            }
            //footer code
            if (FooterRequired)
            {
                //Move the pointer and draw line to separate footer section from rest of page
                if (BorderRequired)
                {
                    cb.MoveTo(40, document.PageSize.GetBottom(50));
                    cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50));
                    cb.Stroke();
                }

                //Add Footer text to footer
                PdfPTable pdfTaba = new PdfPTable(1);



                PdfPCell pdfCellfooter = new PdfPCell(p1Footer);

                pdfCellfooter.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCellfooter.Border            = 0;
                pdfCellfooter.VerticalAlignment = Element.ALIGN_BOTTOM;
                if (PaperSize == "")
                {
                    pdfTaba.TotalWidth = document.PageSize.Width - 80f;
                }
                else
                {
                    pdfTaba.TotalWidth = document.PageSize.Width;
                }

                pdfTaba.WidthPercentage = 100;

                pdfTaba.AddCell(pdfCellfooter);
                //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
                //first param is start row. -1 indicates there is no end row and all the rows to be included to write
                //Third and fourth param is x and y position to start writing
                // pdfTaba.WriteSelectedRows(0, -1, document.PageSize.GetRight(550), document.PageSize.GetBottom(50), writer.DirectContent);
                if (PaperSize == "A4 Size")
                {
                    pdfTaba.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 750, writer.DirectContent);
                }
                else
                {
                    pdfTaba.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 500, writer.DirectContent);
                }
            }
            if (PageRequired)
            {
                //Add paging to footer
                cb.BeginText();
                cb.SetFontAndSize(bf, 8);
                cb.SetTextMatrix(document.PageSize.GetRight(120), document.PageSize.GetBottom(35));
                cb.ShowText(text);
                cb.EndText();
                float len = bf.GetWidthPoint(text, 12);
                cb.AddTemplate(footerTemplate, document.PageSize.GetRight(120) + len, document.PageSize.GetBottom(35));
            }
            if (BorderRequired)
            {
                //Add Paging to Border
                var content        = writer.DirectContent;
                var pageBorderRect = new Rectangle(document.PageSize);

                pageBorderRect.Left   += 40f;
                pageBorderRect.Right  -= 40f;
                pageBorderRect.Top    -= 30f;
                pageBorderRect.Bottom += 30f;

                content.SetColorStroke(BaseColor.BLACK);
                content.Rectangle(pageBorderRect.Left, pageBorderRect.Bottom, pageBorderRect.Width, pageBorderRect.Height);
                content.Stroke();
            }
        }
コード例 #26
0
ファイル: PDF.aspx.cs プロジェクト: yarelyGE/ZCUU-IDD-Vsitas
    protected void Page_Load(object sender, EventArgs e)
    {
        // Creamos el documento con el tamaño de página tradicional
        Document doc = new Document(iTextSharp.text.PageSize.LETTER, 11, 11, 5, 5);
        // Indicamos donde vamos a guardar el documento
        //Path.Combine(Server.MapPath)
        FileStream fs2    = new FileStream(Path.Combine(HttpContext.Current.Server.MapPath(@"~/PDF/IDDVisitas.pdf")), FileMode.Create, FileAccess.Write, FileShare.None);
        PdfWriter  writer = PdfWriter.GetInstance(doc, fs2);

        writer.Open();
        doc.Open();
        var content = writer.DirectContent;
        var page    = new Rectangle(doc.PageSize);

        page.Left   += doc.LeftMargin;
        page.Right  -= doc.RightMargin;
        page.Top    -= doc.TopMargin;
        page.Bottom += doc.BottomMargin;
        FontFactory.RegisterDirectories();
        Font fuente = FontFactory.GetFont("Times New Roman");

        /*PRIMERA TABLA*/
        PdfPTable tableSeccion1 = new PdfPTable(1);

        tableSeccion1.WidthPercentage = 95;
        tableSeccion1.TotalWidth      = page.Width - 65;
        tableSeccion1.LockedWidth     = true;
        tableSeccion1.SetWidths(new float[] { 1f });
        Phrase   titulo1     = new Phrase("SECCION 1: COMPLETADA POR VISITANTE O POR ANFITRION ZLS", fuente);
        PdfPCell celdaTitulo = new PdfPCell(new Phrase(titulo1));

        tableSeccion1.AddCell(celdaTitulo);
        doc.Add(tableSeccion1);

        /*SEGUNDA TABLA*/
        PdfPTable table1 = new PdfPTable(3);

        table1.WidthPercentage = 95;
        table1.TotalWidth      = page.Width - 65;
        table1.LockedWidth     = true;
        table1.SetWidths(new float[] { 2f, 1f, 1.25f });
        Phrase   t1      = new Phrase("Nombre del Anfitrion Empleado de ZLS:", fuente);
        Phrase   t2      = new Phrase("Num. de telefono:", fuente);
        Phrase   t3      = new Phrase("Fecha:", fuente);
        PdfPCell celdaT1 = new PdfPCell(new Phrase(t1));
        PdfPCell celdaT2 = new PdfPCell(new Phrase(t2));
        PdfPCell celdaT3 = new PdfPCell(new Phrase(t3));

        table1.AddCell(celdaT1);
        table1.AddCell(celdaT2);
        table1.AddCell(celdaT3);
        doc.Add(table1);


        /*Cerrar documento, escritor y filestream*/
        doc.Close();
        writer.Close();
        fs2.Close();

        /*Crear y descargar pdf*/
        HttpContext.Current.Response.TransmitFile(Path.Combine(HttpContext.Current.Server.MapPath(@"~/PDF/IDDVisitas.pdf")));
        HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=Visita.pdf");
        HttpContext.Current.Response.ContentType = "application/octet-stream";
        HttpContext.Current.Response.Flush();
        File.Delete(Path.Combine(HttpContext.Current.Server.MapPath(@"~/PDF/IDDVisitas.pdf")));
    }
コード例 #27
0
 /// <summary>
 /// Load system fonts into the static  FontFactory  object
 /// @since 2.0.8
 /// </summary>
 private void importSystemFonts()
 {
     FontFactory.RegisterDirectories();
 }
コード例 #28
0
        public void dataTableToPdf(System.Data.DataTable dataTable, string FilePath)
        {
            FontFactory.RegisterDirectories();
            iTextSharp.text.Font font       = FontFactory.GetFont("Courier", BaseFont.IDENTITY_H, 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
            iTextSharp.text.Font fontMedium = FontFactory.GetFont("Courier", BaseFont.IDENTITY_H, 11, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
            Document             document   = new Document(PageSize.A4.Rotate(), 20f, 20f, 20f, 25f);

            PdfWriter pdfWriter = PdfWriter.GetInstance(document, new FileStream(FilePath, FileMode.Create));

            pdfWriter.PageEvent = new ItextPageEvent();

            PdfPTable pdfTable = new PdfPTable(dataTable.Columns.Count);

            pdfTable.WidthPercentage = 100f;
            pdfTable.SpacingAfter    = 10;
            pdfTable.SpacingBefore   = 10;

            PdfContentByte pdfContentByte = new PdfContentByte(pdfWriter);

            iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(logoPath, true);
            logo.ScaleToFit(80f, 80f);

            StringBuilder sbParagraph1, sbParagraph2, sbParagraph3, sbParagraph4, sbParagraph5, sbParagraph6;

            sbParagraph1 = new StringBuilder("");
            sbParagraph2 = new StringBuilder("");
            sbParagraph3 = new StringBuilder("");
            sbParagraph4 = new StringBuilder("");
            sbParagraph5 = new StringBuilder("");
            sbParagraph6 = new StringBuilder("");


            if (
                reportType == ReportType.HISTORICAL ||
                reportType == ReportType.RUNNING ||
                reportType == ReportType.IDLING ||
                reportType == ReportType.ACC ||
                reportType == ReportType.GEOFENCE ||
                reportType == ReportType.OVERSPEED ||
                reportType == ReportType.EXTERNAL_POWER_CUT
                )
            {
                sbParagraph1.Append(
                    "Vehicle Reg\n" +
                    "Vehicle Model\n" +
                    "Owner Name\n" +
                    "Driver Name\n" +
                    "Device Imei\n"
                    );
                sbParagraph2.Append(
                    ": " + reportInformation.trackerVehicleReg + "\n" +
                    ": " + reportInformation.trackerVehicleModel + "\n" +
                    ": " + reportInformation.trackerOwnerName + "\n" +
                    ": " + reportInformation.trackerDriverName + "\n" +
                    ": " + reportInformation.trackerDeviceImei + "\n"
                    );
            }

            if (
                reportType == ReportType.RUNNING ||
                reportType == ReportType.IDLING ||
                reportType == ReportType.ACC ||
                reportType == ReportType.GEOFENCE ||
                reportType == ReportType.OVERSPEED ||
                reportType == ReportType.TRACKERS_GEOFENCE ||
                reportType == ReportType.EXTERNAL_POWER_CUT
                )
            {
                sbParagraph3.Append(
                    "Total Distance\n" +
                    "Total Fuel\n" +
                    "Total Cost\n");

                switch (reportType)
                {
                case ReportType.RUNNING:
                    sbParagraph3.Append("Total Running Time\n");
                    break;

                case ReportType.IDLING:
                    sbParagraph3.Append("Total Idling Time\n");
                    break;

                case ReportType.GEOFENCE:
                    sbParagraph3.Append("Total Geofence Active Time\n");
                    break;

                case ReportType.ACC:
                    sbParagraph3.Append("Total ACC Active Time\n");
                    break;

                case ReportType.EXTERNAL_POWER_CUT:
                    sbParagraph3.Append("Total ExternalPower Cut Time\n");
                    break;
                }


                sbParagraph4.Append(": " + reportInformation.summaryTotalDistance + "\n");
                sbParagraph4.Append(": " + reportInformation.summaryTotalFuel + "\n");
                sbParagraph4.Append(": " + reportInformation.summaryTotalCost + "\n");
                switch (reportType)
                {
                case ReportType.RUNNING:
                    sbParagraph4.Append(": " + reportInformation.summaryTotalRunningTime + "\n");
                    break;

                case ReportType.IDLING:
                    sbParagraph4.Append(": " + reportInformation.summaryTotalIdlingTime + "\n");
                    break;

                case ReportType.GEOFENCE:
                    sbParagraph4.Append(": " + reportInformation.summaryTotalGeofenceActiveTime + "\n");
                    break;

                case ReportType.ACC:
                    sbParagraph4.Append(": " + reportInformation.summaryTotalAccActiveTime + "\n");
                    break;

                case ReportType.EXTERNAL_POWER_CUT:
                    sbParagraph4.Append(": " + reportInformation.summaryTotalExternalPowerCutTime + "\n");
                    break;
                }
            }

            if (
                reportType == ReportType.HISTORICAL ||
                reportType == ReportType.RUNNING ||
                reportType == ReportType.IDLING ||
                reportType == ReportType.ACC ||
                reportType == ReportType.GEOFENCE ||
                reportType == ReportType.OVERSPEED ||
                reportType == ReportType.EXTERNAL_POWER_CUT
                )
            {
                sbParagraph5.Append("DateTime From\n");
                sbParagraph5.Append("DateTime To\n");
            }

            sbParagraph5.Append("Generated by\n" + "Created on\n");

            if (
                reportType == ReportType.HISTORICAL ||
                reportType == ReportType.RUNNING ||
                reportType == ReportType.IDLING ||
                reportType == ReportType.ACC ||
                reportType == ReportType.GEOFENCE ||
                reportType == ReportType.OVERSPEED ||
                reportType == ReportType.EXTERNAL_POWER_CUT

                )
            {
                sbParagraph6.Append(": " + reportInformation.summaryDateTimeFrom + "\n");
                sbParagraph6.Append(": " + reportInformation.summaryDateTimeTo + "\n");
            }

            sbParagraph6.Append(": " + reportInformation.userName + "\n");
            sbParagraph6.Append(": " + DateTime.Now.ToString() + "\n");

            Paragraph paragraph0 = new Paragraph(reportInformation.companyName + "\n" + Enum.GetName(typeof(ReportType), reportType) + " Report\n" + this.title, fontMedium);
            Paragraph paragraph1 = new Paragraph(sbParagraph1.ToString(), font);
            Paragraph paragraph2 = new Paragraph(sbParagraph2.ToString(), font);
            Paragraph paragraph3 = new Paragraph(sbParagraph3.ToString(), font);
            Paragraph paragraph4 = new Paragraph(sbParagraph4.ToString(), font);
            Paragraph paragraph5 = new Paragraph(sbParagraph5.ToString(), font);
            Paragraph paragraph6 = new Paragraph(sbParagraph6.ToString(), font);


            //======================================
            PdfPTable pdfTableHeader;
            PdfPCell  pdfCell;

            pdfTableHeader = new PdfPTable(8);

            pdfCell                     = new PdfPCell(logo, true);
            pdfCell.BorderWidth         = 0;
            pdfCell.PaddingLeft         = 20f;
            pdfCell.PaddingRight        = 20f;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);

            pdfCell                     = new PdfPCell(paragraph0);
            pdfCell.BorderWidth         = 0;
            pdfCell.Padding             = 0;
            pdfCell.PaddingTop          = 12;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);

            pdfCell                     = new PdfPCell(paragraph1);
            pdfCell.BorderWidth         = 0;
            pdfCell.Padding             = 0;
            pdfCell.PaddingTop          = 12;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);

            pdfCell                     = new PdfPCell(paragraph2);
            pdfCell.BorderWidth         = 0;
            pdfCell.Padding             = 0;
            pdfCell.PaddingTop          = 12;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);


            pdfCell                     = new PdfPCell(paragraph3);
            pdfCell.BorderWidth         = 0;
            pdfCell.Padding             = 0;
            pdfCell.PaddingTop          = 12;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);

            pdfCell                     = new PdfPCell(paragraph4);
            pdfCell.BorderWidth         = 0;
            pdfCell.Padding             = 0;
            pdfCell.PaddingTop          = 12;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);

            pdfCell                     = new PdfPCell(paragraph5);
            pdfCell.BorderWidth         = 0;
            pdfCell.Padding             = 0;
            pdfCell.PaddingTop          = 12;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);

            pdfCell                     = new PdfPCell(paragraph6);
            pdfCell.BorderWidth         = 0;
            pdfCell.Padding             = 0;
            pdfCell.PaddingTop          = 12;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);
            pdfTableHeader.SetWidthPercentage(new float[8] {
                140f, 150f, 60f, 100f, 110f, 100f, 60f, 100f
            }, PageSize.A4.Rotate());
            pdfTableHeader.HorizontalAlignment = Element.ALIGN_LEFT;

            try {
                document.Open();
                document.Add(pdfTableHeader);



                for (int index = 0; index < dataTable.Columns.Count; ++index)
                {
                    string columnName = dataTable.Columns[index].ColumnName;
                    //columnName = columnName.Replace('[', ' ');
                    //columnName = columnName.Replace(']', ' ');
                    Phrase   phrase = new Phrase(columnName, font);
                    PdfPCell cell   = new PdfPCell(phrase);
                    cell.BackgroundColor     = BaseColor.CYAN;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.RunDirection        = PdfWriter.RUN_DIRECTION_RTL;
                    pdfTable.AddCell(cell);
                }

                for (int i = 0; i < dataTable.Rows.Count; ++i)
                {
                    for (int j = 0; j < dataTable.Columns.Count; ++j)
                    {
                        string data = dataTable.Rows[i][j].ToString();

                        if (dataTable.Rows[i][j].GetType() == typeof(DateTime))
                        {
                            DateTime dateTime = (DateTime)dataTable.Rows[i][j];
                            data = dateTime.ToString("yyyy/MM/dd HH:mm:ss");
                        }
                        if (dataTable.Rows[i][j].GetType() == typeof(TimeSpan))
                        {
                            TimeSpan timeSpan = (TimeSpan)dataTable.Rows[i][j];
                            data = timeSpan.ToString(@"dd\ hh\:mm\:ss");
                        }

                        //if (dataTable.Rows[i][j].GetType() == typeof(double)) {
                        //    double number = (double)dataTable.Rows[i][j];
                        //    data = Converter.round(number).ToString();
                        //}
                        //if (dataTable.Rows[i][j].GetType() == typeof(TimeSpan)) {
                        //    TimeSpan timeSpan = (TimeSpan)dataTable.Rows[i][j];
                        //    data = timeSpan.ToString(@"dd\ hh\:mm\:ss");
                        //}

                        Phrase   phrase = new Phrase(data, font);
                        PdfPCell cell   = new PdfPCell(phrase);
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.RunDirection        = PdfWriter.RUN_DIRECTION_RTL;
                        pdfTable.AddCell(cell);
                    }
                }
                document.Add(pdfTable);
                document.Close();
            } catch (Exception exception) {
                document.Close();
                throw exception;
            }
        }
コード例 #29
0
 private Font GetFont(float size)
 {
     FontFactory.RegisterDirectories();
     return(new Font(FontFactory.GetFont("Arial", size, Font.BOLD)));
 }
コード例 #30
0
        public bool ConvertToPDF(string inputFile, string outputFile)
        {
            bool converted = false;

            try
            {
                HtmlDocument doc = new HtmlDocument();
                doc.OptionFixNestedTags   = true;
                doc.OptionWriteEmptyNodes = true;
                doc.OptionAutoCloseOnEnd  = true;

                doc.Load(inputFile);

                string rootInner = doc.DocumentNode.InnerHtml;

                if (!rootInner.Contains("<html"))
                {
                    doc.DocumentNode.InnerHtml = "<!DOCTYPE html>"
                                                 + "\r\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">"
                                                 + "\r\n\t<head>"
                                                 + "\r\n\t\t<title>HTML to PDF</title>"
                                                 + "\r\n\t</head>"
                                                 + "\r\n\t<body>\r\n"
                                                 + rootInner
                                                 + "\r\n\t</body>"
                                                 + "\r\n</html>";
                }

                rootInner = doc.DocumentNode.InnerHtml;

                // Remove <meta> tag.
                string metaTag = @"<\s*(meta)(\s[^>]*)?>\s*";
                while (Regex.IsMatch(rootInner, metaTag))
                {
                    string metaMatch = Regex.Match(rootInner, metaTag).Value;
                    rootInner = rootInner.Replace(metaMatch, string.Empty);
                }
                rootInner = rootInner.Replace("</meta>", string.Empty);

                // Remove <form> tag.
                string formTag = @"<\s*(form)(\s[^>]*)?>\s*";
                while (Regex.IsMatch(rootInner, formTag))
                {
                    string formMatch = Regex.Match(rootInner, formTag).Value;
                    rootInner = rootInner.Replace(formMatch, string.Empty);
                }
                rootInner = rootInner.Replace("</form>", string.Empty);

                // Close br tag.
                string          brTag     = @"<\s*(br)(\s[^>]*)?>";
                MatchCollection brMatches = Regex.Matches(rootInner, brTag);
                if (brMatches != null)
                {
                    foreach (Match match in brMatches)
                    {
                        rootInner = rootInner.Replace(match.Value, "<br />");
                    }
                }

                // Replace <font> tag with div.
                string fontTag = @"<\s*(font)(\s[^>]*)?>";
                while (Regex.IsMatch(rootInner, fontTag))
                {
                    string fontMatch = Regex.Match(rootInner, fontTag).Value;
                    string toSpan    = fontMatch.Replace("font", "div");
                    rootInner = rootInner.Replace(fontMatch, toSpan);
                }
                rootInner = rootInner.Replace("</font>", "</div>");

                doc.DocumentNode.InnerHtml = rootInner;

                // Table elements
                var tableNodes = doc.DocumentNode.SelectNodes("//table");
                if (tableNodes != null)
                {
                    foreach (HtmlNode node in tableNodes)
                    {
                        bool isValidTable = false;
                        if (node.HasChildNodes)
                        {
                            if ((node.SelectSingleNode("thead/tr/th") != null) ||
                                (node.SelectSingleNode("tbody/tr/td") != null) ||
                                (node.SelectSingleNode("tr/td") != null))
                            {
                                isValidTable = true;
                            }
                        }

                        // Remove invalid table (no tr, td tags).
                        if (!isValidTable)
                        {
                            HtmlNode parent = node.ParentNode;
                            parent.InnerHtml = " ";
                        }

                        bool hasStyle = node.Attributes.Contains("style");
                        if (!hasStyle)
                        {
                            node.Attributes.Add("style", string.Empty);
                        }

                        StringBuilder styleValue = new StringBuilder(node.Attributes["style"].Value.Trim());
                        if (!string.IsNullOrEmpty(styleValue.ToString()))
                        {
                            if (!styleValue.ToString().EndsWith(";"))
                            {
                                styleValue.Append(";");
                            }
                        }

                        if (node.Attributes.Contains("cellspacing"))
                        {
                            if (!styleValue.ToString().Contains("border-collapse"))
                            {
                                styleValue.Append("border-collapse: collapse; ");
                            }
                            node.Attributes.Remove("cellspacing");
                        }

                        if (node.Attributes.Contains("cellpadding"))
                        {
                            if (!styleValue.ToString().Contains("cellpadding"))
                            {
                                styleValue.Append("padding: " + node.Attributes["cellpadding"].Value + "px; ");
                            }
                            node.Attributes.Remove("cellpadding");
                        }

                        if (node.Attributes.Contains("border"))
                        {
                            if (!styleValue.ToString().Contains("border"))
                            {
                                styleValue.Append("border: " + node.Attributes["border"].Value + "; ");
                            }
                            node.Attributes.Remove("border");
                        }

                        if (node.Attributes.Contains("width"))
                        {
                            string width = node.Attributes["width"].Value;
                            if (node.Attributes["width"].Value.EndsWith("%"))
                            {
                                width = node.Attributes["width"].Value;
                            }
                            else
                            {
                                if (node.Attributes["width"].Value.EndsWith("px"))
                                {
                                    width = node.Attributes["width"].Value;
                                }
                                else
                                {
                                    width = node.Attributes["width"].Value + "px";
                                }
                            }

                            styleValue.Append("width: " + width + "; ");
                            node.Attributes.Remove("width");
                        }

                        if (node.Attributes.Contains("height"))
                        {
                            string height = node.Attributes["height"].Value.EndsWith("px") ? node.Attributes["height"].Value : node.Attributes["height"].Value + "px; ";
                            styleValue.Append("height: " + height);
                            node.Attributes.Remove("height");
                        }

                        if (node.Attributes.Contains("align"))
                        {
                            styleValue.Append("text-align: " + node.Attributes["align"].Value + "; ");
                            node.Attributes.Remove("align");
                        }

                        node.Attributes["style"].Value = styleValue.ToString();
                    }
                }

                // Remove div from /div/img path.
                var imgNodes = doc.DocumentNode.SelectNodes("//div/img");
                while (imgNodes != null)
                {
                    foreach (HtmlNode node in imgNodes)
                    {
                        node.InnerHtml = " ";
                        HtmlNode td = node.ParentNode.ParentNode;
                        td.RemoveChild(node.ParentNode, true);
                    }
                    imgNodes = doc.DocumentNode.SelectNodes("//div/img");
                }

                // Remove div with class="Top_Hidden".
                var divHiddenNodes = doc.DocumentNode.SelectNodes("//div[@class='Top_Hidden']");
                while (divHiddenNodes != null)
                {
                    foreach (HtmlNode node in divHiddenNodes)
                    {
                        HtmlNode tatay = node.ParentNode;
                        tatay.RemoveChild(node, false);
                    }
                    divHiddenNodes = doc.DocumentNode.SelectNodes("//div[@class='Top_Hidden']");
                }

                // Remove children for div with class="blank".
                var divBlankNodes = doc.DocumentNode.SelectNodes("//div[@class='blank']");
                if (divBlankNodes != null)
                {
                    foreach (HtmlNode node in divBlankNodes)
                    {
                        node.RemoveAllChildren();
                    }
                }

                // Close img tag from /td/img path.
                var tdImgNodes = doc.DocumentNode.SelectNodes("//td/img");
                if (tdImgNodes != null)
                {
                    foreach (HtmlNode node in tdImgNodes)
                    {
                        node.InnerHtml = " ";
                    }
                }

                // Add style to div tag.
                var divNodes = doc.DocumentNode.SelectNodes("//div");
                if (divNodes != null)
                {
                    foreach (HtmlNode node in divNodes)
                    {
                        if (node.HasAttributes)
                        {
                            bool hasStyle = node.Attributes.Contains("style");
                            if (!hasStyle)
                            {
                                node.Attributes.Add("style", string.Empty);
                            }

                            StringBuilder styleValue = new StringBuilder(node.Attributes["style"].Value.Trim());
                            if (!string.IsNullOrEmpty(styleValue.ToString()) && !styleValue.ToString().EndsWith(";"))
                            {
                                styleValue.Append(";");
                            }

                            if (node.Attributes.Contains("face"))
                            {
                                string fontFamily = node.Attributes["face"].Value;
                                styleValue.Append("font-family: " + fontFamily.ToLower() + ";");
                                node.Attributes.Remove("face");
                            }

                            if (node.Attributes.Contains("size"))
                            {
                                string fontSize = node.Attributes["size"].Value;
                                string size     = "9pt";
                                switch (fontSize)
                                {
                                case "1":
                                {
                                    size = "7pt";
                                    break;
                                }

                                case "2":
                                {
                                    size = "9pt";
                                    break;
                                }

                                case "3":
                                {
                                    size = "10pt";
                                    break;
                                }

                                case "4":
                                {
                                    size = "12pt";
                                    break;
                                }

                                case "5":
                                {
                                    size = "16pt";
                                    break;
                                }

                                case "6":
                                {
                                    size = "20pt";
                                    break;
                                }

                                case "7":
                                {
                                    size = "30pt";
                                    break;
                                }

                                default:
                                    break;
                                }

                                styleValue.Append("font-size: " + size.ToLower() + ";");
                                node.Attributes.Remove("size");
                            }

                            node.Attributes["style"].Value = styleValue.ToString();
                        }
                    }
                }

                // Add td style.
                var tdNodes = doc.DocumentNode.SelectNodes("//td");
                if (tdNodes != null)
                {
                    foreach (HtmlNode node in tdNodes)
                    {
                        bool hasStyle = node.Attributes.Contains("style");
                        if (!hasStyle)
                        {
                            node.Attributes.Add("style", string.Empty);
                        }

                        StringBuilder styleValue = new StringBuilder(node.Attributes["style"].Value.Trim());
                        if (!string.IsNullOrEmpty(styleValue.ToString()))
                        {
                            if (!styleValue.ToString().EndsWith(";"))
                            {
                                styleValue.Append("; ");
                            }
                        }

                        if (node.Attributes.Contains("align"))
                        {
                            styleValue.Append("text-align: " + node.Attributes["align"].Value + "; ");
                            node.Attributes.Remove("align");
                        }
                        else
                        {
                            styleValue.Append("text-align: left;");
                        }

                        if (node.Attributes.Contains("valign"))
                        {
                            styleValue.Append("vertical-align: " + node.Attributes["valign"].Value + "; ");
                            node.Attributes.Remove("valign");
                        }

                        if (node.Attributes.Contains("width"))
                        {
                            string width = node.Attributes["width"].Value;
                            if (node.Attributes["width"].Value.EndsWith("%"))
                            {
                                width = node.Attributes["width"].Value;
                            }
                            else
                            {
                                if (node.Attributes["width"].Value.EndsWith("px"))
                                {
                                    width = node.Attributes["width"].Value;
                                }
                                else
                                {
                                    width = node.Attributes["width"].Value + "px";
                                }
                            }

                            styleValue.Append("width: " + width + "; ");
                            node.Attributes.Remove("width");
                        }

                        if (!string.IsNullOrEmpty(styleValue.ToString()))
                        {
                            node.Attributes["style"].Value = styleValue.ToString();
                        }
                    }
                }

                // Add style to p tag.
                var pNodes = doc.DocumentNode.SelectNodes("//p");
                if (pNodes != null)
                {
                    foreach (HtmlNode node in pNodes)
                    {
                        if (node.HasAttributes)
                        {
                            bool hasStyle = node.Attributes.Contains("style");
                            if (!hasStyle)
                            {
                                node.Attributes.Add("style", string.Empty);
                            }

                            StringBuilder styleValue = new StringBuilder(node.Attributes["style"].Value.Trim());
                            if (!string.IsNullOrEmpty(styleValue.ToString()) && !styleValue.ToString().EndsWith(";"))
                            {
                                styleValue.Append(";");
                            }

                            if (node.Attributes.Contains("align"))
                            {
                                string value = node.Attributes["align"].Value;
                                styleValue.Append("text-align: " + value.ToLower() + ";");
                                node.Attributes.Remove("align");
                            }

                            node.Attributes["style"].Value = styleValue.ToString();
                        }
                    }
                }

                // Remove u tag from //u/div path but put underline in div tag.
                var uDivNodes = doc.DocumentNode.SelectNodes("//u/div");
                while (uDivNodes != null)
                {
                    foreach (HtmlNode node in uDivNodes)
                    {
                        bool hasStyle = node.Attributes.Contains("style");
                        if (!hasStyle)
                        {
                            node.Attributes.Add("style", string.Empty);
                        }

                        StringBuilder styleValue = new StringBuilder(node.Attributes["style"].Value.Trim());
                        if (!string.IsNullOrEmpty(styleValue.ToString()) && !styleValue.ToString().EndsWith(";"))
                        {
                            styleValue.Append(";");
                        }

                        styleValue.Append("text-decoration: underline;");

                        node.Attributes["style"].Value = styleValue.ToString();

                        HtmlNode lolo = node.ParentNode.ParentNode;
                        lolo.RemoveChild(node.ParentNode, true);
                    }
                    uDivNodes = doc.DocumentNode.SelectNodes("//u/div");
                }

                // Remove strong tag from //strong/div path but put bold in div tag.
                var strongDivNodes = doc.DocumentNode.SelectNodes("//strong/div");
                while (strongDivNodes != null)
                {
                    foreach (HtmlNode node in strongDivNodes)
                    {
                        bool hasStyle = node.Attributes.Contains("style");
                        if (!hasStyle)
                        {
                            node.Attributes.Add("style", string.Empty);
                        }

                        StringBuilder styleValue = new StringBuilder(node.Attributes["style"].Value.Trim());
                        if (!string.IsNullOrEmpty(styleValue.ToString()) && !styleValue.ToString().EndsWith(";"))
                        {
                            styleValue.Append(";");
                        }

                        styleValue.Append("font-weight: bold;");

                        node.Attributes["style"].Value = styleValue.ToString();

                        HtmlNode lolo = node.ParentNode.ParentNode;
                        lolo.RemoveChild(node.ParentNode, true);
                    }
                    strongDivNodes = doc.DocumentNode.SelectNodes("//strong/div");
                }

                // Replace p tag with div from //p/div path.
                var pDivNodes = doc.DocumentNode.SelectNodes("//p/div");
                while (pDivNodes != null)
                {
                    foreach (HtmlNode node in pDivNodes)
                    {
                        node.ParentNode.Name = "div";
                    }
                    pDivNodes = doc.DocumentNode.SelectNodes("//p/div");
                }


                // Remove div tag from //ol/div path.
                var olDivNodes = doc.DocumentNode.SelectNodes("//ol/div");
                while (olDivNodes != null)
                {
                    foreach (HtmlNode node in olDivNodes)
                    {
                        HtmlNode tatay = node.ParentNode;

                        bool hasStyle = node.Attributes.Contains("style");
                        if (hasStyle)
                        {
                            tatay.Attributes.Add(node.Attributes["style"]);
                        }

                        tatay.RemoveChild(node, true);
                    }
                    olDivNodes = doc.DocumentNode.SelectNodes("//ol/div");
                }

                // Remove div tag from //ul/div path.
                var ulDivNodes = doc.DocumentNode.SelectNodes("//ul/div");
                while (ulDivNodes != null)
                {
                    foreach (HtmlNode node in ulDivNodes)
                    {
                        HtmlNode tatay = node.ParentNode;

                        bool hasStyle = node.Attributes.Contains("style");
                        if (hasStyle)
                        {
                            tatay.Attributes.Add(node.Attributes["style"]);
                        }

                        tatay.RemoveChild(node, true);
                    }
                    ulDivNodes = doc.DocumentNode.SelectNodes("//ul/div");
                }

                // Remove div tag from //li/div path.
                var liDivNodes = doc.DocumentNode.SelectNodes("//li/div");
                while (liDivNodes != null)
                {
                    foreach (HtmlNode node in liDivNodes)
                    {
                        HtmlNode tatay = node.ParentNode;

                        bool hasStyle = node.Attributes.Contains("style");
                        if (hasStyle)
                        {
                            tatay.Attributes.Add(node.Attributes["style"]);
                        }

                        tatay.RemoveChild(node, true);
                    }
                    liDivNodes = doc.DocumentNode.SelectNodes("//li/div");
                }

                // Save the modified html to a new name.
                string formattedHTMLFile = outputFile.Replace(".pdf", string.Empty) + "_TEMP.html";
                doc.Save(formattedHTMLFile);

                HtmlDocument docCPM = new HtmlDocument();
                docCPM.OptionFixNestedTags   = true;
                docCPM.OptionWriteEmptyNodes = true;
                docCPM.OptionAutoCloseOnEnd  = true;

                string newHTML = outputFile.Replace(".pdf", string.Empty) + "_PDF.html";
                docCPM.Load(formattedHTMLFile);
                docCPM.Save(newHTML);

                FontFactory.RegisterDirectories();
                Document  document = new Document();
                PdfWriter writer   = PdfWriter.GetInstance(document, new FileStream(outputFile, FileMode.Create));
                try
                {
                    document.Open();

                    HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
                    htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                    CustomImageProvider imageProvider = new CustomImageProvider();
                    htmlContext.SetImageProvider(imageProvider);

                    ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);

                    IPipeline pipeline =
                        new CssResolverPipeline(cssResolver,
                                                new HtmlPipeline(htmlContext,
                                                                 new PdfWriterPipeline(document, writer)));

                    XMLWorker worker = new XMLWorker(pipeline, true);
                    XMLParser p      = new XMLParser(worker);
                    p.Parse(new StreamReader(newHTML));
                    //XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, new StreamReader(newHTMLFile));

                    converted = true;
                }
                catch
                {
                    converted = false;
                    throw;
                }
                finally
                {
                    if (document.IsOpen())
                    {
                        document.Close();
                    }

                    if (writer != null)
                    {
                        writer.Close();
                    }

                    File.Delete(formattedHTMLFile);
                    File.Delete(newHTML);
                }
            }
            catch
            {
                converted = false;
                throw;
            }
            finally
            {
            }

            return(converted);
        }