Exemplo n.º 1
0
 public void DrawMultiLineOfText(PdfFormField field, string text, BaseFont font, float fontSize, float llx, float lly, float urx, float ury)
 {
     PdfAppearance tp = PdfAppearance.CreateAppearance(writer, urx - llx, ury - lly);
     PdfAppearance tp2 = (PdfAppearance)tp.Duplicate;
     tp2.SetFontAndSize(font, fontSize);
     tp2.ResetRGBColorFill();
     field.DefaultAppearanceString = tp2;
     tp.DrawTextField(0f, 0f, urx - llx, ury - lly);
     tp.BeginVariableText();
     tp.SaveState();
     tp.Rectangle(3f, 3f, urx - llx - 6f, ury - lly - 6f);
     tp.Clip();
     tp.NewPath();
     tp.BeginText();
     tp.SetFontAndSize(font, fontSize);
     tp.ResetRGBColorFill();
     tp.SetTextMatrix(4, 5);
     var tokenizer = new StringTokenizer(text, "\n");
     float yPos = ury - lly;
     while (tokenizer.HasMoreTokens()) {
     yPos -= fontSize * 1.2f;
     tp.ShowTextAligned(PdfContentByte.ALIGN_LEFT, tokenizer.NextToken(), 3, yPos, 0);
     }
     tp.EndText();
     tp.RestoreState();
     tp.EndVariableText();
     field.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, tp);
 }
Exemplo n.º 2
0
        public MemoryStream ExecuteQueryWith(Student student)
        {
            MemoryStream ms = new MemoryStream();

            Document document = new Document(PageSize.A4, 10f, 10f, 125f, 10f);

            PdfWriter.GetInstance(document, ms);//new FileStream("e:\\table.pdf", FileMode.Create));
            document.Open();
            var img = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, @"download.jpg"));

            img.ScalePercent(35);
            PdfPCell cell = new PdfPCell(img);

            cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            PdfPTable table = new PdfPTable(2);

            float[] widths = new float[] { 2f, 7f };
            table.SetWidths(widths);
            PdfPTable row    = new PdfPTable(1);
            PdfPTable table1 = new PdfPTable(2);

            var      p2      = new PdfPCell(new Phrase("NIVEDITA EDUCATIONAL TRUST(R)", FontFactory.GetFont("Arial", 12)));
            BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
            var      times   = new iTextSharp.text.Font(bfTimes, 15, iTextSharp.text.Font.BOLD);
            var      p3      = new PdfPCell(new Phrase("Nivedita School of Nursing", times));

            var p5 = new PdfPCell(new Phrase("Station Area, Hyderabad - Road - YADGIRI- 585 202.", FontFactory.GetFont("Arial", 12)));

            p2.Colspan = 2;
            p3.Colspan = 2;
            p5.Colspan = 2;

            p2.BorderWidth = 0;
            p3.BorderWidth = 0;
            p5.BorderWidth = 0;

            p2.HorizontalAlignment = 1;
            p3.HorizontalAlignment = 1;
            p5.HorizontalAlignment = 1;

            table1.AddCell(p2);
            table1.AddCell(p3);
            table1.AddCell(p5);
            row.AddCell(table1);
            table.AddCell(cell);
            table.AddCell(row);

            document.Add(table);

            PdfPTable secondRow = new PdfPTable(1);

            var s1 = new PdfPCell(new Phrase("FEE RECEIPT", GetFont(12f)));

            s1.HorizontalAlignment = 1;
            secondRow.AddCell(s1);
            document.Add(secondRow);

            PdfPTable thirdRow    = new PdfPTable(1);
            PdfPTable nameSection = new PdfPTable(2);

            nameSection.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            var p6 = new Phrase("Name: " + student.Name, FontFactory.GetFont("Arial", 12));

            var p7    = new Phrase("No:     ", FontFactory.GetFont("Arial", 12));
            var p8    = new Phrase("Date: " + student.DateOfAdmission.FormatDate("/"), FontFactory.GetFont("Arial", 12));
            var cell1 = new PdfPCell(p6);

            cell1.BorderWidth = 0;

            cell1.Colspan = 2;

            var cell2 = new PdfPCell(p7);

            //cell2.Colspan = 3;
            cell2.BorderWidth = 0;
            nameSection.AddCell(cell2);
            nameSection.AddCell(p8);
            nameSection.AddCell(cell1);
            thirdRow.AddCell(nameSection);
            document.Add(thirdRow);

            PdfPTable fourthRow = new PdfPTable(3);

            float[] width = new float[] { 1f, 5f, 3f };
            fourthRow.SetWidths(width);
            var c1 = new PdfPCell(new Phrase("Sl. No", GetFont(12f)));
            var c2 = new PdfPCell(new Phrase("Particulars", GetFont(12f)));



            PdfPTable headings      = new PdfPTable(2);
            var       amountHeading = new PdfPCell(new Phrase("Amount", GetFont(12f)));

            amountHeading.Colspan             = 2;
            amountHeading.HorizontalAlignment = 1;
            amountHeading.BorderWidth         = 0;
            var rupeesHeading = new PdfPCell(new Phrase("Rs", GetFont(12f)));

            rupeesHeading.HorizontalAlignment = 0;
            rupeesHeading.BorderWidth         = 0;

            var paiseHeading = new PdfPCell(new Phrase("Ps", GetFont(12f)));

            paiseHeading.HorizontalAlignment = 2;
            paiseHeading.BorderWidth         = 0;

            headings.AddCell(amountHeading);
            headings.AddCell(rupeesHeading);
            headings.AddCell(paiseHeading);
            c1.HorizontalAlignment = 1;
            c2.HorizontalAlignment = 1;
            fourthRow.AddCell(c1);
            fourthRow.AddCell(c2);
            fourthRow.AddCell(headings);

            document.Add(fourthRow);

            PdfPTable            fifthRow = new PdfPTable(4);
            IList <FeeStructure> fees     = new List <FeeStructure> {
                new FeeStructure {
                    Description = "Admission Fee", Amount = student.AdmissionFee
                }, new FeeStructure {
                    Description = "Tution Fee", Amount = student.CourseFee
                },
                new FeeStructure {
                    Description = "Phyciatric Fee", Amount = student.PhyciatricFee
                }, new FeeStructure {
                    Description = "Lab Fee", Amount = student.LabFee
                },
                new FeeStructure {
                    Description = "Library Fee", Amount = student.LibraryFee
                }, new FeeStructure {
                    Description = "Sports Fee", Amount = student.SportsFee
                },
                new FeeStructure {
                    Description = "Medical Fee", Amount = student.MedicalFee
                }, new FeeStructure {
                    Description = "Transportation Fee", Amount = student.TransportationFee
                },
                new FeeStructure {
                    Description = "Examination Fees Board / Class", Amount = student.ExaminationFee
                }, new FeeStructure {
                    Description = "Hostel", Amount = student.HostelFee
                },
                new FeeStructure {
                    Description = "Mess", Amount = student.MessFee
                }, new FeeStructure {
                    Description = "Books Fee", Amount = student.BooksFee
                },
                new FeeStructure {
                    Description = "Uniform", Amount = student.UniformFee
                }, new FeeStructure {
                    Description = "Caution Deposit", Amount = student.CautionDepositFee
                },
                new FeeStructure {
                    Description = "Other Fees", Amount = student.OtherFee
                }, new FeeStructure {
                    Description = "Total Fee Rs.", Amount = student.TotalFee
                },
                new FeeStructure {
                    Description = "Total Fee Paid Rs.", Amount = student.PaidFee
                }, new FeeStructure {
                    Description = "Due Fee Rs.", Amount = student.DueFee
                }
            };

            fifthRow.SetWidths(new float[] { 1f, 5f, 2f, 1f });
            FillValues(document, fifthRow, fees);
            PdfPTable sixthRow = new PdfPTable(1);
            PdfPTable footer   = new PdfPTable(2);

            footer.SetWidths(new float[] { 5f, 2f });
            var c4 = new PdfPCell(new Phrase("Rupeesin words: " + changeToWords(student.PaidFee.ToString(), false) + " only", FontFactory.GetFont("Arial", 12)));

            c4.Colspan = 2;
            footer.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;

            var c6 = new PdfPCell(new Phrase("Accountant", FontFactory.GetFont("Arial", 12)));

            c6.HorizontalAlignment = 2;
            c6.Colspan             = 2;
            c4.BorderWidth         = 0;
            c6.BorderWidth         = 0;
            footer.AddCell(c4);
            footer.AddCell(c6);
            sixthRow.AddCell(footer);
            document.Add(sixthRow);
            document.Close();
            ms.Close();
            return(ms);
        }
Exemplo n.º 3
0
 /** Each font used in a document has an instance of this class.
  * This class stores the characters used in the document and other
  * specifics unique to the current working document.
  * @param fontName the font name
  * @param indirectReference the indirect reference to the font
  * @param baseFont the <CODE>BaseFont</CODE>
  */
 internal FontDetails(PdfName fontName, PdfIndirectReference indirectReference, BaseFont baseFont)
 {
     this.fontName = fontName;
     this.indirectReference = indirectReference;
     this.baseFont = baseFont;
     fontType = baseFont.FontType;
     switch (fontType) {
         case BaseFont.FONT_TYPE_T1:
         case BaseFont.FONT_TYPE_TT:
             shortTag = new byte[256];
             break;
         case BaseFont.FONT_TYPE_CJK:
             cjkTag = new IntHashtable();
             cjkFont = (CJKFont)baseFont;
             break;
         case BaseFont.FONT_TYPE_TTUNI:
             longTag = new Hashtable();
             ttu = (TrueTypeFontUnicode)baseFont;
             symbolic = baseFont.IsFontSpecific();
             break;
     }
 }
Exemplo n.º 4
0
 public PdfFormField AddResetButton(string name, string caption, string value, BaseFont font, float fontSize, float llx, float lly, float urx, float ury)
 {
     PdfAction action = PdfAction.CreateResetForm(null, 0);
     PdfFormField button = new PdfFormField(writer, llx, lly, urx, ury, action);
     SetButtonParams(button, PdfFormField.FF_PUSHBUTTON, name, value);
     DrawButton(button, caption, font, fontSize, llx, lly, urx, ury);
     AddFormField(button);
     return button;
 }
Exemplo n.º 5
0
 /// <summary>
 /// Constructs a Font.
 /// </summary>
 /// <param name="bf">the external font</param>
 /// <param name="size">the size of this font</param>
 /// <param name="style">the style of this font</param>
 /// <param name="color">the Color of this font.</param>
 public Font(BaseFont bf, float size, int style, Color color)
 {
     this.baseFont = bf;
     this.size = size;
     this.style = style;
     this.color = color;
 }
Exemplo n.º 6
0
 /** Hyphenates a word and returns the first part of it. To get
  * the second part of the hyphenated word call <CODE>getHyphenatedWordPost()</CODE>.
  * @param word the word to hyphenate
  * @param font the font used by this word
  * @param fontSize the font size used by this word
  * @param remainingWidth the width available to fit this word in
  * @return the first part of the hyphenated word including
  * the hyphen symbol, if any
  */
 public string GetHyphenatedWordPre(string word, BaseFont font, float fontSize, float remainingWidth)
 {
     post = word;
     string hyphen = this.HyphenSymbol;
     float hyphenWidth = font.GetWidthPoint(hyphen, fontSize);
     if (hyphenWidth > remainingWidth)
         return "";
     var hyphenation = hyphenator.Hyphenate(word);
     if (hyphenation == null) {
         return "";
     }
     int len = hyphenation.Length;
     int k;
     for (k = 0; k < len; ++k) {
         if (font.GetWidthPoint(hyphenation.GetPreHyphenText(k), fontSize) + hyphenWidth > remainingWidth)
             break;
     }
     --k;
     if (k < 0)
         return "";
     post = hyphenation.GetPostHyphenText(k);
     return hyphenation.GetPreHyphenText(k) + hyphen;
 }
Exemplo n.º 7
0
            public static int GetTextWidth(string text, BaseFont baseFont, float fontSize)
            {
                float width = baseFont.GetWidthPoint(text, fontSize);

                return((int)(width));
            }
        public void GenerarPDF(DataTable dt, string fecha, string hora, string total, string proveedor)
        {
            try
            {
                //instanciamos el documento
                Document     pdfDoc  = new Document(PageSize.A4, 10, 10, 10, 10);
                MemoryStream PDFData = new MemoryStream();
                PdfWriter    writer  = PdfWriter.GetInstance(pdfDoc, PDFData);
                //tipos de fuentes que vamos a utilizar
                var       titleFont     = FontFactory.GetFont("Arial", 12, Font.BOLD);
                var       titleFontBlue = FontFactory.GetFont("Arial", 14, Font.NORMAL, BaseColor.BLUE);
                var       boldTableFont = FontFactory.GetFont("Arial", 8, Font.BOLD);
                var       bodyFont      = FontFactory.GetFont("Arial", 8, Font.NORMAL);
                var       EmailFont     = FontFactory.GetFont("Arial", 8, Font.NORMAL, BaseColor.BLUE);
                BaseColor TabelHeaderBackGroundColor = WebColors.GetRGBColor("#EEEEEE");

                Rectangle pageSize = writer.PageSize;
                // abrimos el documento para escribir
                pdfDoc.Open();
                //Agregamos los elementos para el documento

                #region Top table
                // creamos la tabla del encabezado
                PdfPTable headertable = new PdfPTable(3);
                headertable.HorizontalAlignment = 0;
                headertable.WidthPercentage     = 100;
                headertable.SetWidths(new float[] { 100f, 320f, 100f });  // Establecemos las dimensiones de las columnas
                headertable.DefaultCell.Border = Rectangle.NO_BORDER;
                //headertable.DefaultCell.Border = Rectangle.BOX; //para probar el codigo

                //colocamos el logo
                iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/ImagenesSistema/logoGym.JPG"));
                logo.ScaleToFit(100, 15);

                {
                    PdfPCell pdfCelllogo = new PdfPCell(logo);
                    pdfCelllogo.Border            = Rectangle.NO_BORDER;
                    pdfCelllogo.BorderColorBottom = new BaseColor(System.Drawing.Color.Black);
                    pdfCelllogo.BorderWidthBottom = 1f;
                    headertable.AddCell(pdfCelllogo);
                }

                {
                    PdfPCell middlecell = new PdfPCell();
                    middlecell.Border            = Rectangle.NO_BORDER;
                    middlecell.BorderColorBottom = new BaseColor(System.Drawing.Color.Black);
                    middlecell.BorderWidthBottom = 1f;
                    headertable.AddCell(middlecell);
                }

                {
                    PdfPTable nested = new PdfPTable(1);
                    nested.DefaultCell.Border = Rectangle.NO_BORDER;
                    PdfPCell nextPostCell1 = new PdfPCell(new Phrase("THE GYM", titleFont));
                    nextPostCell1.Border = Rectangle.NO_BORDER;
                    nested.AddCell(nextPostCell1);
                    PdfPCell nextPostCell2 = new PdfPCell(new Phrase("Salta, Argentina", bodyFont));
                    nextPostCell2.Border = Rectangle.NO_BORDER;
                    nested.AddCell(nextPostCell2);
                    PdfPCell nextPostCell3 = new PdfPCell(new Phrase("Av. Entre Rios 865", bodyFont));
                    nextPostCell3.Border = Rectangle.NO_BORDER;
                    nested.AddCell(nextPostCell3);
                    PdfPCell nextPostCell4 = new PdfPCell(new Phrase("*****@*****.**", EmailFont));
                    nextPostCell4.Border = Rectangle.NO_BORDER;
                    nested.AddCell(nextPostCell4);
                    nested.AddCell("");
                    PdfPCell nesthousing = new PdfPCell(nested);
                    nesthousing.Border            = Rectangle.NO_BORDER;
                    nesthousing.BorderColorBottom = new BaseColor(System.Drawing.Color.Black);
                    nesthousing.BorderWidthBottom = 1f;
                    nesthousing.Rowspan           = 5;
                    nesthousing.PaddingBottom     = 10f;
                    headertable.AddCell(nesthousing);
                }


                PdfPTable Invoicetable = new PdfPTable(3);
                Invoicetable.HorizontalAlignment = 0;
                Invoicetable.WidthPercentage     = 100;
                Invoicetable.SetWidths(new float[] { 100f, 320f, 100f });  // establecemos el ancho de las columnas
                Invoicetable.DefaultCell.Border = Rectangle.NO_BORDER;

                {
                    PdfPTable nested = new PdfPTable(1);
                    nested.DefaultCell.Border = Rectangle.NO_BORDER;
                    PdfPCell nextPostCell1 = new PdfPCell(new Phrase("PARA:", bodyFont));
                    nextPostCell1.Border = Rectangle.NO_BORDER;
                    nested.AddCell(nextPostCell1);
                    PdfPCell nextPostCell2 = new PdfPCell(new Phrase(proveedor, titleFont));
                    nextPostCell2.Border = Rectangle.NO_BORDER;
                    nested.AddCell(nextPostCell2);
                    PdfPCell nextPostCell3 = new PdfPCell(new Phrase("", bodyFont));
                    nextPostCell3.Border = Rectangle.NO_BORDER;
                    nested.AddCell(nextPostCell3);
                    PdfPCell nextPostCell4 = new PdfPCell(new Phrase("", EmailFont));
                    nextPostCell4.Border = Rectangle.NO_BORDER;
                    nested.AddCell(nextPostCell4);
                    nested.AddCell("");
                    PdfPCell nesthousing = new PdfPCell(nested);
                    nesthousing.Border = Rectangle.NO_BORDER;
                    //nesthousing.BorderColorBottom = new BaseColor(System.Drawing.Color.Black);
                    //nesthousing.BorderWidthBottom = 1f;
                    nesthousing.Rowspan       = 5;
                    nesthousing.PaddingBottom = 10f;
                    Invoicetable.AddCell(nesthousing);
                }

                {
                    PdfPCell middlecell = new PdfPCell();
                    middlecell.Border = Rectangle.NO_BORDER;
                    //middlecell.BorderColorBottom = new BaseColor(System.Drawing.Color.Black);
                    //middlecell.BorderWidthBottom = 1f;
                    Invoicetable.AddCell(middlecell);
                }


                {
                    PdfPTable nested = new PdfPTable(1);
                    nested.DefaultCell.Border = Rectangle.NO_BORDER;
                    PdfPCell nextPostCell1 = new PdfPCell(new Phrase("ORDEN DE COMPRA", titleFontBlue));
                    nextPostCell1.Border = Rectangle.NO_BORDER;
                    nested.AddCell(nextPostCell1);
                    PdfPCell nextPostCell2 = new PdfPCell(new Phrase("Fecha: " + DateTime.Now.ToShortDateString(), bodyFont));
                    nextPostCell2.Border = Rectangle.NO_BORDER;
                    nested.AddCell(nextPostCell2);
                    PdfPCell nextPostCell3 = new PdfPCell(new Phrase(" " + fecha, bodyFont));
                    nextPostCell3.Border = Rectangle.NO_BORDER;
                    nested.AddCell(nextPostCell3);
                    nested.AddCell("");
                    PdfPCell nesthousing = new PdfPCell(nested);
                    nesthousing.Border = Rectangle.NO_BORDER;
                    //nesthousing.BorderColorBottom = new BaseColor(System.Drawing.Color.Black);
                    //nesthousing.BorderWidthBottom = 1f;
                    nesthousing.Rowspan       = 5;
                    nesthousing.PaddingBottom = 10f;
                    Invoicetable.AddCell(nesthousing);
                }


                pdfDoc.Add(headertable);
                Invoicetable.PaddingTop = 10f;

                pdfDoc.Add(Invoicetable);
                #endregion

                #region Items Table
                //Create body table
                PdfPTable itemTable = new PdfPTable(2);

                itemTable.HorizontalAlignment = 0;
                itemTable.WidthPercentage     = 100;
                itemTable.SetWidths(new float[] { 40, 10 });  // then set the column's __relative__ widths
                itemTable.SpacingAfter       = 40;
                itemTable.DefaultCell.Border = Rectangle.BOX;
                PdfPCell cell1 = new PdfPCell(new Phrase("Producto", boldTableFont));
                cell1.BackgroundColor     = TabelHeaderBackGroundColor;
                cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                itemTable.AddCell(cell1);
                PdfPCell cell2 = new PdfPCell(new Phrase("Cantidad", boldTableFont));
                cell2.BackgroundColor     = TabelHeaderBackGroundColor;
                cell2.HorizontalAlignment = 1;
                itemTable.AddCell(cell2);
                foreach (DataRow row in dt.Rows)
                {
                    //instanciamos variables para los elementos del datatable
                    string productonombre   = row[1].ToString();
                    string cantidadproducto = row[0].ToString();
                    //insertamos en la tabla el nombre
                    PdfPCell numberCell = new PdfPCell(new Phrase(productonombre, bodyFont));
                    numberCell.HorizontalAlignment = 1;
                    numberCell.PaddingLeft         = 10f;
                    numberCell.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER;
                    itemTable.AddCell(numberCell);
                    //insertamos en la tabla la cantidad
                    var _phrase = new Phrase();
                    _phrase.Add(new Chunk(cantidadproducto, EmailFont));
                    PdfPCell descCell = new PdfPCell(_phrase);
                    descCell.HorizontalAlignment = 0;
                    descCell.PaddingLeft         = 10f;
                    descCell.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER;
                    itemTable.AddCell(descCell);
                }
                //pie de tabla
                PdfPCell totalAmtCell1 = new PdfPCell(new Phrase(""));
                totalAmtCell1.Border = Rectangle.LEFT_BORDER | Rectangle.TOP_BORDER;
                itemTable.AddCell(totalAmtCell1);
                PdfPCell totalAmtCell2 = new PdfPCell(new Phrase(""));
                totalAmtCell2.Border = Rectangle.TOP_BORDER; //Rectangle.NO_BORDER; //Rectangle.TOP_BORDER;
                itemTable.AddCell(totalAmtCell2);
                //PdfPCell totalAmtCell3 = new PdfPCell(new Phrase(""));
                //totalAmtCell3.Border = Rectangle.TOP_BORDER; //Rectangle.NO_BORDER; //Rectangle.TOP_BORDER;
                //itemTable.AddCell(totalAmtCell3);
                //PdfPCell totalAmtStrCell = new PdfPCell(new Phrase("Total", boldTableFont));
                //totalAmtStrCell.Border = Rectangle.TOP_BORDER;   //Rectangle.NO_BORDER; //Rectangle.TOP_BORDER;
                //totalAmtStrCell.HorizontalAlignment = 1;
                //itemTable.AddCell(totalAmtStrCell);
                //PdfPCell totalAmtCell = new PdfPCell(new Phrase("TOTAL", boldTableFont));
                //totalAmtCell.HorizontalAlignment = 1;
                //itemTable.AddCell(totalAmtCell);

                PdfPCell cell = new PdfPCell(new Phrase("***NOTA: Se acepta hasta un cargo del 0.5% en el periodo de 30 days. ***", bodyFont));
                cell.Colspan             = 5;
                cell.HorizontalAlignment = 1;
                itemTable.AddCell(cell);
                pdfDoc.Add(itemTable);
                #endregion

                PdfContentByte cb = new PdfContentByte(writer);


                BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, true);
                cb = new PdfContentByte(writer);
                cb = writer.DirectContent;
                cb.BeginText();
                cb.SetFontAndSize(bf, 8);
                cb.SetTextMatrix(pageSize.GetLeft(120), 20);
                cb.ShowText("Esta factura es válida como comprobante de solicitud de reposición");
                cb.EndText();

                //Movemos el puntero y dibujamos una linea para separa el resto del documento del footer
                cb.MoveTo(40, pdfDoc.PageSize.GetBottom(50));
                cb.LineTo(pdfDoc.PageSize.Width - 40, pdfDoc.PageSize.GetBottom(50));
                cb.Stroke();

                //cerramos el PDF
                pdfDoc.Close();
                DownloadPDF(PDFData);
            }
            catch (Exception ex)
            {
                lblerrorPDF.Text = ex.Message.ToString();
            }
        }
Exemplo n.º 9
0
 // constructors
 /**
  * Constructs a <CODE>PdfChunk</CODE>-object.
  *
  * @param string the content of the <CODE>PdfChunk</CODE>-object
  * @param font the <CODE>PdfFont</CODE>
  * @param attributes the metrics attributes
  * @param noStroke the non metric attributes
  */
 internal PdfChunk(string str, PdfChunk other)
 {
     thisChunk[0] = this;
     value = str;
     this.font = other.font;
     this.attributes = other.attributes;
     this.noStroke = other.noStroke;
     this.baseFont = other.baseFont;
     Object[] obj = (Object[])attributes[Chunk.IMAGE];
     if (obj == null)
         image = null;
     else {
         image = (Image)obj[0];
         offsetX = (float)obj[1];
         offsetY = (float)obj[2];
         changeLeading = (bool)obj[3];
     }
     encoding = font.Font.Encoding;
     splitCharacter = (ISplitCharacter)noStroke[Chunk.SPLITCHARACTER];
     if (splitCharacter == null)
         splitCharacter = DefaultSplitCharacter.DEFAULT;
 }
Exemplo n.º 10
0
        /**
         * Constructs a <CODE>PdfChunk</CODE>-object.
         *
         * @param chunk the original <CODE>Chunk</CODE>-object
         * @param action the <CODE>PdfAction</CODE> if the <CODE>Chunk</CODE> comes from an <CODE>Anchor</CODE>
         */
        internal PdfChunk(Chunk chunk, PdfAction action)
        {
            thisChunk[0] = this;
            value = chunk.Content;

            Font f = chunk.Font;
            float size = f.Size;
            if (size == Legacy.Text.Font.UNDEFINED)
                size = 12;
            baseFont = f.BaseFont;
            BaseFont bf = f.BaseFont;
            int style = f.Style;
            if (style == Legacy.Text.Font.UNDEFINED) {
                style = Legacy.Text.Font.NORMAL;
            }
            if (baseFont == null) {
                // translation of the font-family to a PDF font-family
                baseFont = f.GetCalculatedBaseFont(false);
            }
            else{
                // bold simulation
                if ((style & Legacy.Text.Font.BOLD) != 0)
                    attributes[Chunk.TEXTRENDERMODE] = new Object[]{PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, size / 30f, null};
                // italic simulation
                if ((style & Legacy.Text.Font.ITALIC) != 0)
                    attributes[Chunk.SKEW] = new float[]{0, ITALIC_ANGLE};
            }
            font = new PdfFont(baseFont, size);
            // other style possibilities
            Hashtable attr = chunk.Attributes;
            if (attr != null) {
                foreach (DictionaryEntry entry in attr) {
                    string name = (string)entry.Key;
                    if (keysAttributes.ContainsKey(name)) {
                        attributes[name] = entry.Value;
                    }
                    else if (keysNoStroke.ContainsKey(name)) {
                        noStroke[name] = entry.Value;
                    }
                }
                if ("".Equals(attr[Chunk.GENERICTAG])) {
                    attributes[Chunk.GENERICTAG] = chunk.Content;
                }
            }
            if (f.IsUnderlined()) {
                Object[] obj = {null, new float[]{0, 1f / 15, 0, -1f / 3, 0}};
                Object[][] unders = Utilities.AddToArray((Object[][])attributes[Chunk.UNDERLINE], obj);
                attributes[Chunk.UNDERLINE] = unders;
            }
            if (f.IsStrikethru()) {
                Object[] obj = {null, new float[]{0, 1f / 15, 0, 1f / 3, 0}};
                Object[][] unders = Utilities.AddToArray((Object[][])attributes[Chunk.UNDERLINE], obj);
                attributes[Chunk.UNDERLINE] = unders;
            }
            if (action != null)
                attributes[Chunk.ACTION] = action;
            // the color can't be stored in a PdfFont
            noStroke[Chunk.COLOR] = f.Color;
            noStroke[Chunk.ENCODING] = font.Font.Encoding;
            Object[] obj2 = (Object[])attributes[Chunk.IMAGE];
            if (obj2 == null)
                image = null;
            else {
                attributes.Remove(Chunk.HSCALE); // images are scaled in other ways
                image = (Image)obj2[0];
                offsetX = ((float)obj2[1]);
                offsetY = ((float)obj2[2]);
                changeLeading = (bool)obj2[3];
            }
            font.Image = image;
            object hs = attributes[Chunk.HSCALE];
            if (hs != null)
                font.HorizontalScaling = (float)hs;
            encoding = font.Font.Encoding;
            splitCharacter = (ISplitCharacter)noStroke[Chunk.SPLITCHARACTER];
            if (splitCharacter == null)
                splitCharacter = DefaultSplitCharacter.DEFAULT;
        }
Exemplo n.º 11
0
 public ITextmyHtmlHandler(IDocListener document, BaseFont bf)
     : base(document, new HtmlTagMap(), bf)
 {
 }
Exemplo n.º 12
0
 protected static ArrayList BreakLines(ArrayList breaks, BaseFont font, float fontSize, float width)
 {
     ArrayList lines = new ArrayList();
     StringBuilder buf = new StringBuilder();
     for (int ck = 0; ck < breaks.Count; ++ck) {
         buf.Length = 0;
         float w = 0;
         char[] cs = ((String)breaks[ck]).ToCharArray();
         int len = cs.Length;
         // 0 inline first, 1 inline, 2 spaces
         int state = 0;
         int lastspace = -1;
         char c = (char)0;
         int refk = 0;
         for (int k = 0; k < len; ++k) {
             c = cs[k];
             switch (state) {
                 case 0:
                     w += font.GetWidthPoint(c, fontSize);
                     buf.Append(c);
                     if (w > width) {
                         w = 0;
                         if (buf.Length > 1) {
                             --k;
                             buf.Length = buf.Length - 1;
                         }
                         lines.Add(buf.ToString());
                         buf.Length = 0;
                         refk = k;
                         if (c == ' ')
                             state = 2;
                         else
                             state = 1;
                     }
                     else {
                         if (c != ' ')
                             state = 1;
                     }
                     break;
                 case 1:
                     w += font.GetWidthPoint(c, fontSize);
                     buf.Append(c);
                     if (c == ' ')
                         lastspace = k;
                     if (w > width) {
                         w = 0;
                         if (lastspace >= 0) {
                             k = lastspace;
                             buf.Length = lastspace - refk;
                             TrimRight(buf);
                             lines.Add(buf.ToString());
                             buf.Length = 0;
                             refk = k;
                             lastspace = -1;
                             state = 2;
                         }
                         else {
                             if (buf.Length > 1) {
                                 --k;
                                 buf.Length = buf.Length - 1;
                             }
                             lines.Add(buf.ToString());
                             buf.Length = 0;
                             refk = k;
                             if (c == ' ')
                                 state = 2;
                         }
                     }
                     break;
                 case 2:
                     if (c != ' ') {
                         w = 0;
                         --k;
                         state = 1;
                     }
                     break;
             }
         }
         TrimRight(buf);
         lines.Add(buf.ToString());
     }
     return lines;
 }
Exemplo n.º 13
0
 /** Creates a new instance of DocumentFont */
 internal DocumentFont(PRIndirectReference refFont)
 {
     encoding = "";
     fontSpecific = false;
     this.refFont = refFont;
     fontType = FONT_TYPE_DOCUMENT;
     font = (PdfDictionary)PdfReader.GetPdfObject(refFont);
     fontName = PdfName.DecodeName(font.GetAsName(PdfName.BASEFONT).ToString());
     PdfName subType = font.GetAsName(PdfName.SUBTYPE);
     if (PdfName.TYPE1.Equals(subType) || PdfName.TRUETYPE.Equals(subType))
         DoType1TT();
     else {
         for (int k = 0; k < cjkNames.Length; ++k) {
             if (fontName.StartsWith(cjkNames[k])) {
                 fontName = cjkNames[k];
                 cjkMirror = BaseFont.CreateFont(fontName, cjkEncs[k], false);
                 return;
             }
         }
         String enc = PdfName.DecodeName(font.GetAsName(PdfName.ENCODING).ToString());
         for (int k = 0; k < cjkEncs2.Length; ++k) {
             if (enc.StartsWith(cjkEncs2[k])) {
                 if (k > 3)
                     k -= 4;
                 cjkMirror = BaseFont.CreateFont(cjkNames2[k], cjkEncs2[k], false);
                 return;
             }
         }
         if (PdfName.TYPE0.Equals(subType) && enc.Equals("Identity-H")) {
             ProcessType0(font);
             isType0 = true;
         }
     }
 }
Exemplo n.º 14
0
        private void btnpdf2_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd5 = new SaveFileDialog();

            sfd5.Filter   = "PDF (*.pdf)|*.pdf";
            sfd5.FileName = "Palveluiden_Raportti.pdf";
            bool fileError = false;

            iTextSharp.text.Font     f    = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN);
            iTextSharp.text.Document pdfD = new iTextSharp.text.Document(PageSize.A4);
            pdfD.SetMargins(70, 70, 110, 110);
            Paragraph prg = new Paragraph("Raportti/Palvelut, Newbie Village" + Chunk.NEWLINE + Chunk.NEWLINE, f);

            if (dgvPalvRapsa.Rows.Count > 0)
            {
                if (sfd5.ShowDialog() == DialogResult.OK)
                {   //Tarkistaa, onko saman niminen tiedosto
                    if (File.Exists(sfd5.FileName))
                    {
                        try
                        {   //Jos on, yrittää poistaa vanhan
                            File.Delete(sfd5.FileName);
                        }
                        catch (IOException ex)
                        {
                            fileError = true;
                            MessageBox.Show("Raportin kirjoittaminen ei onnistunut!" + ex.Message);
                        }
                    }
                    if (!fileError)
                    {
                        try
                        {
                            //Lukee raportti-dgv:n
                            PdfPTable pdf = new PdfPTable(dgvPalvRapsa.Columns.Count);
                            pdf.DefaultCell.Padding = 3;
                            pdf.WidthPercentage     = 100;
                            pdf.HorizontalAlignment = Element.ALIGN_LEFT;

                            BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED);

                            iTextSharp.text.Font text = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
                            foreach (DataGridViewColumn column in dgvPalvRapsa.Columns)
                            {
                                PdfPCell cell = new PdfPCell(new iTextSharp.text.Phrase(column.HeaderText, text));
                                pdf.AddCell(cell);
                            }
                            string pdfcell;
                            foreach (DataGridViewRow row in dgvPalvRapsa.Rows)
                            {
                                foreach (DataGridViewCell cell in row.Cells)
                                {
                                    if (cell.Value == null)
                                    {
                                        pdfcell = null;
                                    }
                                    else
                                    {
                                        pdfcell = cell.Value.ToString();
                                        pdf.AddCell(new Phrase(pdfcell, text));
                                    }
                                }
                            }
                            using (FileStream stream = new FileStream(sfd5.FileName, FileMode.Create))
                            {
                                //Tekee pdf:n
                                PdfWriter.GetInstance(pdfD, stream);
                                pdfD.Open();
                                pdfD.Add(prg);
                                pdfD.Add(pdf);

                                pdfD.Close();
                                stream.Close();
                            }
                            MessageBox.Show("Raportin tekeminen onnistui!", "Info");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Error! Raportin kirjoittaminen ei onnistunut" + ex.Message);
                        }
                    }
                }
            }
        }
Exemplo n.º 15
0
        private void Export(DataGridView dg, String Header, string filename)
        {
            BaseFont  bf       = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED);
            PdfPTable pdftable = new PdfPTable(dg.Columns.Count);

            //MessageBox.Show(dg.Columns.Count.ToString());
            pdftable.DefaultCell.PaddingTop    = 20;
            pdftable.DefaultCell.PaddingBottom = 20;
            pdftable.WidthPercentage           = 100;
            pdftable.HorizontalAlignment       = Element.ALIGN_LEFT;
            pdftable.DefaultCell.BorderWidth   = 1;
            iTextSharp.text.Font text = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
            //Add Header
            foreach (DataGridViewColumn column in dg.Columns)
            {
                PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, text));
                //cell.BackgroundColor = new iTextSharp.text.Color(240,240,240);
                pdftable.AddCell(cell);
            }
            //add data row

            foreach (DataGridViewRow row in dg.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    //here HERERERERERERER
                    pdftable.AddCell(new Phrase(cell.Value.ToString(), text));
                }
            }
            var savefiledialoge = new SaveFileDialog();

            savefiledialoge.FileName   = filename;
            savefiledialoge.DefaultExt = ".pdf";
            string imageFilePath = @"C:\Users\User\Desktop\Materi Kuliah\Refer Matkul Sem 5\Pemrograman Platform Khusus\Logo.png";

            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
            jpg.ScaleToFit(80, 120);
            jpg.Alignment = iTextSharp.text.Image.UNDERLYING;
            jpg.SetAbsolutePosition(250, 25);

            if (savefiledialoge.ShowDialog() == DialogResult.OK)
            {
                using (FileStream stream = new FileStream(savefiledialoge.FileName, FileMode.Create))
                {
                    Document  pdfdoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
                    PdfWriter writer = PdfWriter.GetInstance(pdfdoc, stream);

                    pdfdoc.Open();
                    Paragraph            prg    = new Paragraph(" == Hasil Raport ==");
                    Paragraph            pr     = new Paragraph(" ");
                    BaseFont             bfHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                    iTextSharp.text.Font fthead = new iTextSharp.text.Font(bfHead, 16, 1);
                    prg.Alignment = Element.ALIGN_CENTER;
                    prg.Add(new Chunk(Header.ToUpper()));
                    pdfdoc.Add(prg);
                    pdfdoc.Add(pr);
                    pdfdoc.Add(pr);
                    pdfdoc.Add(jpg);
                    LineSeparator underline = new LineSeparator(5, 100, null, Element.ALIGN_CENTER, -2);
                    pdfdoc.Add(underline);
                    pdfdoc.Add(pdftable);
                    pdfdoc.Close();
                    stream.Close();
                }
            }
        }
Exemplo n.º 16
0
        public void ExportDataTableToPdf(DataTable dtblTable, String strPdfPath, string strHeader)
        {
            System.IO.FileStream fs       = new FileStream(strPdfPath, FileMode.Create, FileAccess.Write, FileShare.None);
            Document             document = new Document();

            document.SetPageSize(iTextSharp.text.PageSize.A4);
            PdfWriter writer = PdfWriter.GetInstance(document, fs);

            document.Open();

            //Report Header
            BaseFont  bfntHead   = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font      fntHead    = new Font(bfntHead, 16, 1, Color.GRAY);
            Paragraph prgHeading = new Paragraph();

            prgHeading.Alignment = Element.ALIGN_CENTER;
            prgHeading.Add(new Chunk(strHeader.ToUpper(), fntHead));
            document.Add(prgHeading);

            //Author
            Paragraph prgAuthor = new Paragraph();
            BaseFont  btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font      fntAuthor = new Font(btnAuthor, 8, 2, Color.GRAY);

            prgAuthor.Alignment = Element.ALIGN_RIGHT;
            prgAuthor.Add(new Chunk("Author : Stock Manager", fntAuthor));
            prgAuthor.Add(new Chunk("\nRun Date : " + DateTime.Now.ToShortDateString(), fntAuthor));
            document.Add(prgAuthor);

            //Add a line seperation
            Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, Color.BLACK, Element.ALIGN_LEFT, 1)));

            document.Add(p);

            //Add line break
            document.Add(new Chunk("\n", fntHead));

            //Write the table
            PdfPTable table = new PdfPTable(dtblTable.Columns.Count);
            //Table header
            BaseFont btnColumnHeader = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntColumnHeader = new Font(btnColumnHeader, 10, 1, Color.WHITE);

            for (int i = 0; i < dtblTable.Columns.Count; i++)
            {
                PdfPCell cell = new PdfPCell();
                cell.BackgroundColor = Color.GRAY;
                cell.AddElement(new Chunk(dtblTable.Columns[i].ColumnName.ToUpper(), fntColumnHeader));
                table.AddCell(cell);
            }
            //table Data
            for (int i = 0; i < dtblTable.Rows.Count; i++)
            {
                for (int j = 0; j < dtblTable.Columns.Count; j++)
                {
                    table.AddCell(dtblTable.Rows[i][j].ToString());
                }
            }

            document.Add(table);
            document.Close();
            writer.Close();
            fs.Close();
        }
Exemplo n.º 17
0
        protected void ReportExportPDF(List <ReportSaleItemDTO> lst)
        {
            MemoryStream ms  = new MemoryStream();
            Document     doc = new Document(PageSize.A4, 3, 3, 7, 3);
            //var output = new FileStream(Server.MapPath(filename), FileMode.Create);
            var writer = PdfWriter.GetInstance(doc, ms);

            doc.Open();
            try
            {
                #region Variable
                BaseColor  bc = new BaseColor(255, 255, 255);
                float[]    widths;
                string     header     = "";
                string     fontFamily = "C:/Windows/Fonts/Tahoma.ttf";
                BaseFont   bf         = BaseFont.CreateFont(fontFamily, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                Font       fontTitle  = new Font(bf, 12, iTextSharp.text.Font.BOLD);
                Font       fontHeader = new Font(bf, 10);
                Font       fontGrid   = new Font(bf, 9);
                PdfPTable  table      = new PdfPTable(1);
                PdfPTable  tableGrid  = new PdfPTable(4);
                PdfPCell[] cellAry;
                PdfPRow    row;
                PdfPCell   cell1 = new PdfPCell();
                PdfPCell   cell2 = new PdfPCell();
                PdfPCell   cell3 = new PdfPCell();
                PdfPCell   cell4 = new PdfPCell();
                table.WidthPercentage     = 95;
                tableGrid.WidthPercentage = 95;
                DateTime dateFrom = string.IsNullOrEmpty(txtDateFrom.Text) ? DateTime.MinValue : DateTime.ParseExact(txtDateFrom.Text, "dd/MM/yyyy", new System.Globalization.CultureInfo("en-US"));
                DateTime dateTo   = string.IsNullOrEmpty(txtDateTo.Text) ? DateTime.MaxValue : DateTime.ParseExact(txtDateTo.Text, "dd/MM/yyyy", new System.Globalization.CultureInfo("en-US")).AddDays(1);

                #endregion

                header = "รายงานการขายตามสินค้า : ";
                if (dateFrom == DateTime.MinValue && dateTo == DateTime.MaxValue)
                {
                    header = header + "ทั้งหมด";
                }
                else
                {
                    header = header + "ตั้งแต่วันที่ " + txtDateFrom.Text + " ถึง " + txtDateTo.Text;
                }
                cell1 = GetNewCell(false);
                cell1.AddElement(GetNewParag(header, fontTitle));
                cellAry = new PdfPCell[] { cell1 };
                row     = new PdfPRow(cellAry);
                table.Rows.Add(row);

                cell1 = GetNewCell(false);
                cell1.AddElement(GetNewParag(" ", fontHeader));
                cellAry = new PdfPCell[] { cell1 };
                row     = new PdfPRow(cellAry);
                table.Rows.Add(row);
                doc.Add(table);

                cell1 = GetNewCell(true);
                cell2 = GetNewCell(true);
                cell3 = GetNewCell(true);
                cell4 = GetNewCell(true);

                cell1.AddElement(GetNewParag("ลำดับ", fontHeader, 1));
                cell2.AddElement(GetNewParag("สินค้า", fontHeader, 1));
                cell3.AddElement(GetNewParag("ขาย", fontHeader, 1));
                cell4.AddElement(GetNewParag("แถม", fontHeader, 1));

                cellAry = new PdfPCell[] { cell1, cell2, cell3, cell4 };
                row     = new PdfPRow(cellAry);
                widths  = new float[] { 10f, 65f, 10f, 10f };
                tableGrid.SetWidths(widths);
                tableGrid.Rows.Add(row);

                foreach (ReportSaleItemDTO item in lst)
                {
                    cell1 = GetNewCell(true);
                    cell2 = GetNewCell(true);
                    cell3 = GetNewCell(true);
                    cell4 = GetNewCell(true);

                    cell1.AddElement(GetNewParag(item.No.ToString(), fontGrid, 1));
                    cell2.AddElement(GetNewParag(item.ItemName, fontGrid));
                    cell3.AddElement(GetNewParag(item.AmountStr, fontGrid, 1));
                    cell4.AddElement(GetNewParag(item.AmountFreeStr, fontGrid, 1));

                    cellAry = new PdfPCell[] { cell1, cell2, cell3, cell4 };
                    row     = new PdfPRow(cellAry);
                    tableGrid.Rows.Add(row);
                }
                doc.Add(tableGrid);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                doc.Close();
                writer.Close();
            }

            string filename = "ReportSaleItem_" + DateTime.Now.ToString("yyyyMMdd");
            Response.Clear();
            Response.Buffer          = false;
            Response.ContentEncoding = Encoding.UTF8;
            Response.HeaderEncoding  = Encoding.UTF8;
            Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".pdf");
            Response.ContentType = "application/pdf";
            Response.BinaryWrite(ms.ToArray());
            Response.Flush();
            Response.SuppressContent = true;
        }
Exemplo n.º 18
0
        public static void Genera(string sourcePath, string title, List <InventoryReportModel> data)
        {
            sourcePath = HttpContext.Current.Server.MapPath(sourcePath);
            //定义一个Document,并设置页面大小为A4,竖向
            iTextSharp.text.Document doc = new Document(PageSize.A4);
            try
            {
                //写实例
                PdfWriter.GetInstance(doc, new FileStream(sourcePath, FileMode.Create));
                //打开document
                doc.Open();


                //载入字体
                BaseFont baseFont = BaseFont.CreateFont(
                    "C:\\WINDOWS\\FONTS\\SIMHEI.TTF", //黑体
                    BaseFont.IDENTITY_H,              //横向字体
                    BaseFont.NOT_EMBEDDED);
                iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 9);

                #region 其他元素

                doc.Add(new Paragraph(title, font));


                //包含页码没有任何边框的页脚。
                iTextSharp.text.HeaderFooter footer = new iTextSharp.text.HeaderFooter(new Phrase("This is page: "), true);
                footer.Border = iTextSharp.text.Rectangle.NO_BORDER;
                doc.Footer    = footer;

                //构建了一个简单的表:

                int   rows   = data.Count;
                Table aTable = new Table(15, rows + 1);
                aTable.AutoFillEmptyCells = true;
                //行 从1开始,列 从0开始
                #region 表头
                // Chunk chunk1 = new Chunk("This text is underlined", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.UNDEFINED));
                // Cell cell=new Cell(chunk1);
                //aTable.AddCell(cell,ne
                aTable.AddCell("序号", new System.Drawing.Point(1, 0));
                aTable.AddCell("耗材规格", new System.Drawing.Point(1, 1));
                aTable.AddCell("期初库存数", new System.Drawing.Point(1, 2));
                aTable.AddCell("期初库存数", new System.Drawing.Point(1, 3));
                aTable.AddCell("期初库存额", new System.Drawing.Point(1, 4));
                aTable.AddCell("入库数", new System.Drawing.Point(1, 5));
                aTable.AddCell("入库额", new System.Drawing.Point(1, 6));
                aTable.AddCell("出库数", new System.Drawing.Point(1, 7));
                aTable.AddCell("出库额", new System.Drawing.Point(1, 8));
                aTable.AddCell("期末库存数", new System.Drawing.Point(1, 9));
                aTable.AddCell("期末库存额", new System.Drawing.Point(1, 10));
                aTable.AddCell("期初结余量", new System.Drawing.Point(1, 11));
                aTable.AddCell("期初结余额", new System.Drawing.Point(1, 12));
                aTable.AddCell("期末结余量", new System.Drawing.Point(1, 13));
                aTable.AddCell("期末结余额", new System.Drawing.Point(1, 14));
                #endregion
                #region 内容
                for (int i = 0; i < rows; i++)
                {
                    var item = data[i];
                    aTable.AddCell((i + 1).ToString(), new System.Drawing.Point(i + 2, 0));
                    aTable.AddCell(item.material_specification_name + "(" + @item.material_specification_model + ")", new System.Drawing.Point(i + 2, 1));
                    aTable.AddCell(item.unit_html, new System.Drawing.Point(i + 2, 2));
                    aTable.AddCell(item.inventory_reports_beginning_amount.Value.ToString(), new System.Drawing.Point(i + 2, 3));
                    aTable.AddCell(item.inventory_reports_beginning_cost.Value.ToString("N"), new System.Drawing.Point(i + 2, 4));
                    aTable.AddCell(item.inventory_reports_in_amount.Value.ToString(), new System.Drawing.Point(i + 2, 5));
                    aTable.AddCell(item.inventory_reports_in_cost.Value.ToString("N"), new System.Drawing.Point(i + 2, 6));
                    aTable.AddCell(item.inventory_reports_out_amount.Value.ToString(), new System.Drawing.Point(i + 2, 7));
                    aTable.AddCell(item.inventory_reports_out_cost.Value.ToString("N"), new System.Drawing.Point(i + 2, 8));
                    aTable.AddCell(item.inventory_reports_ending_amount.Value.ToString(), new System.Drawing.Point(i + 2, 9));
                    aTable.AddCell(item.inventory_reports_ending_cost.Value.ToString("N"), new System.Drawing.Point(i + 2, 10));
                    aTable.AddCell(item.beginning_locale_amount.Value.ToString(), new System.Drawing.Point(i + 2, 11));
                    aTable.AddCell(item.beginning_locale_cost.Value.ToString("N"), new System.Drawing.Point(i + 2, 12));
                    aTable.AddCell(item.ending_locale_amount.Value.ToString(), new System.Drawing.Point(i + 2, 13));
                    aTable.AddCell(item.ending_locale_cost.Value.ToString("N"), new System.Drawing.Point(i + 2, 14));
                }
                #endregion
                doc.Add(aTable);



                #endregion
                //关闭document
                doc.Close();
                //打开PDF,看效果
                //Process.Start(sourcePath);
            }
            catch (DocumentException de)
            {
                Console.WriteLine(de.Message);
                Console.ReadKey();
            }
            catch (IOException io)
            {
                Console.WriteLine(io.Message);
                Console.ReadKey();
            }
        }
Exemplo n.º 19
0
        private void button3_Click(object sender, EventArgs e)
        {
            ///设置导出字体
            string path     = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
            string FontPath = path + "\\simsun.ttc";
            int    FontSize = 12;

            if (File.Exists(FontPath))
            {
                FontPath += ",1";
            }
            else
            {
                MessageBox.Show("Wrong!");
                return;
            }


            Boolean        cc = false;
            string         strFileName;
            SaveFileDialog savFile = new SaveFileDialog();

            savFile.Filter = "PDF文件|.pdf";
            savFile.ShowDialog();
            if (savFile.FileName != "")
            {
                strFileName = savFile.FileName;
            }
            else
            {
                return;
            }

            Document document = new Document(PageSize.A4.Rotate(), 25, 25, 25, 25);

            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));

            BaseFont baseFont = BaseFont.CreateFont(
                FontPath,
                BaseFont.IDENTITY_H,
                BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, FontSize);

            document.Open();

            int ColCount = 0;

            for (int j = 0; j < dataGridView1.Columns.Count; j++)
            {
                if (dataGridView1.Columns[j].Visible == true)
                {
                    ColCount++;
                }
            }
            PdfPTable table = new PdfPTable(ColCount);

            // table.DefaultCell.BackgroundColor = BaseColor.BLUE;
            for (int j = 0; j < dataGridView1.Columns.Count; j++)
            {
                if (dataGridView1.Columns[j].Visible == true)
                {
                    table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText, font));
                }
            }

            table.HeaderRows = 1;

            // table.DefaultCell.BackgroundColor = BaseColor.WHITE;

            for (int j = 0; j < dataGridView1.Rows.Count; j++)
            {
                for (int k = 0; k < dataGridView1.Columns.Count; k++)
                {
                    if (dataGridView1.Rows[j].Cells[k].Visible == true)
                    {
                        try
                        {
                            string value = "";
                            if (dataGridView1.Rows[j].Cells[k].Value != null)
                            {
                                value = dataGridView1.Rows[j].Cells[k].Value.ToString();
                            }
                            table.AddCell(new Phrase(value, font));
                        }
                        catch (Exception)
                        {
                            //MessageBox.Show(e.Message);
                            cc = true;
                        }
                    }
                }
            }
            document.Add(table);
            document.Close();
            writer.Close();
            MessageBox.Show("Export successful!!");
        }
Exemplo n.º 20
0
 /// <summary>
 /// Constructs a Font.
 /// </summary>
 /// <param name="bf">the external font</param>
 /// <param name="size">the size of this font</param>
 public Font(BaseFont bf, float size)
     : this(bf, size, UNDEFINED, null)
 {
 }
Exemplo n.º 21
0
 // This is the method writing text to the content byte
 private static void WriteText(PdfContentByte cb, string text, int xPos, int yPos, BaseFont font, int size)
 {
     cb.SetFontAndSize(font, size);
     cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, xPos, yPos, 0);
 }
Exemplo n.º 22
0
 private Phrase ComposePhrase(String text, BaseFont ufont, Color color, float fontSize)
 {
     Phrase phrase = null;
     if (extensionFont == null && (substitutionFonts == null || substitutionFonts.Count == 0))
         phrase = new Phrase(new Chunk(text, new Font(ufont, fontSize, 0, color)));
     else {
         FontSelector fs = new FontSelector();
         fs.AddFont(new Font(ufont, fontSize, 0, color));
         if (extensionFont != null)
             fs.AddFont(new Font(extensionFont, fontSize, 0, color));
         if (substitutionFonts != null) {
             foreach (BaseFont bf in substitutionFonts) {
                 fs.AddFont(new Font(bf, fontSize, 0, color));
             }
         }
         phrase = fs.Process(text);
     }
     return phrase;
 }
Exemplo n.º 23
0
        public ValueCreationBlock()
        {
            filenameBlank = filename.Replace(".", "_Blank.");

            FileStream fs = new System.IO.FileStream(filenameBlank, System.IO.FileMode.Create);

            writer = PdfWriter.GetInstance(doc, fs);
            doc.Open();
            cb = writer.DirectContent;

            BaseFont bfHelvetica = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false);
            Font     helvetica12 = new Font(bfHelvetica, 12, Font.NORMAL, BaseColor.BLACK);

            PdfPTable table = new PdfPTable(2);

            table.TotalWidth  = 570f;
            table.LockedWidth = true;
            //relative col widths in proportions - 1/3 and 2/3
            float[] widths = new float[] { 2f, 3f };
            table.SetWidths(widths);
            table.HorizontalAlignment = Element.ALIGN_CENTER;


            PdfPCell cell1 = new PdfPCell(new Phrase("Value Creation and Impact", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.WHITE)));

            cell1.PaddingLeft         = 10;
            cell1.BackgroundColor     = PDFColor.BCGGreen;
            cell1.Colspan             = 3;
            cell1.Border              = PdfPCell.NO_BORDER;
            cell1.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
            table.AddCell(cell1);

            PdfPTable nested = new PdfPTable(1);
            //nested.TotalWidth = 270f;
            //nested.LockedWidth = true;
            //float[] widthforcol = new float[] { 100f, 170f};
            //nested.SetWidths(widthforcol);

            PdfPCell cell2 = new PdfPCell(new Phrase("Develops clear recommendations with an action bias", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.BLACK)));

            cell2.PaddingLeft = 10;
            //cell2.Colspan = 2;
            cell2.BackgroundColor     = BaseColor.LIGHT_GRAY;
            cell2.Border              = PdfPCell.NO_BORDER;
            cell2.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
            nested.AddCell(cell2);

            PdfPCell cell3 = new PdfPCell(new Phrase("Networks within client organization to understand agenda", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.BLACK)));

            cell3.PaddingLeft = 10;
            //cell3.Colspan = 2;
            cell3.BackgroundColor     = BaseColor.LIGHT_GRAY;
            cell3.Border              = PdfPCell.NO_BORDER;
            cell3.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
            nested.AddCell(cell3);

            PdfPCell cell4 = new PdfPCell(new Phrase("Is able to assess implementation challenges", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.BLACK)));

            cell4.PaddingLeft = 10;
            //cell4.Colspan = 2;
            cell4.BackgroundColor     = BaseColor.LIGHT_GRAY;
            cell4.Border              = PdfPCell.NO_BORDER;
            cell4.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
            nested.AddCell(cell4);

            PdfPCell cell5 = new PdfPCell(new Phrase("Applies expertise to generate superior and sustainable results for client; is committed to making change happen", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.BLACK)));

            cell5.PaddingLeft = 10;
            //cell5.Colspan = 2;
            cell5.BackgroundColor     = BaseColor.LIGHT_GRAY;
            cell5.Border              = PdfPCell.NO_BORDER;
            cell5.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
            nested.AddCell(cell5);

            PdfPCell cell6 = new PdfPCell(new Phrase("Effectively transfers capabilities to client teams", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.BLACK)));

            cell6.PaddingLeft = 10;
            //cell6.Colspan = 2;
            cell6.BackgroundColor     = BaseColor.LIGHT_GRAY;
            cell6.Border              = PdfPCell.NO_BORDER;
            cell6.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
            nested.AddCell(cell6);

            //Rectangle rect = new iTextSharp.text.Rectangle(10, 20, 30, 40);
            //var rf1 = new RadioCheckField(writer, rect, "cellRadioBox", "on");
            //rf1.CheckType = RadioCheckField.TYPE_CHECK;
            //PdfFormField field = rf1.CheckField;

            string[] labels = { "NA", "1", "2", "3", "4", "5" };
            BaseFont bf     = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
            // create a radio field spanning different pages
            PdfFormField radiogroup = PdfFormField.CreateRadioButton(writer, true);

            radiogroup.FieldName = "language";
            //Rectangle rect = new Rectangle(40, 606, 60, 588);
            RadioCheckField radio;
            PdfFormField    radiofield;
            Rectangle       rect;

            for (int i = 0; i < labels.Length; ++i)
            {
                rect = new Rectangle(50 + i * 30, 705, 50 + (i + 1) * 30, 695);//PDFDocPageSize.RIGHT
                //rect = new Rectangle(40, 606, 60, 588);
                radio = new RadioCheckField(writer, rect, null, labels[i]);
                radio.BackgroundColor  = new GrayColor(0.8f);
                radiofield             = radio.RadioField;
                radiofield.PlaceInPage = 1;
                //radiofield.PlaceInPage= ++page;
                radiogroup.AddKid(radiofield);
            }


            var      radioEvents = new iTextSharp.text.pdf.events.FieldPositioningEvents(writer, radiogroup);
            PdfPCell radioCell   = new PdfPCell();

            radioCell.CellEvent = radioEvents;
            nested.AddCell(radioCell);

            PdfPCell nesthousing = new PdfPCell(nested);

            nesthousing.Padding = 0f;
            table.AddCell(nesthousing);
            TextField textfield = new TextField(writer, new iTextSharp.text.Rectangle(10, 20, 30, 40), "cellTextBox");
            PdfPCell  tbCell    = new PdfPCell(new Phrase(" ", helvetica12));

            iTextSharp.text.pdf.events.FieldPositioningEvents events =
                new iTextSharp.text.pdf.events.FieldPositioningEvents(writer, textfield.GetTextField());
            tbCell.CellEvent = events;
            table.AddCell(tbCell);

            doc.Add(table);

            this.doc.Close();

            GetReader();


            //Add common Javascript code
            writer.AddJavaScript("var requiredFields = ['text1', 'grp1'];");
            string validateFunction = "function validate () { " +
                                      " for (i=0; i<requiredFields.length; i++) {" +
                                      " var grp = this.getField(requiredFields[i]);  if (!grp || grp.value === null || grp.value == ''|| grp.value=='Off') { " +
                                      " app.alert('please select this '+ requiredFields[i]); return false; }}" +
                                      "return true}";

            writer.AddJavaScript(validateFunction);


            //Close all the streams
            stamper.Close();
            reader.Close();
            doc.Close();
        }
Exemplo n.º 24
0
 public PdfFormField AddComboBox(string name, string[,] options, string defaultValue, bool editable, BaseFont font, float fontSize, float llx, float lly, float urx, float ury)
 {
     PdfFormField choice = PdfFormField.CreateCombo(writer, editable, options, 0);
     SetChoiceParams(choice, name, defaultValue, llx, lly, urx, ury);
     string value = null;
     for (int i = 0; i < options.GetLength(0); i++) {
     if (options[i, 0].Equals(defaultValue)) {
         value = options[i, 1];
         break;
     }
     }
     if (value == null) {
     value = options[0, 1];
     }
     DrawSingleLineOfText(choice, value, font, fontSize, llx, lly, urx, ury);
     AddFormField(choice);
     return choice;
 }
Exemplo n.º 25
0
        /// <summary>
        /// Constructs a Font-object.
        /// </summary>
        /// <param name="fontname">the name of the font</param>
        /// <param name="encoding">the encoding of the font</param>
        /// <param name="embedded">true if the font is to be embedded in the PDF</param>
        /// <param name="size">the size of this font</param>
        /// <param name="style">the style of this font</param>
        /// <param name="color">the BaseColor of this font</param>
        /// <param name="cached">true if the font comes from the cache or is added to the cache if new, false if the font is always created new</param>
        /// <returns>a Font object</returns>
        public virtual Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached)
        {
            if (fontname == null)
            {
                return(new Font(Font.FontFamily.UNDEFINED, size, style, color));
            }
            string        lowercasefontname = fontname.ToLower(CultureInfo.InvariantCulture);
            List <string> tmp;

            fontFamilies.TryGetValue(lowercasefontname, out tmp);
            if (tmp != null)
            {
                // some bugs were fixed here by Daniel Marczisovszky
                int  fs    = Font.NORMAL;
                bool found = false;
                int  s     = style == Font.UNDEFINED ? Font.NORMAL : style;
                foreach (string f in tmp)
                {
                    string lcf = f.ToLower(CultureInfo.InvariantCulture);
                    fs = Font.NORMAL;
                    if (lcf.ToLower(CultureInfo.InvariantCulture).IndexOf("bold") != -1)
                    {
                        fs |= Font.BOLD;
                    }
                    if (lcf.ToLower(CultureInfo.InvariantCulture).IndexOf("italic") != -1 || lcf.ToLower(CultureInfo.InvariantCulture).IndexOf("oblique") != -1)
                    {
                        fs |= Font.ITALIC;
                    }
                    if ((s & Font.BOLDITALIC) == fs)
                    {
                        fontname = f;
                        found    = true;
                        break;
                    }
                }
                if (style != Font.UNDEFINED && found)
                {
                    style &= ~fs;
                }
            }
            BaseFont basefont = null;

            try {
                try {
                    // the font is a type 1 font or CJK font
                    basefont = BaseFont.CreateFont(fontname, encoding, embedded, cached, null, null, true);
                }
                catch (DocumentException) {
                }
                if (basefont == null)
                {
                    // the font is a true type font or an unknown font
                    trueTypeFonts.TryGetValue(fontname.ToLower(CultureInfo.InvariantCulture), out fontname);
                    // the font is not registered as truetype font
                    if (fontname == null)
                    {
                        return(new Font(Font.FontFamily.UNDEFINED, size, style, color));
                    }
                    // the font is registered as truetype font
                    basefont = BaseFont.CreateFont(fontname, encoding, embedded, cached, null, null);
                }
            }
            catch (DocumentException de) {
                // this shouldn't happen
                throw de;
            }
            catch (System.IO.IOException) {
                // the font is registered as a true type font, but the path was wrong
                return(new Font(Font.FontFamily.UNDEFINED, size, style, color));
            }
            catch {
                // null was entered as fontname and/or encoding
                return(new Font(Font.FontFamily.UNDEFINED, size, style, color));
            }
            return(new Font(basefont, size, style, color));
        }
Exemplo n.º 26
0
 public PdfFormField AddSingleLineTextField(string name, string text, BaseFont font, float fontSize, float llx, float lly, float urx, float ury)
 {
     PdfFormField field = PdfFormField.CreateTextField(writer, PdfFormField.SINGLELINE, PdfFormField.PLAINTEXT, 0);
     SetTextFieldParams(field, text, name, llx, lly, urx, ury);
     DrawSingleLineOfText(field, text, font, fontSize, llx, lly, urx, ury);
     AddFormField(field);
     return field;
 }
Exemplo n.º 27
0
 /// <summary>
 /// Register a ttf- or a ttc-file and use an alias for the font contained in the ttf-file.
 /// </summary>
 /// <param name="path">the path to a ttf- or ttc-file</param>
 /// <param name="alias">the alias you want to use for the font</param>
 public virtual void Register(string path, string alias)
 {
     try {
         if (path.ToLower(CultureInfo.InvariantCulture).EndsWith(".ttf") || path.ToLower(CultureInfo.InvariantCulture).EndsWith(".otf") || path.ToLower(CultureInfo.InvariantCulture).IndexOf(".ttc,") > 0)
         {
             Object[] allNames = BaseFont.GetAllFontNames(path, BaseFont.WINANSI, null);
             trueTypeFonts[((string)allNames[0]).ToLower(CultureInfo.InvariantCulture)] = path;
             if (alias != null)
             {
                 trueTypeFonts[alias.ToLower(CultureInfo.InvariantCulture)] = path;
             }
             // register all the font names with all the locales
             string[][] names = (string[][])allNames[2]; //full name
             for (int i = 0; i < names.Length; i++)
             {
                 trueTypeFonts[names[i][3].ToLower(CultureInfo.InvariantCulture)] = path;
             }
             string fullName   = null;
             string familyName = null;
             names = (string[][])allNames[1]; //family name
             for (int k = 0; k < TTFamilyOrder.Length; k += 3)
             {
                 foreach (string[] name in names)
                 {
                     if (TTFamilyOrder[k].Equals(name[0]) && TTFamilyOrder[k + 1].Equals(name[1]) && TTFamilyOrder[k + 2].Equals(name[2]))
                     {
                         familyName = name[3].ToLower(CultureInfo.InvariantCulture);
                         k          = TTFamilyOrder.Length;
                         break;
                     }
                 }
             }
             if (familyName != null)
             {
                 String lastName = "";
                 names = (string[][])allNames[2]; //full name
                 foreach (string[] name in names)
                 {
                     for (int k = 0; k < TTFamilyOrder.Length; k += 3)
                     {
                         if (TTFamilyOrder[k].Equals(name[0]) && TTFamilyOrder[k + 1].Equals(name[1]) && TTFamilyOrder[k + 2].Equals(name[2]))
                         {
                             fullName = name[3];
                             if (fullName.Equals(lastName))
                             {
                                 continue;
                             }
                             lastName = fullName;
                             RegisterFamily(familyName, fullName, null);
                             break;
                         }
                     }
                 }
             }
         }
         else if (path.ToLower(CultureInfo.InvariantCulture).EndsWith(".ttc"))
         {
             string[] names = BaseFont.EnumerateTTCNames(path);
             for (int i = 0; i < names.Length; i++)
             {
                 Register(path + "," + i);
             }
         }
         else if (path.ToLower(CultureInfo.InvariantCulture).EndsWith(".afm") || path.ToLower(CultureInfo.InvariantCulture).EndsWith(".pfm"))
         {
             BaseFont bf         = BaseFont.CreateFont(path, BaseFont.CP1252, false);
             String   fullName   = (bf.FullFontName[0][3]).ToLower(CultureInfo.InvariantCulture);
             String   familyName = (bf.FamilyFontName[0][3]).ToLower(CultureInfo.InvariantCulture);
             String   psName     = bf.PostscriptFontName.ToLower(CultureInfo.InvariantCulture);
             RegisterFamily(familyName, fullName, null);
             trueTypeFonts[psName]   = path;
             trueTypeFonts[fullName] = path;
         }
     }
     catch (DocumentException de) {
         // this shouldn't happen
         throw de;
     }
     catch (System.IO.IOException ioe) {
         throw ioe;
     }
 }
Exemplo n.º 28
0
 // constructors
 internal PdfFont(BaseFont bf, float size)
 {
     this.size = size;
     font = bf;
 }
        public void ExportOneInfoToPdf(PurchaseOperationInformation purchaseInfo)
        {
            Document document;
            string   fileSavePath = fileSaveLocation.PurchaseReportPdfLocation;
            string   fileName     = "PurchaseReport" + purchaseInfo.PurchaseNo + ".pdf";

            FileStream fileStream = new FileStream(fileSavePath + fileName, FileMode.Create, FileAccess.Write, FileShare.None);

            document = new Document(PageSize.A4, 70f, 70f, 50f, 50f);
            PdfWriter pdfWriter = PdfWriter.GetInstance(document, fileStream);

            document.Open();

            document.Add(defaultReport.ReportHeader());

            // Report Info
            BaseFont  bfnInfo      = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font      fntInfo      = new Font(bfnInfo, 10, 1, BaseColor.BLACK);
            Font      fntInfoSmall = new Font(bfnInfo, 8, 1, BaseColor.BLACK);
            Paragraph prgInfo      = new Paragraph();

            prgInfo.Alignment = Element.ALIGN_LEFT;
            prgInfo.Add((new Chunk("Purchase No: ", fntInfo)));
            prgInfo.Add((new Chunk(purchaseInfo.PurchaseNo, fntInfoSmall)));
            prgInfo.Add((new Chunk("\nBranch: ", fntInfo)));
            prgInfo.Add((new Chunk(purchaseInfo.Branch.Address, fntInfoSmall)));
            prgInfo.Add((new Chunk("\nSupplier: ", fntInfo)));
            prgInfo.Add((new Chunk(purchaseInfo.Supplier.Name, fntInfoSmall)));
            prgInfo.Add((new Chunk("\nPurchase By: ", fntInfo)));
            prgInfo.Add((new Chunk(purchaseInfo.Employee.Name, fntInfoSmall)));
            prgInfo.Add((new Chunk("\nRemarks: ", fntInfo)));
            prgInfo.Add((new Chunk(purchaseInfo.Remarks, fntInfoSmall)));
            prgInfo.Add((new Chunk("\nDate: ", fntInfo)));
            prgInfo.Add((new Chunk(purchaseInfo.PurchaseDate.ToString("D"), fntInfoSmall)));
            document.Add(prgInfo);

            // Break
            document.Add(new Chunk("\n", fntInfo));

            // Table Start
            PdfPTable table = new PdfPTable(5);

            table.HorizontalAlignment = Element.ALIGN_LEFT;

            // Table Header
            BaseFont bfnTableHeader = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntTableHeader = new Font(bfnTableHeader, 10, 1, BaseColor.BLACK);

            PdfPCell cellSl = new PdfPCell();

            cellSl.AddElement(new Chunk("SL", fntTableHeader));
            cellSl.Border = 0;
            table.AddCell(cellSl);

            PdfPCell cellItem = new PdfPCell();

            cellItem.AddElement(new Chunk("Item", fntTableHeader));
            cellItem.Border = 0;
            table.AddCell(cellItem);

            PdfPCell cellQty = new PdfPCell();

            cellQty.AddElement(new Chunk("Qty", fntTableHeader));
            cellQty.Border = 0;
            table.AddCell(cellQty);

            PdfPCell cellPrice = new PdfPCell();

            cellPrice.AddElement(new Chunk("Price", fntTableHeader));
            cellPrice.Border = 0;
            table.AddCell(cellPrice);

            PdfPCell cellLineTotal = new PdfPCell();

            cellLineTotal.AddElement(new Chunk("Total", fntTableHeader));
            cellLineTotal.Border = 0;
            table.AddCell(cellLineTotal);

            // Table Data
            int      sl           = 1;
            BaseFont bfnTableData = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntTableData = new Font(bfnTableData, 8, 1, BaseColor.BLACK);

            foreach (var item in purchaseInfo.PurchaseItems)
            {
                PdfPCell cellItemSl = new PdfPCell();
                cellItemSl.AddElement(new Chunk((sl++).ToString(), fntTableData));
                cellItemSl.Border = 0;
                table.AddCell(cellItemSl);

                PdfPCell cellItemItem = new PdfPCell();
                cellItemItem.AddElement(new Chunk(item.Item.Name.ToString(), fntTableData));
                cellItemItem.Border = 0;
                table.AddCell(cellItemItem);

                PdfPCell cellItemQty = new PdfPCell();
                cellItemQty.AddElement(new Chunk(item.Quantity.ToString(), fntTableData));
                cellItemQty.Border = 0;
                table.AddCell(cellItemQty);

                PdfPCell cellItemUnitPrice = new PdfPCell();
                cellItemUnitPrice.AddElement(new Chunk(item.UnitPrice.ToString(), fntTableData));
                cellItemUnitPrice.Border = 0;
                table.AddCell(cellItemUnitPrice);

                PdfPCell cellItemLineTotal = new PdfPCell();
                cellItemLineTotal.AddElement(new Chunk(item.LineTotal.ToString(), fntTableData));
                cellItemLineTotal.Border = 0;
                table.AddCell(cellItemLineTotal);
            }

            PdfPCell borderBottom = new PdfPCell();

            borderBottom.AddElement(new Chunk("\n", fntTableData));
            borderBottom.Colspan = 5;
            borderBottom.Border  = PdfPCell.BOTTOM_BORDER;
            table.AddCell(borderBottom);

            // Total Amount
            PdfPCell nullCell = new PdfPCell();

            nullCell.Colspan = 3;
            nullCell.Border  = 0;
            table.AddCell(nullCell);

            PdfPCell cellTotal = new PdfPCell();

            cellTotal.AddElement(new Chunk("Total Amount", fntTableHeader));
            cellTotal.Border = 0;
            table.AddCell(cellTotal);

            PdfPCell cellTotalValue = new PdfPCell();

            cellTotalValue.AddElement(new Chunk(purchaseInfo.TotalAmount.ToString(), fntTableHeader));
            cellTotalValue.Border = 0;
            table.AddCell(cellTotalValue);

            document.Add(table);
            document.Close();
            pdfWriter.Close();
            fileStream.Close();
        }
Exemplo n.º 30
0
        void XuatPDF()
        {
            BaseFont bf = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + @"\\fonts\\tahoma.ttf", BaseFont.IDENTITY_H, true);

            iTextSharp.text.Font textFontVLC    = new iTextSharp.text.Font(bf, 18, iTextSharp.text.Font.BOLD, BaseColor.BLUE);
            iTextSharp.text.Font textFontHeader = new iTextSharp.text.Font(bf, 25, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font textFont       = new iTextSharp.text.Font(bf, 14, iTextSharp.text.Font.NORMAL);
            iTextSharp.text.Font damNghieng     = new iTextSharp.text.Font(bf, 14, iTextSharp.text.Font.BOLDITALIC);
            iTextSharp.text.Font nhatNghieng    = new iTextSharp.text.Font(bf, 14, iTextSharp.text.Font.ITALIC);

            Paragraph pr     = new Paragraph("CHUNG CƯ Phạm Nguyễn Hoàng Phan", textFontVLC);
            Paragraph diachi = new Paragraph("Địa chỉ: 54 Nguyễn Lương Bằng, phường Hòa Khánh Bắc, quận Liên Chiểu, Tp. Đà Nẵng\n", damNghieng);
            Paragraph sdt    = new Paragraph("Số điện thoại: 0937581934\n", damNghieng);
            Paragraph mahd   = new Paragraph("Mã hóa đơn: " + maHD, textFont);
            Paragraph header = new Paragraph("HÓA ĐƠN DỊCH VỤ", textFontHeader);

            string StrHD = @"Tên chủ hộ đang thuê: " + HoadonBLL.Instance.LayThongTin1CanHo(Convert.ToInt32(txtMaCH.Text)).hogiadinh.tenchuho + "\n" +
                           "Mã căn hộ: " + txtMaCH.Text + "\n" +
                           "Khu: " + HoadonBLL.Instance.LayThongTin1CanHo(Convert.ToInt32(txtMaCH.Text)).khu.tenkhu + "\n" +
                           "Mã nhân viên: " + txtMaNV.Text + "\n" +
                           "Ngày làm đơn: " + dtpNgayLap.Value.ToShortDateString() + "\n";
            Paragraph trong    = new Paragraph("\n");
            Paragraph doanDau  = new Paragraph(StrHD, textFont);
            PdfPTable ptable   = new PdfPTable(dgvDSDichVu.ColumnCount);
            Paragraph tongtien = new Paragraph("Tổng tiền: " + lbTT.Text, textFont);

            tongtien.Alignment = 2;

            ptable.DefaultCell.Padding     = 5;
            ptable.WidthPercentage         = 100;
            ptable.HorizontalAlignment     = Element.ALIGN_CENTER;
            ptable.DefaultCell.BorderWidth = 1;

            foreach (DataGridViewColumn col in dgvDSDichVu.Columns)
            {
                PdfPCell cell = new PdfPCell(new Phrase(col.HeaderText, textFont));
                cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
                ptable.AddCell(cell);
            }

            foreach (DataGridViewRow row in dgvDSDichVu.Rows)
            {
                foreach (DataGridViewCell c in row.Cells)
                {
                    ptable.AddCell(new Phrase(c.Value.ToString(), textFont));
                }
            }

            var saveDia = new SaveFileDialog();

            saveDia.FileName = "HD" + maHD;

            saveDia.DefaultExt = ".pdf";

            if (saveDia.ShowDialog() == DialogResult.OK)
            {
                using (FileStream fstream = new FileStream(saveDia.FileName, FileMode.Create))
                {
                    Document  pdoc = new Document(iTextSharp.text.PageSize.A4, 10, 10, 42, 35);
                    PdfWriter pwr  = PdfWriter.GetInstance(pdoc, fstream);
                    pdoc.Open();
                    pdoc.Add(pr);
                    pdoc.Add(diachi);
                    pdoc.Add(sdt);
                    pdoc.Add(mahd);
                    pdoc.Add(header);
                    pdoc.Add(doanDau);
                    pdoc.Add(trong);
                    pdoc.Add(ptable);
                    pdoc.Add(trong);
                    pdoc.Add(trong);
                    pdoc.Add(tongtien);
                    pdoc.Close();
                }
                Process.Start(saveDia.FileName);
            }
        }
        public void ExportAllInfoToPdf(IEnumerable <PurchaseOperationInformation> purchaseInfoCollection, DateTime fromDate, DateTime toDate)
        {
            List <PurchaseOperationInformation> purchaseInfoList = purchaseInfoCollection.ToList();
            Document document;
            string   fileSavePath = fileSaveLocation.PurchaseReportPdfLocation;
            string   fileName     = "PurchaseReport_" + purchaseInfoList[0].Branch.Address + "_" +
                                    fromDate.ToString("dd'.'MM'.'yyyy") + "_" +
                                    toDate.ToString("dd'.'MM'.'yyyy") + ".pdf";

            FileStream fileStream = new FileStream(fileSavePath + fileName, FileMode.Create, FileAccess.Write, FileShare.None);

            document = new Document(PageSize.A4, 50f, 50f, 30f, 30f);
            PdfWriter pdfWriter = PdfWriter.GetInstance(document, fileStream);

            document.Open();

            document.Add(defaultReport.ReportHeader());

            // Report Info
            BaseFont  bfnInfo      = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font      fntInfo      = new Font(bfnInfo, 10, 1, BaseColor.BLACK);
            Font      fntInfoSmall = new Font(bfnInfo, 8, 1, BaseColor.BLACK);
            Paragraph prgInfo      = new Paragraph();

            prgInfo.Alignment = Element.ALIGN_LEFT;
            prgInfo.Add((new Chunk("Branch: ", fntInfo)));
            prgInfo.Add((new Chunk(purchaseInfoList[0].Branch.Address, fntInfoSmall)));
            prgInfo.Add((new Chunk("\nFrom Date: ", fntInfo)));
            prgInfo.Add((new Chunk(fromDate.ToString("D"), fntInfoSmall)));
            prgInfo.Add((new Chunk("\nTo Date: ", fntInfo)));
            prgInfo.Add((new Chunk(toDate.ToString("D"), fntInfoSmall)));
            document.Add(prgInfo);

            // Break
            document.Add(new Chunk("\n", fntInfo));

            // Table Start
            PdfPTable table = new PdfPTable(6);

            table.HorizontalAlignment = Element.ALIGN_LEFT;
            table.TotalWidth          = 1000f;
            table.SetTotalWidth(new float[] { 50f, 120f, 180f, 180f, 180f, 220f });

            // Table Header
            BaseFont bfnTableHeader = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntTableHeader = new Font(bfnTableHeader, 10, 1, BaseColor.BLACK);

            PdfPCell cellSl = new PdfPCell();

            cellSl.AddElement(new Chunk("SL", fntTableHeader));
            cellSl.Border = 0;
            table.AddCell(cellSl);

            PdfPCell cellDate = new PdfPCell();

            cellDate.AddElement(new Chunk("Date", fntTableHeader));
            cellDate.Border = 0;
            table.AddCell(cellDate);

            PdfPCell cellBranch = new PdfPCell();

            cellBranch.AddElement(new Chunk("Branch", fntTableHeader));
            cellBranch.Border = 0;
            table.AddCell(cellBranch);

            PdfPCell cellSupplier = new PdfPCell();

            cellSupplier.AddElement(new Chunk("Supplier", fntTableHeader));
            cellSupplier.Border = 0;
            table.AddCell(cellSupplier);

            PdfPCell cellEmployee = new PdfPCell();

            cellEmployee.AddElement(new Chunk("Employee", fntTableHeader));
            cellEmployee.Border = 0;
            table.AddCell(cellEmployee);

            PdfPCell cellLineTotal = new PdfPCell();

            cellLineTotal.AddElement(new Chunk("Purchase Total", fntTableHeader));
            cellLineTotal.Border = 0;
            table.AddCell(cellLineTotal);

            // Table Data
            int      sl           = 1;
            BaseFont bfnTableData = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntTableData = new Font(bfnTableData, 8, 1, BaseColor.BLACK);

            double TotalAmount = 0;

            foreach (var item in purchaseInfoList)
            {
                PdfPCell cellItemSl = new PdfPCell();
                cellItemSl.AddElement(new Chunk((sl++).ToString(), fntTableData));
                cellItemSl.Border = 0;
                table.AddCell(cellItemSl);

                PdfPCell cellItemDate = new PdfPCell();
                cellItemDate.AddElement(new Chunk(item.PurchaseDate.ToString("d"), fntTableData));
                cellItemDate.Border = 0;
                table.AddCell(cellItemDate);

                PdfPCell cellItemBranch = new PdfPCell();
                cellItemBranch.AddElement(new Chunk(item.Branch.Address.ToString(), fntTableData));
                cellItemBranch.Border = 0;
                table.AddCell(cellItemBranch);

                PdfPCell cellItemSupplier = new PdfPCell();
                cellItemSupplier.AddElement(new Chunk(item.Supplier.Name.ToString(), fntTableData));
                cellItemSupplier.Border = 0;
                table.AddCell(cellItemSupplier);

                PdfPCell cellItemEmployee = new PdfPCell();
                cellItemEmployee.AddElement(new Chunk(item.Employee.Name.ToString(), fntTableData));
                cellItemEmployee.Border = 0;
                table.AddCell(cellItemEmployee);

                PdfPCell cellItemLineTotal = new PdfPCell();
                cellItemLineTotal.AddElement(new Chunk(item.TotalAmount.ToString(), fntTableData));
                cellItemLineTotal.Border = 0;
                table.AddCell(cellItemLineTotal);

                TotalAmount += item.TotalAmount;
            }

            PdfPCell borderBottom = new PdfPCell();

            borderBottom.AddElement(new Chunk("\n", fntTableData));
            borderBottom.Colspan = 6;
            borderBottom.Border  = PdfPCell.BOTTOM_BORDER;
            table.AddCell(borderBottom);

            // Total Amount
            PdfPCell nullCell = new PdfPCell();

            nullCell.Colspan = 4;
            nullCell.Border  = 0;
            table.AddCell(nullCell);

            PdfPCell cellTotal = new PdfPCell();

            cellTotal.AddElement(new Chunk("Total Amount", fntTableHeader));
            cellTotal.Border = 0;
            table.AddCell(cellTotal);

            PdfPCell cellTotalValue = new PdfPCell();

            cellTotalValue.AddElement(new Chunk(TotalAmount.ToString(), fntTableHeader));
            cellTotalValue.Border = 0;
            table.AddCell(cellTotalValue);

            document.Add(table);
            document.Close();
            pdfWriter.Close();
            fileStream.Close();
        }
Exemplo n.º 32
0
        public override void SaveAs(string fileName)
        {
            PdfWriter writer = null;
            var       doc    = new Document();

            try
            {
                writer = PdfWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create));

                doc.Open();

                var baseFont   = BaseFont.CreateFont("C:\\Windows\\Fonts\\arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                var font       = new Font(baseFont, 12, Font.NORMAL);
                var fontBold   = new Font(baseFont, 12, Font.BOLD);
                var fontHeader = new Font(baseFont, 14, Font.BOLD);
                var fontTitle  = new Font(baseFont, 18, Font.NORMAL);

                doc.Add(new Paragraph(Title, fontTitle));

                var table = new PdfPTable(2)
                {
                    SpacingBefore = 50
                };

                foreach (var model in Models)
                {
                    table.AddTitleTable($"{model.Id} / {model.DateOsemeneniya} - {(model.DateOtela == null ? "?" : model.DateOtela.ToString())}", fontHeader, 2);

                    table.AddCell("Идентификатор", font);
                    table.AddCell(model.Id.ToString(), font);

                    table.AddCell("Метод случки", font);
                    table.AddCell(model.MethodSluchki?.Name, font);

                    table.AddCell("Число сухих дней", font);
                    table.AddCell(model.ChisloSuhihDney.ToString(), font);

                    table.AddCell("Сер. период", font);
                    table.AddCell(model.SerPeriod.ToString(), font);

                    table.AddCell("Дата осеменения", font);
                    table.AddCell(model.DateOsemeneniya.ToString(), font);

                    table.AddCell("Дата отела", font);
                    table.AddCell((model.DateOtela == null ? "?" : model.DateOtela.ToString()), font);

                    table.AddHeaderColumn("Соответствующий бык", fontBold, 2);

                    table.AddCell("Идентификатор", font, 0, 15);
                    table.AddCell(model.Bull?.Id.ToString(), font, 0, 15);

                    table.AddCell("Месторасположение", font, 0, 15);
                    table.AddCell(model.Bull?.Location.ToString(), font, 0, 15);

                    table.AddCell("Сторонний идентификатор", font, 0, 15);
                    table.AddCell(model.Bull?.OtherId.ToString(), font, 0, 15);

                    table.AddHeaderColumn("Соответствующая корова", fontBold, 2);

                    table.AddCell("Идентификатор", font, 0, 15);
                    table.AddCell(model.Cow?.Id.ToString(), font, 0, 15);

                    table.AddCell("Имя", font, 0, 15);
                    table.AddCell(model.Cow?.Name, font, 0, 15);
                }

                doc.Add(table);
            }
            finally
            {
                writer?.Flush();
                doc.Close();

                writer = null;
                doc    = null;
            }
        }
Exemplo n.º 33
0
        private void button1_Click(object sender, EventArgs e)
        {
            Document doc = new Document(new iTextSharp.text.Rectangle(24, 12), 5, 5, 1, 1);

            try
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/codes.pdf", FileMode.Create));
                doc.Open();

                DataTable dt = new DataTable();

                dt.Columns.Add("ID");
                dt.Columns.Add("Price");
                for (int i = 0; i < 20; i++)
                {
                    DataRow row = dt.NewRow();
                    string  cod = "";
                    for (int j = 0; j < 13;)
                    {
                        bool bandera = false;

                        while (bandera)
                        {
                        }
                    }
                    row["ID"]    = "ZS00000000000000" + i.ToString();
                    row["Price"] = "100," + i.ToString();
                    dt.Rows.Add(row);
                }
                System.Drawing.Image img1 = null;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (i != 0)
                    {
                        doc.NewPage();
                    }
                    PdfContentByte cb1 = writer.DirectContent;
                    BaseFont       bf  = BaseFont.CreateFont(BaseFont.TIMES_BOLDITALIC, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

                    cb1.SetFontAndSize(bf, 2.0f);
                    cb1.BeginText();
                    cb1.SetTextMatrix(1.2f, 9.5f);
                    cb1.ShowText("Producto");
                    cb1.EndText();



                    PdfContentByte cb2 = writer.DirectContent;
                    BaseFont       bf1 = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                    cb2.SetFontAndSize(bf1, 1.3f);
                    cb2.BeginText();
                    cb2.SetTextMatrix(17.5f, 1.0f);
                    cb2.ShowText(dt.Rows[i]["Price"].ToString());
                    cb2.EndText();



                    iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
                    iTextSharp.text.pdf.Barcode128     bc = new Barcode128();
                    bc.TextAlignment = Element.ALIGN_LEFT;
                    bc.Code          = dt.Rows[i]["ID"].ToString();
                    bc.StartStopText = false;
                    bc.CodeType      = iTextSharp.text.pdf.Barcode128.EAN13;
                    bc.Extended      = true;

                    //System.Drawing.Image bimg = bc.CreateDrawingImage(System.Drawing.Color.Black, System.Drawing.Color.White);
                    //img1 = bimg;


                    iTextSharp.text.Image img = bc.CreateImageWithBarcode(cb, iTextSharp.text.BaseColor.BLACK, iTextSharp.text.BaseColor.BLACK);

                    cb.SetTextMatrix(1.5f, 3.0f);
                    img.ScaleToFit(60, 5);
                    img.SetAbsolutePosition(1.5f, 1);
                    cb.AddImage(img);
                }

                ////////////////////***********************************//////////////////////


                doc.Close();
                System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/codes.pdf");
                //MessageBox.Show("el archivo se guardo en escritorio con el nombre de codes.pdf");
            }
            catch
            {
            }
            finally
            {
                doc.Close();
            }
        }
Exemplo n.º 34
0
 /// <summary>
 /// Constractor function
 /// </summary>
 /// <param name="doc">the spcific doc pointer</param>
 public PdfReports(Document doc)
 {
     this.doc = doc;
     bf       = BaseFont.CreateFont(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "/Fonts/Fonts/GISHA.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
 }
Exemplo n.º 35
0
        public Chap1002()
        {
            Console.WriteLine("Chapter 10 example 2: Text at absolute positions");

            // step 1: creation of a document-object
            Document document = new Document();

            try
            {
                // step 2:
                // we create a writer that listens to the document
                // and directs a PDF-stream to a file
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Chap1002.pdf", FileMode.Create));

                // step 3: we open the document
                document.Open();

                // step 4: we grab the ContentByte and do some stuff with it
                PdfContentByte cb = writer.DirectContent;

                // first we draw some lines to be able to visualize the text alignment functions
                cb.SetLineWidth(0f);
                cb.MoveTo(250, 500);
                cb.LineTo(250, 800);
                cb.MoveTo(50, 700);
                cb.LineTo(400, 700);
                cb.MoveTo(50, 650);
                cb.LineTo(400, 650);
                cb.MoveTo(50, 600);
                cb.LineTo(400, 600);
                cb.Stroke();

                // we tell the ContentByte we're ready to draw text
                cb.BeginText();

                BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                cb.SetFontAndSize(bf, 12);
                String text = "Sample text for alignment";
                // we show some text starting on some absolute position with a given alignment
                cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, text + " Center", 250, 700, 0);
                cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, text + " Right", 250, 650, 0);
                cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text + " Left", 250, 600, 0);

                // we draw some text on a certain position
                cb.SetTextMatrix(100, 400);
                cb.ShowText("Text at position 100,400.");

                // we draw some rotated text on a certain position
                cb.SetTextMatrix(0, 1, -1, 0, 100, 300);
                cb.ShowText("Text at position 100,300, rotated 90 degrees.");

                // we draw some mirrored, rotated text on a certain position
                cb.SetTextMatrix(0, 1, 1, 0, 200, 200);
                cb.ShowText("Text at position 200,200, mirrored and rotated 90 degrees.");

                // we tell the contentByte, we've finished drawing text
                cb.EndText();
            }
            catch (DocumentException de)
            {
                Console.Error.WriteLine(de.Message);
            }
            catch (IOException ioe)
            {
                Console.Error.WriteLine(ioe.Message);
            }

            // step 5: we close the document
            document.Close();
        }
Exemplo n.º 36
0
        public static void Genera(string sourcePath, string content)
        {
            sourcePath = HttpContext.Current.Server.MapPath(sourcePath);
            //定义一个Document,并设置页面大小为A4,竖向
            iTextSharp.text.Document doc = new Document(PageSize.A4);
            try
            {
                //写实例
                PdfWriter.GetInstance(doc, new FileStream(sourcePath, FileMode.Create));
                //打开document
                doc.Open();


                //载入字体
                BaseFont baseFont = BaseFont.CreateFont(
                    "C:\\WINDOWS\\FONTS\\SIMHEI.TTF", //黑体
                    BaseFont.IDENTITY_H,              //横向字体
                    BaseFont.NOT_EMBEDDED);
                iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 9);


                //写入一个段落, Paragraph
                doc.Add(new Paragraph("第一段:" + content, font));
                doc.Add(new Paragraph("这是第二段 !", font));


                #region 图片
                //以下代码用来添加图片,此时图片是做为背景加入到pdf文件当中的:

                Stream inputImageStream     = new FileStream(HttpContext.Current.Server.MapPath("~/images/logo.jpg"), FileMode.Open, FileAccess.Read, FileShare.Read);
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
                image.SetAbsolutePosition(0, 0);
                image.Alignment = iTextSharp.text.Image.UNDERLYING;    //这里可以设定图片是做为背景还是做为元素添加到文件中
                doc.Add(image);

                #endregion
                #region 其他元素
                doc.Add(new Paragraph("Hello World"));
                //另起一行。有几种办法建立一个段落,如:
                Paragraph p1 = new Paragraph(new Chunk("This is my first paragraph.\n", FontFactory.GetFont(FontFactory.HELVETICA, 12)));
                Paragraph p2 = new Paragraph(new Phrase("This is my second paragraph.", FontFactory.GetFont(FontFactory.HELVETICA, 12)));
                Paragraph p3 = new Paragraph("This is my third paragraph.", FontFactory.GetFont(FontFactory.HELVETICA, 12));
                //所有有些对象将被添加到段落中:
                p1.Add("you can add string here\n\t");
                p1.Add(new Chunk("you can add chunks \n")); p1.Add(new Phrase("or you can add phrases.\n"));
                doc.Add(p1); doc.Add(p2); doc.Add(p3);

                //创建了一个内容为“hello World”、红色、斜体、COURIER字体、尺寸20的一个块:
                Chunk chunk = new Chunk("创建了一个内容为“hello World”、红色、斜体、COURIER字体、尺寸20的一个块", FontFactory.GetFont(FontFactory.COURIER, 20, iTextSharp.text.Font.COURIER, new iTextSharp.text.Color(255, 0, 0)));
                doc.Add(chunk);
                //如果你希望一些块有下划线或删除线,你可以通过改变字体风格简单做到:
                Chunk chunk1 = new Chunk("This text is underlined", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.UNDEFINED));
                Chunk chunk2 = new Chunk("This font is of type ITALIC | STRIKETHRU", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.ITALIC | iTextSharp.text.Font.STRIKETHRU));
                //改变块的背景
                chunk2.SetBackground(new iTextSharp.text.Color(0xFF, 0xFF, 0x00));
                //上标/下标
                chunk1.SetTextRise(5);
                doc.Add(chunk1);
                doc.Add(chunk2);

                //外部链接示例:
                Anchor anchor = new Anchor("website", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.UNDEFINED, new iTextSharp.text.Color(0, 0, 255)));
                anchor.Reference = "http://itextsharp.sourceforge.net";
                anchor.Name      = "website";
                //内部链接示例:
                Anchor anchor1 = new Anchor("This is an internal link\n\n");
                anchor1.Name = "link1";
                Anchor anchor2 = new Anchor("Click here to jump to the internal link\n\f");
                anchor2.Reference = "#link1";
                doc.Add(anchor); doc.Add(anchor1); doc.Add(anchor2);

                //排序列表示例:
                List list = new List(true, 20);
                list.Add(new ListItem("First line"));
                list.Add(new ListItem("The second line is longer to see what happens once the end of the line is reached. Will it start on a new line?"));
                list.Add(new ListItem("Third line"));
                doc.Add(list);

                //文本注释:
                Annotation a = new Annotation("authors", "Maybe its because I wanted to be an author myself that I wrote iText.");
                doc.Add(a);

                //包含页码没有任何边框的页脚。
                iTextSharp.text.HeaderFooter footer = new iTextSharp.text.HeaderFooter(new Phrase("This is page: "), true);
                footer.Border = iTextSharp.text.Rectangle.NO_BORDER;
                doc.Footer    = footer;


                //Chapter对象和Section对象自动构建一个树:
                iTextSharp.text.Font f1 = new iTextSharp.text.Font();
                f1.SetStyle(iTextSharp.text.Font.BOLD);
                Paragraph cTitle  = new Paragraph("This is chapter 1", f1);
                Chapter   chapter = new Chapter(cTitle, 1);
                Paragraph sTitle  = new Paragraph("This is section 1 in chapter 1", f1);
                Section   section = chapter.AddSection(sTitle, 1);
                doc.Add(chapter);

                //构建了一个简单的表:
                Table aTable = new Table(4, 4);
                aTable.AutoFillEmptyCells = true;
                aTable.AddCell("2.2", new System.Drawing.Point(2, 2));
                aTable.AddCell("3.3", new System.Drawing.Point(3, 3));
                aTable.AddCell("2.1", new System.Drawing.Point(2, 1));
                aTable.AddCell("1.3", new System.Drawing.Point(1, 3));
                doc.Add(aTable);
                //构建了一个不简单的表:
                Table table = new Table(3);
                table.BorderWidth = 1;
                table.BorderColor = new iTextSharp.text.Color(0, 0, 255);
                table.Cellpadding = 5;
                table.Cellspacing = 5;
                Cell cell = new Cell("header");
                cell.Header  = true;
                cell.Colspan = 3;
                table.AddCell(cell);
                cell             = new Cell("example cell with colspan 1 and rowspan 2");
                cell.Rowspan     = 2;
                cell.BorderColor = new iTextSharp.text.Color(255, 0, 0);
                table.AddCell(cell);
                table.AddCell("1.1");
                table.AddCell("2.1");
                table.AddCell("1.2");
                table.AddCell("2.2");
                table.AddCell("cell test1");
                cell                 = new Cell("big cell");
                cell.Rowspan         = 2;
                cell.Colspan         = 2;
                cell.BackgroundColor = new iTextSharp.text.Color(0xC0, 0xC0, 0xC0);
                table.AddCell(cell);
                table.AddCell("cell test2");
                // 改变了单元格“big cell”的对齐方式:
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                doc.Add(table);

                #endregion
                //关闭document
                doc.Close();
                //打开PDF,看效果
                //Process.Start(sourcePath);
            }
            catch (DocumentException de)
            {
                Console.WriteLine(de.Message);
                Console.ReadKey();
            }
            catch (IOException io)
            {
                Console.WriteLine(io.Message);
                Console.ReadKey();
            }
        }
Exemplo n.º 37
0
        private void ExportPdf(DocGia docGia)
        {
            string ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "times.TTF");

            //Create a base font object making sure to specify IDENTITY-H
            BaseFont bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            //Creating iTextSharp Table from the DataTable data


            //Font f = new System.Drawing.Font(bf, 12, Font.NORMAL);
            //Font f = new Font(bf, 12, Font.NORMAL);
            iTextSharp.text.Font text = new iTextSharp.text.Font(bf, 14, iTextSharp.text.Font.NORMAL);
            //Adding Header row


            //Exporting to PDF
            string folderPath = "C:\\PDFs\\";

            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            using (FileStream stream = new FileStream(folderPath + "TheDocGia" + docGia.MaDocGia + ".pdf", FileMode.Create))
            {
                Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
                PdfWriter.GetInstance(pdfDoc, stream);
                pdfDoc.Open();
                // Tieude


                // khoang trang
                var spacer = new Paragraph("")
                {
                    SpacingBefore = 10f,
                    SpacingAfter  = 10f,
                };

                // Bang
                var headTable = new PdfPTable(new[] { .3f, .7f })
                {
                    HorizontalAlignment = Left,
                    WidthPercentage     = 75,
                    DefaultCell         = { MinimumHeight = 25f }
                };
                headTable.DefaultCell.BorderWidth   = 1;
                headTable.DefaultCell.MinimumHeight = 30f;

                headTable.WidthPercentage     = 30;                   // set Width for table
                headTable.HorizontalAlignment = Element.ALIGN_CENTER; // align: center
                headTable.AddCell(new PdfPCell(new Phrase("Mã độc giả", text)));
                headTable.AddCell(new PdfPCell(new Phrase(docGia.MaDocGia, text)));
                headTable.AddCell(new PdfPCell(new Phrase("Họ và tên", text)));
                headTable.AddCell(new PdfPCell(new Phrase(docGia.HoTen, text)));
                headTable.AddCell(new PdfPCell(new Phrase("Giới tính", text)));
                headTable.AddCell(new PdfPCell(new Phrase(docGia.GioiTinh, text)));
                headTable.AddCell(new PdfPCell(new Phrase("Ngày sinh", text)));
                headTable.AddCell(new PdfPCell(new Phrase(docGia.NgaySinh.ToString("dd/MM/yyyy"), text)));
                headTable.AddCell(new PdfPCell(new Phrase("Ngày cấp thẻ", text)));
                headTable.AddCell(new PdfPCell(new Phrase(docGia.NgayCap.ToString("dd/MM/yyyy"), text)));
                headTable.AddCell(new PdfPCell(new Phrase("Ngày gia hạn thẻ", text)));
                headTable.AddCell(new PdfPCell(new Phrase(docGia.NgayGHan.ToString("dd/MM/yyyy"), text)));

                iTextSharp.text.Font text2 = new iTextSharp.text.Font(bf, 24, iTextSharp.text.Font.BOLD);
                Paragraph            p1    = new Paragraph("THÔNG TIN THẺ", text2);
                p1.Alignment = Element.ALIGN_CENTER;

                pdfDoc.Add(p1);
                pdfDoc.Add(spacer);
                pdfDoc.Add(headTable);
                pdfDoc.Add(spacer);
                //pdfDoc.Add(pdfTable);


                pdfDoc.Close();
                stream.Close();
            }
        }
Exemplo n.º 38
0
 // constructors
 /**
 * Copy constructor of a Font
 * @param other the font that has to be copied
 */
 public Font(Font other)
 {
     this.color = other.color;
     this.family = other.family;
     this.size = other.size;
     this.style = other.style;
     this.baseFont = other.baseFont;
 }
Exemplo n.º 39
0
        void ExportDataTableToPdf(DataTable dtblTable, String strPdfPath, string strHeader)
        {
            System.IO.FileStream fs = new FileStream(strPdfPath, FileMode.Create, FileAccess.Write, FileShare.None);

            Document document = new Document();

            document.SetPageSize(iTextSharp.text.PageSize.A4);
            PdfWriter writer = PdfWriter.GetInstance(document, fs);

            writer.RunDirection = iTextSharp.text.pdf.PdfWriter.RUN_DIRECTION_RTL;

            document.Open();

            //Report Header
            var arialFontPath2 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "trado.TTF");

            BaseFont  bfntHead   = BaseFont.CreateFont(arialFontPath2, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font      fntHead    = new Font(bfntHead, 16, 1);
            Paragraph prgHeading = new Paragraph();
            PdfPTable Y          = new PdfPTable(1);

            Y.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            PdfPCell c1 = new PdfPCell();

            prgHeading.Alignment = Element.ALIGN_CENTER;
            prgHeading.Add(new Chunk(strHeader.ToUpper(), fntHead));
            c1.AddElement(prgHeading);
            c1.Border = Rectangle.NO_BORDER;

            Y.AddCell(c1);
            document.Add(Y);

            //Author

            Paragraph prgAuthor = new Paragraph();
            PdfPTable X         = new PdfPTable(1);

            X.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            PdfPCell c = new PdfPCell();

            var      arialFontPath1 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "trado.TTF");
            BaseFont authorf        = BaseFont.CreateFont(arialFontPath1, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font     f1             = new Font(authorf, 18);

            prgAuthor.Alignment = Element.ALIGN_RIGHT;

            prgAuthor.Font = f1;
            prgAuthor.Add(new Chunk(" بيان مشتروات", f1));
            prgAuthor.Add(new Chunk("\nDate : " + datetext.Text, f1));
            c.AddElement(prgAuthor);
            c.Border = Rectangle.NO_BORDER;

            X.AddCell(c);
            document.Add(X);

            //Add a line seperation
            Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1)));

            document.Add(p);

            //Add line break
            document.Add(new Chunk("\n", fntHead));

            //Write the table
            PdfPTable table = new PdfPTable(dtblTable.Columns.Count);
            //Table header
            var      arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "tradbdo.TTF");
            BaseFont bf            = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font     f             = new Font(bf, 12);

            BaseFont btnColumnHeader = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font     fntColumnHeader = new Font(btnColumnHeader, 10, 1, BaseColor.WHITE);

            for (int i = 0; i < dtblTable.Columns.Count; i++)
            {
                Phrase phrase = new Phrase(dtblTable.Columns[i].ColumnName.ToUpper(), f);
                table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                PdfPCell cell = new PdfPCell(phrase);
                cell.HorizontalAlignment = 1;
                cell.BackgroundColor     = BaseColor.GRAY;
                table.AddCell(cell);
            }
            //table Data
            for (int i = 0; i < dtblTable.Rows.Count; i++)
            {
                for (int j = 0; j < dtblTable.Columns.Count; j++)
                {
                    Phrase   phrase = new Phrase(dtblTable.Rows[i][j].ToString(), f);
                    PdfPCell cell   = new PdfPCell(phrase);
                    cell.HorizontalAlignment = 1;
                    table.AddCell(cell);
                }
            }

            document.Add(table);
            document.Close();
            writer.Close();
            fs.Close();
        }
Exemplo n.º 40
0
 /// <summary>
 /// Constructs a Font.
 /// </summary>
 /// <param name="bf">the external font</param>
 /// <param name="size">the size of this font</param>
 /// <param name="style">the style of this font</param>
 public Font(BaseFont bf, float size, int style)
     : this(bf, size, style, null)
 {
 }
Exemplo n.º 41
0
        protected void ReportDeliveryExportPDF(List <SaleHeaderDTO> lst)
        {
            MemoryStream ms  = new MemoryStream();
            Document     doc = new Document(PageSize.A4, 3, 3, 3, 3);
            //var output = new FileStream(Server.MapPath(filename), FileMode.Create);
            var writer = PdfWriter.GetInstance(doc, ms);

            doc.Open();
            try
            {
                #region Variable
                BaseColor bc = new BaseColor(255, 255, 255);
                //string fontFamily = "C:/Windows/Fonts/Tahoma.ttf";
                string    fontFamily = Server.MapPath("~") + "Fonts\\CSChatThai.ttf";
                BaseFont  bf         = BaseFont.CreateFont(fontFamily, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                Font      fontBold   = new Font(bf, 15, iTextSharp.text.Font.BOLD);
                Font      fontNormal = new Font(bf, 15);
                PdfPTable table      = new PdfPTable(1);
                PdfPCell  cell1      = new PdfPCell();
                table.WidthPercentage = 99;
                PdfContentByte   pcbItemCode, pcbCOD;
                string           CODTextForm = "เก็บเงินปลายทาง \r\nจำนวนเงิน ";
                string           CODText = "", SenderName = "", SenderTel = "", ItemCode = "";
                int              i = 0, senderID = 0;
                int[]            lowerY = { 620, 350, 90 };
                int[]            upperY = { 650, 380, 120 };
                Rectangle        rect;
                List <MasSender> lstSen = new List <MasSender>();
                MasSender        Sen    = new MasSender();
                #endregion

                if (lst != null && lst.Count > 0)
                {
                    if (Session["ReportSaleDeliDDL"] != null)
                    {
                        lstSen   = (List <MasSender>)Session["ReportSaleDeliDDL"];
                        senderID = ToInt32(ddlSender.SelectedItem.Value);
                        Sen      = lstSen.FirstOrDefault(w => w.SenderID.Equals(senderID));
                        if (Sen != null)
                        {
                            SenderName = Sen.SenderName;
                            SenderTel  = Sen.Tel;
                        }
                    }

                    foreach (SaleHeaderDTO item in lst)
                    {
                        if (i > 0 && i % 3 == 0)
                        {
                            doc.Add(table);
                            doc.NewPage();
                            table = new PdfPTable(1);
                            table.WidthPercentage = 99;
                            i = 0;
                        }

                        AddTextToRow("  ", fontNormal, table);
                        AddTextToRow("  จัดส่ง :  " + item.Name, fontNormal, table);
                        AddTextToRow("  โทร :  " + item.Tel, fontNormal, table);
                        AddTextToRow("  ที่อยู่1 :  " + item.CustomerAddress, fontNormal, table);
                        AddTextToRow("  ที่อยู่2 :  " + item.CustomerDistrict + " " + item.CustomerCountry, fontNormal, table);
                        AddTextToRow("  ที่อยู่3 :  " + item.CustomerProvince + " " + item.CustomerPostalCode, fontNormal, table);
                        //AddTextToRow("ที่อยู่1 :  " + item.Add1, fontNormal, table);
                        //AddTextToRow("ที่อยู่2 :  " + item.Add2, fontNormal, table);
                        //AddTextToRow("ที่อยู่3 :  " + item.Add3, fontNormal, table);
                        AddTextToRow("  ผู้ส่ง :  " + SenderName, fontNormal, table);
                        AddTextToRow("  โทร.  " + SenderTel, fontNormal, table);

                        AddTextToRow("  ", fontNormal, table);
                        AddTextToRow("   ----------------------------------------------------------------------------------------------------", fontNormal, table);

                        //pcbItemCode = writer.DirectContent;
                        //PlaceText(pcbItemCode, item.ItemCode, fontBold, 300, lowerY[i], 550, upperY[i], 20, Element.ALIGN_CENTER);

                        pcbItemCode = writer.DirectContent;
                        if (item.dAmount > 1)
                        {
                            //ItemCode = item.ItemCode + "(" + item.dAmount + ")";
                            ItemCode = item.ItemCode + " * " + item.dAmount;
                        }
                        else
                        {
                            ItemCode = item.ItemCode;
                        }
                        PlaceText(pcbItemCode, ItemCode, fontBold, 300, lowerY[i], 550, upperY[i], 20, Element.ALIGN_CENTER);
                        rect = new Rectangle(300, lowerY[i], 550, upperY[i]);
                        pcbItemCode.SetColorStroke(BaseColor.BLACK);
                        pcbItemCode.Rectangle(rect.Left, rect.Bottom, rect.Width, rect.Height);
                        pcbItemCode.Stroke();

                        if (!string.IsNullOrEmpty(item.COD) && item.COD == "1")
                        {
                            pcbCOD  = writer.DirectContent;
                            CODText = CODTextForm + item.SaleAmount.ToString("###,##0") + " บาท";
                            PlaceText(pcbCOD, CODText, fontBold, 300, lowerY[i] + 130, 550, upperY[i] + 150, 20, Element.ALIGN_CENTER);
                            rect = new Rectangle(300, lowerY[i] + 130, 550, upperY[i] + 150);
                            pcbCOD.SetColorStroke(BaseColor.BLACK);
                            pcbCOD.Rectangle(rect.Left, rect.Bottom, rect.Width, rect.Height);
                            pcbCOD.Stroke();
                        }

                        i++;
                    }
                    doc.Add(table);
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                doc.Close();
                writer.Close();
            }

            string filename = "ReportSaleDelivery_" + DateTime.Now.ToString("yyyyMMdd");
            Response.Clear();
            Response.Buffer          = false;
            Response.ContentEncoding = Encoding.UTF8;
            Response.HeaderEncoding  = Encoding.UTF8;
            Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".pdf");
            Response.ContentType = "application/pdf";
            Response.BinaryWrite(ms.ToArray());
            Response.Flush();
            Response.SuppressContent = true;
        }
Exemplo n.º 42
0
 /// <summary>
 /// Constructs a Font.
 /// </summary>
 /// <param name="bf">the external font</param>
 public Font(BaseFont bf)
     : this(bf, UNDEFINED, UNDEFINED, null)
 {
 }
Exemplo n.º 43
0
        }//Скрывает интерфейс разных методов прогноза

        private void PdfToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Объект документа пдф
            iTextSharp.text.Document doc = new iTextSharp.text.Document();
            doc.SetPageSize(PageSize.A4.Rotate());
            try
            {
                //Создаем объект записи пдф-документа в файл
                PdfWriter.GetInstance(doc, new FileStream("pdfTables.pdf", FileMode.Create));
            }
            catch (IOException)
            {
                MessageBox.Show("Пожалуйста, для сохранения файла, закройте файл pdf и нажмите ОК");
                try
                {
                    PdfWriter.GetInstance(doc, new FileStream("pdfTables.pdf", FileMode.Create));
                }
                catch (Exception)
                {
                    MessageBox.Show("Не удалост вывести в pdf файл!");
                    return;
                }
            }

            //Открываем документ
            doc.Open();

            //Определение шрифта необходимо для сохранения кириллического текста
            //Иначе мы не увидим кириллический текст
            //Если мы работаем только с англоязычными текстами, то шрифт можно не указывать
            string   FONT_LOCATION = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.TTF"); //определяем В СИСТЕМЕ(чтобы не копировать файл) расположение шрифта arial.ttf
            BaseFont baseFont      = BaseFont.CreateFont(FONT_LOCATION, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);        //создаем шрифт

            iTextSharp.text.Font fontParagraph = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.NORMAL);       //регистрируем + можно задать параметры для него(17 - размер, последний параметр - стиль)
            //Создаем объект таблицы и передаем в нее число столбцов таблицы из нашего датасета
            PdfPTable table = new PdfPTable(dataGridView1.ColumnCount);                                                     //MyDataSet.Tables[i].Columns.Count);
            //Добавим в таблицу общий заголовок

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

            //cell.Colspan = dataGridView1.ColumnCount;
            //cell.HorizontalAlignment = 1;
            ////Убираем границу первой ячейки, чтобы был как заголовок
            //cell.Border = 0;
            //table.AddCell(cell);

            //Сначала добавляем заголовки таблицы
            for (int j = 0; j < dataGridView1.ColumnCount; j++)
            {
                cell = new PdfPCell(new Phrase(new Phrase(dataGridView1.Columns[j].HeaderText, fontParagraph)));
                //Фоновый цвет (необязательно, просто сделаем по красивее)
                cell.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY;
                table.AddCell(cell);
            }
            //Добавляем все остальные ячейки
            for (int j = 0; j < dataGridView1.RowCount - 1; j++)
            {
                for (int k = 0; k < dataGridView1.ColumnCount; k++)
                {
                    if (dataGridView1.Rows[j].Cells[k].Value != null)
                    {
                        table.AddCell(new Phrase(Math.Round(Convert.ToDouble(dataGridView1.Rows[j].Cells[k].Value), 2).ToString(), fontParagraph));
                    }
                    else
                    {
                        table.AddCell(new Phrase(" ", fontParagraph));
                    }
                }
            }
            //if (ComboBoxMethod.SelectedIndex != 1 && textBoxErrorIndic.Text != "")
            //fileCSV += "Среднеквадратическая ошибка расчёта ;" + textBoxErrorIndic.Text + ";";
            //table.AddCell(new Phrase(Math.Round(Convert.ToDouble(textBoxErrorIndic.Text), 2).ToString(), fontParagraph));
            // table.AddCell(new Phrase("123", fontParagraph));
            /**/

            chart1.SaveImage(Application.StartupPath + @"\1.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(Application.StartupPath + @"/1.bmp");
            jpg.Alignment = iTextSharp.text.Image.ALIGN_CENTER;

            //Добавляем таблицу в документ
            doc.Add(table);
            if (ComboBoxMethod.SelectedIndex != 1 && textBoxErrorIndic.Text != "")
            {
                doc.Add(new Phrase("\n                         Среднеквадратическая ошибка прогноза: " + Math.Round(Convert.ToDouble(textBoxErrorIndic.Text), 3).ToString(), fontParagraph));
            }
            if (ComboBoxMethod.SelectedIndex == 2 && textBoxErrorForecast.Text != "")
            {
                doc.Add(new Phrase("\n                         Ошибка прогноза: " + Math.Round(Convert.ToDouble(textBoxErrorForecast.Text), 3).ToString(), fontParagraph));
            }
            doc.NewPage();
            jpg.ScalePercent(80);
            doc.Add(jpg);
            //Закрываем документ
            doc.Close();

            Process.Start("pdfTables.pdf");
        }
Exemplo n.º 44
0
 /**
 * Adds a <CODE>BaseFont</CODE> to the document but not to the page resources.
 * It is used for templates.
 * @param bf the <CODE>BaseFont</CODE> to add
 * @return an <CODE>Object[]</CODE> where position 0 is a <CODE>PdfName</CODE>
 * and position 1 is an <CODE>PdfIndirectReference</CODE>
 */
 internal FontDetails AddSimple(BaseFont bf)
 {
     if (bf.FontType == BaseFont.FONT_TYPE_DOCUMENT) {
         return new FontDetails(new PdfName("F" + (fontNumber++)), ((DocumentFont)bf).IndirectReference, bf);
     }
     FontDetails ret = (FontDetails)documentFonts[bf];
     if (ret == null) {
         PdfXConformanceImp.CheckPDFXConformance(this, PdfXConformanceImp.PDFXKEY_FONT, bf);
         ret = new FontDetails(new PdfName("F" + (fontNumber++)), body.PdfIndirectReference, bf);
         documentFonts[bf] = ret;
     }
     return ret;
 }
Exemplo n.º 45
0
        public MemoryStream GeneratePdfTemplate(RegradingResultDocsViewModel viewModel)
        {
            BaseFont bf          = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            BaseFont bf_bold     = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            var      normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            var      bold_font   = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);

            Document     document = new Document(PageSize.A5);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            writer.CloseStream = false;
            document.Open();
            PdfContentByte cb = writer.DirectContent;

            cb.BeginText();

            //cb.SetFontAndSize(bf, 8);
            //cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "PT DANLIRIS", 50, 378, 0);
            //cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "SUKOHARJO", 50, 368, 0);

            cb.SetFontAndSize(bf_bold, 8);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "FM.FP-01-PR.01-09.1-02", 290, 570, 0);

            cb.SetFontAndSize(bf_bold, 14);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "BON Results RE-GRADING KAIN Here", 210, 540, 0);

            cb.SetFontAndSize(bf, 8);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "No Bon", 20, 500, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ":", 90, 500, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, viewModel.Code, 100, 500, 0);

            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Unit", 20, 490, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ":", 90, 490, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, viewModel.Bon.UnitName, 100, 490, 0);


            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Item name", 20, 480, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ":", 90, 480, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, viewModel.Product.Name, 100, 480, 0);

            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Long Datang", 20, 470, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ":", 90, 470, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, string.Format("{0:n}", viewModel.TotalLength), 100, 470, 0);

            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Grade Datang", 20, 460, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ":", 90, 460, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, viewModel.OriginalGrade, 100, 460, 0);

            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Date", 240, 500, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ":", 290, 500, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, viewModel.CreatedUtc.ToString("MM-dd-yyyy"), 300, 500, 0);

            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Nama Mesin", 240, 490, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ":", 290, 490, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, viewModel.Machine.Name, 300, 490, 0);

            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Operator", 240, 480, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ":", 290, 480, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, viewModel.Operator, 300, 480, 0);

            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Shift", 240, 470, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ":", 290, 470, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, viewModel.Shift, 300, 470, 0);


            cb.EndText();

            #region CreateTable
            PdfPTable table = new PdfPTable(3);
            PdfPCell  cell;
            table.TotalWidth = 380f;

            float[] widths = new float[] { 4f, 4f, 7f };
            table.SetWidths(widths);

            cell = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5
            };
            var rightCell = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5
            };
            var leftCell = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5
            };
            //Create cells headers.


            //cell.Phrase = new Phrase("Grade Asli", bold_font);
            //table.AddCell(cell);

            cell.Phrase = new Phrase("Results Regrade", bold_font);
            table.AddCell(cell);

            //cell.Phrase = new Phrase("Long Before", bold_font);
            //table.AddCell(cell);

            cell.Phrase = new Phrase("Long Re-grade", bold_font);
            table.AddCell(cell);

            cell.Phrase = new Phrase("Keterangan", bold_font);
            table.AddCell(cell);

            //int index = 1;

            foreach (var detail in viewModel.Details)
            {
                cell = new PdfPCell()
                {
                    Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5
                };
                //cell.Phrase = new Phrase(detail.GradeBefore, normal_font);
                //table.AddCell(cell);


                cell.Phrase = new Phrase(detail.Grade, normal_font);
                table.AddCell(cell);


                //cell.Phrase = new Phrase(string.Format("{0:n}", detail.LengthBeforeReGrade), normal_font);
                //table.AddCell(cell);

                cell.Phrase = new Phrase(string.Format("{0:n}", detail.Length), normal_font);
                table.AddCell(cell);

                cell = new PdfPCell()
                {
                    Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5
                };
                cell.Phrase = new Phrase(detail.Remark, normal_font);
                table.AddCell(cell);

                //index++;
            }

            table.WriteSelectedRows(0, -1, 20, 450, cb);
            #endregion


            cb.BeginText();
            cb.SetTextMatrix(15, 23);

            cb.SetFontAndSize(bf, 8);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Penerima,", 100, 110, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "(.................................)", 100, 50, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Operator", 100, 35, 0);

            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Mengetahui,", 320, 110, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "(.................................)", 320, 50, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Kasubsie", 320, 35, 0);

            cb.EndText();

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;
            return(stream);
        }
Exemplo n.º 46
0
 /**
 * Adds a substitution font to the list. The fonts in this list will be used if the original
 * font doesn't contain the needed glyphs.
 * @param font the font
 */
 public void AddSubstitutionFont(BaseFont font)
 {
     if (substitutionFonts == null)
         substitutionFonts = new ArrayList();
     substitutionFonts.Add(font);
 }
Exemplo n.º 47
0
 /** Always throws an error. This operation is not allowed.
  * @param bf dummy
  * @param size dummy */
 public override void SetFontAndSize(BaseFont bf, float size)
 {
     ThrowError();
 }
Exemplo n.º 48
0
 public PdfFormField AddComboBox(string name, string[] options, string defaultValue, bool editable, BaseFont font, float fontSize, float llx, float lly, float urx, float ury)
 {
     PdfFormField choice = PdfFormField.CreateCombo(writer, editable, options, 0);
     SetChoiceParams(choice, name, defaultValue, llx, lly, urx, ury);
     if (defaultValue == null) {
     defaultValue = options[0];
     }
     DrawSingleLineOfText(choice, defaultValue, font, fontSize, llx, lly, urx, ury);
     AddFormField(choice);
     return choice;
 }
Exemplo n.º 49
0
        private void pago()
        {
            try
            {
                BaseFont bfTimes = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, false);
                Font     font    = new Font(bfTimes, 12, 2, BaseColor.BLACK);
                Font     font2   = new Font(bfTimes, 9, 2, BaseColor.BLACK);

                Font arial  = FontFactory.GetFont("Arial", 12, BaseColor.BLACK);
                Font arial2 = FontFactory.GetFont("Arial", 9, BaseColor.BLACK);


                iTextSharp.text.Document doc = new iTextSharp.text.Document();
                string    rutatemporal       = Path.GetTempPath();
                PdfWriter title = PdfWriter.GetInstance(doc, new FileStream(rutatemporal + "/PagoGuiacopia.pdf", FileMode.Create));
                doc.Open();
                Bitmap imagensplash = new Bitmap(Autobuses.Properties.Resources.logotickets);

                iTextSharp.text.Image PatientSign = iTextSharp.text.Image.GetInstance(imagensplash, System.Drawing.Imaging.ImageFormat.Png);
                PatientSign.Alignment = Element.ALIGN_LEFT;

                doc.Add(new Paragraph("\n"));



                PdfPTable table = new PdfPTable(3);
                table.HorizontalAlignment = Element.ALIGN_CENTER;

                table.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                table.WidthPercentage    = 100;

                PdfPCell cell = new PdfPCell();

                cell                     = new PdfPCell(PatientSign);
                cell.BorderColor         = BaseColor.WHITE;
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                table.AddCell(cell);
                Paragraph p = new Paragraph();
                p.Add(new Chunk("Sucursal: ", font));
                p.Add(new Chunk("\n"));
                p.Add(new Chunk(LoginInfo.Sucursal, arial));

                p.Add(new Chunk("\n"));
                p.Add(new Chunk("\n"));
                p.Add(new Chunk("Linea: ", font));
                p.Add(new Chunk("\n"));
                p.Add(new Chunk(linea, arial));

                cell             = new PdfPCell(p);
                cell.BorderColor = BaseColor.WHITE;
                table.AddCell(cell);
                Paragraph d = new Paragraph();

                d.Add(new Chunk("Fecha: ", font));
                d.Add(new Chunk(DateTime.Now.ToString("dd/MM/yyyy"), arial));

                d.Add(new Chunk("\n"));
                d.Add(new Chunk("\n"));
                d.Add(new Chunk("Hora: ", font));
                d.Add(new Chunk(DateTime.Now.ToString("HH: mm tt"), arial));

                d.Add(new Chunk("\n"));
                d.Add(new Chunk("\n"));
                d.Add(new Chunk("Folio: ", font));
                d.Add(new Chunk(foliotext, arial));

                d.Alignment = Element.ALIGN_RIGHT;



                cell             = new PdfPCell(d);
                cell.BorderColor = BaseColor.WHITE;
                table.AddCell(cell);



                doc.Add(table);

                doc.Add(new Paragraph("\n"));


                PdfPTable table2 = new PdfPTable(3);
                table2.WidthPercentage     = 100;
                table2.HorizontalAlignment = Element.ALIGN_CENTER;


                PdfPCell cell2 = new PdfPCell();
                cell2.HorizontalAlignment = Element.ALIGN_CENTER;

                Paragraph a2 = new Paragraph();
                a2.Add(new Chunk("Usuario: ", font));
                a2.Add(new Chunk("\n"));
                a2.Add(new Chunk(LoginInfo.NombreID + " " + LoginInfo.ApellidoID, arial));
                a2.Add(new Chunk("\n"));
                a2.Add(new Chunk("\n"));
                a2.Add(new Chunk("Socio: ", font));
                a2.Add(new Chunk("\n"));
                a2.Add(new Chunk(_socio, arial));
                a2.Add(new Chunk("\n"));
                a2.Add(new Chunk("\n"));
                a2.Add(new Chunk("Quién Cobro: ", font));
                a2.Add(new Chunk("\n"));
                a2.Add(new Chunk(nombredetermindo, arial));
                a2.Add(new Chunk("\n"));

                cell2             = new PdfPCell(a2);
                cell2.BorderColor = BaseColor.WHITE;
                table2.AddCell(cell2);
                Paragraph p2 = new Paragraph();
                p2.Add(new Chunk("Cantidad de guias: ", font));
                p2.Add(new Chunk("\n"));
                p2.Add(new Chunk(cantidadfolios.ToString(), arial));
                p2.Add(new Chunk("\n"));
                p2.Add(new Chunk("\n"));
                p2.Add(new Chunk("Rango  de pago:", font));
                p2.Add(new Chunk("\n"));
                p2.Add(new Chunk(fechainicio + "-" + fechatermino, arial));



                cell2             = new PdfPCell(p2);
                cell2.BorderColor = BaseColor.WHITE;
                table2.AddCell(cell2);
                Paragraph             d2           = new Paragraph();
                BarcodeLib.Barcode    Codigobarras = new BarcodeLib.Barcode();
                iTextSharp.text.Image qrr          = iTextSharp.text.Image.GetInstance(Codigobarras.Encode(BarcodeLib.TYPE.CODE128, foliotext, Color.Black, Color.White, 170, 30), System.Drawing.Imaging.ImageFormat.Png);
                qrr.Alignment = Element.ALIGN_RIGHT;

                cell2             = new PdfPCell(qrr);
                cell2.BorderColor = BaseColor.WHITE;
                table2.AddCell(cell2);



                doc.Add(table2);

                doc.Add(new Paragraph("\n"));

                PdfPTable table3 = new PdfPTable(8);
                table3.WidthPercentage     = 100;
                table3.HorizontalAlignment = Element.ALIGN_CENTER;

                PdfPCell cell3 = new PdfPCell();
                cell3.HorizontalAlignment = Element.ALIGN_CENTER;


                Paragraph folio   = new Paragraph();
                Paragraph importe = new Paragraph();
                Paragraph gastos  = new Paragraph();
                Paragraph aport   = new Paragraph();
                Paragraph com     = new Paragraph();

                Paragraph tarjetas = new Paragraph();
                Paragraph iva      = new Paragraph();
                Paragraph total    = new Paragraph();
                folio.Add(new Chunk("Folio", font2));
                folio.Add(new Chunk("\n", font2));
                importe.Add(new Chunk("Importe", font2));
                importe.Add(new Chunk("\n", font2));
                gastos.Add(new Chunk("Gastos", font2));
                gastos.Add(new Chunk("\n", font2));
                aport.Add(new Chunk("Aportación", font2));
                aport.Add(new Chunk("\n", font2));
                com.Add(new Chunk("Com. Banco", font2));
                com.Add(new Chunk("\n", font2));
                tarjetas.Add(new Chunk("Tarjetas", font2));
                tarjetas.Add(new Chunk("\n", font2));
                iva.Add(new Chunk("Iva", font2));
                iva.Add(new Chunk("\n", font2));
                total.Add(new Chunk("Total", font2));
                total.Add(new Chunk("\n", font2));

                cell3 = new PdfPCell(folio);
                table3.AddCell(cell3);
                cell3 = new PdfPCell(importe);
                table3.AddCell(cell3);
                cell3 = new PdfPCell(gastos);
                table3.AddCell(cell3);
                cell3 = new PdfPCell(aport);
                table3.AddCell(cell3);
                cell3 = new PdfPCell(com);
                table3.AddCell(cell3);
                cell3 = new PdfPCell(tarjetas);
                table3.AddCell(cell3);
                cell3 = new PdfPCell(iva);
                table3.AddCell(cell3);
                cell3 = new PdfPCell(total);
                table3.AddCell(cell3);
                doc.Add(table3);

                PdfPTable table33 = new PdfPTable(8);
                table33.WidthPercentage = 100;
                PdfPCell cell33 = new PdfPCell();

                Paragraph folio3    = new Paragraph();
                Paragraph importe3  = new Paragraph();
                Paragraph gastos3   = new Paragraph();
                Paragraph aport3    = new Paragraph();
                Paragraph com3      = new Paragraph();
                Paragraph tarjetas3 = new Paragraph();
                Paragraph iva3      = new Paragraph();
                Paragraph total3    = new Paragraph();
                for (int i = 0; i < asiento.Count(); i++)
                {
                    folio3.Add(new Chunk(asiento[i], arial2));
                    folio3.Add(new Chunk("\n", arial2));
                    importe3.Add(new Chunk(pasajero[i], arial2));
                    importe3.Add(new Chunk("\n", arial2));
                    gastos3.Add(new Chunk(destinopasajero[i], arial2));
                    gastos3.Add(new Chunk("\n", arial2));
                    aport3.Add(new Chunk(aportaciong[i], arial2));
                    aport3.Add(new Chunk("\n", arial2));
                    com3.Add(new Chunk(compbang[i], arial2));
                    com3.Add(new Chunk("\n", arial2));
                    tarjetas3.Add(new Chunk(foliopasajero[i], arial2));
                    tarjetas3.Add(new Chunk("\n", arial2));
                    iva3.Add(new Chunk(tarifapasajero[i], arial2));
                    iva3.Add(new Chunk("\n", arial2));
                    total3.Add(new Chunk(preciopasajero[i], arial2));
                    total3.Add(new Chunk("\n", arial2));
                }
                cell33             = new PdfPCell(folio3);
                cell33.BorderColor = BaseColor.WHITE;
                table33.AddCell(cell33);

                cell33             = new PdfPCell(importe3);
                cell33.BorderColor = BaseColor.WHITE;
                table33.AddCell(cell33);

                cell33             = new PdfPCell(gastos3);
                cell33.BorderColor = BaseColor.WHITE;
                table33.AddCell(cell33);

                cell33             = new PdfPCell(aport3);
                cell33.BorderColor = BaseColor.WHITE;
                table33.AddCell(cell33);

                cell33             = new PdfPCell(com3);
                cell33.BorderColor = BaseColor.WHITE;

                table33.AddCell(cell33);
                cell33             = new PdfPCell(tarjetas3);
                cell33.BorderColor = BaseColor.WHITE;
                table33.AddCell(cell33);

                cell33             = new PdfPCell(iva3);
                cell33.BorderColor = BaseColor.WHITE;
                table33.AddCell(cell33);

                cell33             = new PdfPCell(total3);
                cell33.BorderColor = BaseColor.WHITE;
                table33.AddCell(cell33);
                cell33 = new PdfPCell();



                doc.Add(table33);
                doc.Add(new Paragraph("\n"));
                doc.Add(new Paragraph("\n"));
                PdfPTable table4 = new PdfPTable(6);
                table4.WidthPercentage = 100;

                PdfPCell cell4 = new PdfPCell();
                PdfPCell cell6 = new PdfPCell();


                cell4.BorderColor = BaseColor.WHITE;
                cell6.BorderColor = BaseColor.WHITE;

                cell4             = new PdfPCell(new Paragraph("\n"));
                cell4.BorderColor = BaseColor.WHITE;
                table4.AddCell(cell4);
                cell4             = new PdfPCell(new Paragraph("\n"));
                cell4.BorderColor = BaseColor.WHITE;
                table4.AddCell(cell4);
                cell4             = new PdfPCell(new Paragraph("\n"));
                cell4.BorderColor = BaseColor.WHITE;
                table4.AddCell(cell4);
                cell4             = new PdfPCell(new Paragraph("\n"));
                cell4.BorderColor = BaseColor.WHITE;
                table4.AddCell(cell4);

                Paragraph d4 = new Paragraph();
                Paragraph d5 = new Paragraph();
                d4.Add(new Chunk("Importe: ", arial));
                d5.Add(new Chunk(importetext, arial));
                d4.Add(new Chunk("\n"));
                d5.Add(new Chunk("\n"));
                d4.Add(new Chunk("Gastos: ", arial));
                d5.Add(new Chunk(gastostext, arial));
                d4.Add(new Chunk("\n"));
                d5.Add(new Chunk("\n"));
                d4.Add(new Chunk("Aportaciónes:", arial));
                d5.Add(new Chunk(aportaciontext, arial));
                d4.Add(new Chunk("\n"));
                d5.Add(new Chunk("\n"));
                d4.Add(new Chunk("Comp. Banco:", arial));
                d5.Add(new Chunk(compbantext, arial));
                d4.Add(new Chunk("\n"));
                d5.Add(new Chunk("\n"));
                d4.Add(new Chunk("Tarjetas:", arial));
                d5.Add(new Chunk(tarjetastext, arial));
                d4.Add(new Chunk("\n"));
                d5.Add(new Chunk("\n"));
                d4.Add(new Chunk("Iva:", arial));
                d5.Add(new Chunk(ivatext, arial));
                d4.Add(new Chunk("\n"));
                d5.Add(new Chunk("\n"));
                d4.Add(new Chunk("Total:", arial));
                d5.Add(new Chunk(totaltext, arial));
                d4.Add(new Chunk("\n"));
                d5.Add(new Chunk("\n"));


                cell4             = new PdfPCell(d4);
                cell4.BorderColor = BaseColor.WHITE;
                table4.AddCell(cell4);

                cell6             = new PdfPCell(d5);
                cell6.BorderColor = BaseColor.WHITE;
                table4.AddCell(cell6);

                doc.Add(table4);
                doc.Add(new Paragraph("\n"));

                float bo = doc.Bottom;

                Paragraph parrafo = new Paragraph("El presente documento representa el pago de las guias mencionadas, el cual, debera ser firmado por la persona quién recibe el pago, aceptando a los términos y condiciones de ATAH.", arial);
                parrafo.SpacingBefore = 120;
                doc.Add(parrafo);

                doc.Add(new Paragraph("\n"));
                doc.Add(new Paragraph("\n"));
                doc.Add(new Paragraph("_____________________________________", arial));
                doc.Add(new Paragraph("         Nombre y firma", arial));
                doc.Add(new Paragraph("\n"));
                doc.Add(new Paragraph("\n"));
                doc.AddTitle("Pago de Guia");

                doc.Close();

                MemoryStream ms        = new MemoryStream();
                PdfWriter    writerPdf = PdfWriter.GetInstance(doc, ms);
                byte[]       bytes     = ms.ToArray();
                System.Diagnostics.Process.Start(rutatemporal + "/PagoGuiacopia.pdf");
            }
            catch (Exception err)
            {
                string error   = err.Message;
                string funcion = "Pago";
                Utilerias.LOG.write(_clase, funcion, error);

                MessageBox.Show("Ocurrio un Error, intente de nuevo.");
            }
        }
Exemplo n.º 50
0
 public PdfFormField AddHtmlPostButton(string name, string caption, string value, string url, BaseFont font, float fontSize, float llx, float lly, float urx, float ury)
 {
     PdfAction action = PdfAction.CreateSubmitForm(url, null, PdfAction.SUBMIT_HTML_FORMAT);
     PdfFormField button = new PdfFormField(writer, llx, lly, urx, ury, action);
     SetButtonParams(button, PdfFormField.FF_PUSHBUTTON, name, value);
     DrawButton(button, caption, font, fontSize, llx, lly, urx, ury);
     AddFormField(button);
     return button;
 }
Exemplo n.º 51
0
        private MemoryStream getPdfconQR(string IDPasaje, EPersona epersona, EPasaje epasaje, int costo)
        {
            string orign       = iParada.getParada(epasaje.IdParadaOrigen).Nombre;
            string destino     = iParada.getParada(epasaje.IdParadaDestino).Nombre;
            string linea       = iLinea.getLinea(iSalida.getSalidas(iViaje.getViaje(epasaje.IdViaje).IdSalida).IdLinea).Nombre;
            string matricula   = iVehiculo.getVehiculos(iSalida.getSalidas(iViaje.getViaje(epasaje.IdViaje).IdSalida).IdVehiculo).Matricula;
            string fechaViajeL = iViaje.getViaje(epasaje.IdViaje).Fecha.ToString();

            string fechaViaje = fechaViajeL;
            int    index      = fechaViaje.IndexOf(" ");

            if (index > 0)
            {
                fechaViaje = fechaViaje.Substring(0, index);
            }



            string hora = iSalida.getSalidas(iViaje.getViaje(epasaje.IdViaje).IdSalida).HoraInicio.ToString();

            Document doc = new Document(PageSize.A5, 18, 18, 16, 0);

            MemoryStream ms  = new MemoryStream();
            PdfWriter    pdf = PdfWriter.GetInstance(doc, ms);

            //PdfWriter.GetInstance(doc, new FileStream(outputFile, FileMode.Create));

            doc.Open();
            BarcodeQRCode barcodeWrcode = new BarcodeQRCode(IDPasaje, 1000, 1000, null);
            Image         codeQRImga    = barcodeWrcode.GetImage();

            codeQRImga.ScaleAbsolute(200, 200);


            ////string outputFile2 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), @"pdf", "uybus.png");
            //string outputFile2 = Path.Combine(Environment.CurrentDirectory, @"..\..\..\BuisnessLayer\pdf\uybus.png");

            //Image image = Image.GetInstance(outputFile2);
            //image.ScaleAbsoluteHeight(42.0f * 1.88f);
            //image.ScaleAbsoluteWidth(185.2f * 2.07f);
            //image.Alignment = Element.ALIGN_CENTER;
            //doc.Add(image);


            BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI, BaseFont.EMBEDDED);

            Font      fontText = new Font(bf, 20, 0, BaseColor.BLACK);
            Paragraph par1     = new Paragraph("Estimado pasajero, ha recibido su pasaje.", fontText);

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

            Font fontText2 = new Font(bf, 15, 0, BaseColor.BLACK);

            Paragraph par0 = new Paragraph("UruguayBus 2020 le desea buen viaje.", fontText2);

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

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

            doc.Add(p);

            DateTime ahora = DateTime.Now;

            ahora = ahora.Subtract(new TimeSpan(03, 0, 0)); // seteo tiempo a estedos unidos

            Paragraph paragraphs = new Paragraph(new Phrase("Enviado: " + ahora));

            paragraphs.Alignment = Element.ALIGN_RIGHT;
            doc.Add(paragraphs);

            doc.Add(new Paragraph("Pasajero: " + epersona.pNombre + " " + epersona.pApellido));
            doc.Add(new Paragraph("Documento: " + epersona.Documento));
            if (epasaje.Asientos != null)
            {
                if (epasaje.Asientos != -1)
                {
                    doc.Add(new Paragraph("Asiento: " + epasaje.Asientos));
                }
            }

            doc.Add(new Paragraph("Linea: " + linea));
            doc.Add(new Paragraph("Origen: " + orign));
            doc.Add(new Paragraph("Destino: " + destino));
            doc.Add(new Paragraph("Salida: " + fechaViaje + " " + hora));
            doc.Add(new Paragraph("Matricula: " + matricula));



            doc.Add(new Paragraph("Costo: " + costo + " UYU"));

            //doc.Add(new Chunk("\n"));

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

            doc.Add(p3);

            Font fontText4 = new Font(bf, 10, 0, BaseColor.BLACK);

            doc.Add(new Paragraph("Presente el siguiente código QR al chofer.", fontText4));


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

            pdf.CloseStream = false;
            doc.Close();
            ms.Position = 0;

            return(ms);
        }
Exemplo n.º 52
0
 public PdfFormField AddSelectList(string name, string[,] options, string defaultValue, BaseFont font, float fontSize, float llx, float lly, float urx, float ury)
 {
     PdfFormField choice = PdfFormField.CreateList(writer, options, 0);
     SetChoiceParams(choice, name, defaultValue, llx, lly, urx, ury);
     StringBuilder text = new StringBuilder();
     for (int i = 0; i < options.GetLength(0); i++) {
     text.Append(options[i, 1]).Append('\n');
     }
     DrawMultiLineOfText(choice, text.ToString(), font, fontSize, llx, lly, urx, ury);
     AddFormField(choice);
     return choice;
 }
Exemplo n.º 53
0
        public Chap1003()
        {
            Console.WriteLine("Chapter 10 example 3: Templates");

            // step 1: creation of a document-object
            Document document = new Document();

            try
            {
                // step 2:
                // we create a writer that listens to the document
                // and directs a PDF-stream to a file
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Chap1003.pdf", FileMode.Create));

                // step 3: we open the document
                document.Open();

                // step 4: we grab the ContentByte and do some stuff with it
                PdfContentByte cb = writer.DirectContent;

                // we create a PdfTemplate
                PdfTemplate template = cb.CreateTemplate(500, 200);

                // we add some graphics
                template.MoveTo(0, 200);
                template.LineTo(500, 0);
                template.Stroke();
                template.SetRGBColorStrokeF(255f, 0f, 0f);
                template.Circle(250f, 100f, 80f);
                template.Stroke();

                // we add some text
                template.BeginText();
                BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                template.SetFontAndSize(bf, 12);
                template.SetTextMatrix(100, 100);
                template.ShowText("Text at the position 100,100 (relative to the template!)");
                template.EndText();

                // we add the template on different positions
                cb.AddTemplate(template, 0, 0);
                cb.AddTemplate(template, 0, 1, -1, 0, 500, 200);
                cb.AddTemplate(template, .5f, 0, 0, .5f, 100, 400);

                // we go to a new page
                document.NewPage();
                cb.AddTemplate(template, 0, 400);
                cb.AddTemplate(template, 2, 0, 0, 2, -200, 400);
            }
            catch (DocumentException de)
            {
                Console.Error.WriteLine(de.Message);
            }
            catch (IOException ioe)
            {
                Console.Error.WriteLine(ioe.Message);
            }

            // step 5: we close the document
            document.Close();
        }
Exemplo n.º 54
0
 public void DrawButton(PdfFormField button, string caption, BaseFont font, float fontSize, float llx, float lly, float urx, float ury)
 {
     PdfAppearance pa = PdfAppearance.CreateAppearance(writer, urx - llx, ury - lly);
     pa.DrawButton(0f, 0f, urx - llx, ury - lly, caption, font, fontSize);
     button.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, pa);
 }
        public void Export(string savePath)
        {
            string path;
            string docName;
            int    indexOfFileName = savePath.LastIndexOf('\\');

            path    = savePath.Substring(0, indexOfFileName);
            docName = savePath.Substring(indexOfFileName + 1);

            Document  pdf    = new Document(iTextSharp.text.PageSize.A4, 20, 20, 35, 35);
            PdfWriter writer = PdfWriter
                               .GetInstance(pdf, new FileStream(System.IO.Path.Combine(path, docName),
                                                                FileMode.Create));

            pdf.Open();

            iTextSharp.text.Image imghead      = iTextSharp.text.Image.GetInstance("../../Images/styleHeader.png");
            iTextSharp.text.Image imgSeparator = iTextSharp.text.Image.GetInstance("../../Images/imageSeparator.png");
            iTextSharp.text.Image separator    = iTextSharp.text.Image.GetInstance("../../Images/separator.png");

            pdf.Add(imghead);
            pdf.Add(new iTextSharp.text.Paragraph(30, this.generalInfo.ProjectName, new Font(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false), 40)));
            pdf.Add(new iTextSharp.text.Paragraph(30, "created by " + this.generalInfo.TeamName,
                                                  new Font(BaseFont.CreateFont(), 20)));
            pdf.Add(new Chunk(string.Format(@"Course: {0}", this.generalInfo.Course)));
            pdf.Add(new Chunk("Project repository:"));
            pdf.Add(new Chunk(this.projectGitInfo.ToString()));

            pdf.Add(separator);

            pdf.Add(new iTextSharp.text.Paragraph(10, "Description: ", new Font(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false), 30)));
            pdf.Add(new iTextSharp.text.Paragraph(this.mainProjectDescription.Text, new Font(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false), 14)));
            pdf.Add(separator);
            pdf.Add(new iTextSharp.text.Paragraph(15, "Used resources: ", new Font(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false), 30)));
            foreach (var usedResource in this.usedResources)
            {
                pdf.Add(new Chunk((usedResource as ExternalResource).ToString()));
            }

            pdf.Add(separator);

            pdf.Add(new iTextSharp.text.Paragraph(30, "Project participants: ", new Font(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false), 30)));
            foreach (var participant in this.participants)
            {
                pdf.Add(new Chunk(participant.ToString()));
            }
            pdf.Add(separator);

            pdf.Add(new iTextSharp.text.Paragraph(18, "Screenshots: ", new Font(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false), 30)));
            foreach (var item in this.screenshots)
            {
                var paragraph             = new iTextSharp.text.Paragraph(Environment.NewLine + item.Description);
                iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(item.ImageFilePath);

                if (pic.Height > pic.Width)
                {
                    float percentage = 0.0f;
                    percentage = 300 / pic.Height;
                    pic.ScalePercent(percentage * 100);
                }
                else
                {
                    float percentage = 0.0f;
                    percentage = 300 / pic.Width;
                    pic.ScalePercent(percentage * 100);
                }

                pic.Border      = iTextSharp.text.Rectangle.BOX;
                pic.BorderColor = iTextSharp.text.BaseColor.BLACK;
                pic.BorderWidth = 2f;
                pdf.Add(paragraph);
                pdf.Add(pic);
            }

            pdf.Close();
            MessageBox.Show("Done!");
        }
Exemplo n.º 56
0
 public void DrawSingleLineOfText(PdfFormField field, string text, BaseFont font, float fontSize, float llx, float lly, float urx, float ury)
 {
     PdfAppearance tp = PdfAppearance.CreateAppearance(writer, urx - llx, ury - lly);
     PdfAppearance tp2 = (PdfAppearance)tp.Duplicate;
     tp2.SetFontAndSize(font, fontSize);
     tp2.ResetRGBColorFill();
     field.DefaultAppearanceString = tp2;
     tp.DrawTextField(0f, 0f, urx - llx, ury - lly);
     tp.BeginVariableText();
     tp.SaveState();
     tp.Rectangle(3f, 3f, urx - llx - 6f, ury - lly - 6f);
     tp.Clip();
     tp.NewPath();
     tp.BeginText();
     tp.SetFontAndSize(font, fontSize);
     tp.ResetRGBColorFill();
     tp.SetTextMatrix(4, (ury - lly) / 2 - (fontSize * 0.3f));
     tp.ShowText(text);
     tp.EndText();
     tp.RestoreState();
     tp.EndVariableText();
     field.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, tp);
 }
Exemplo n.º 57
0
 /**
 * Set the font and the size for the subsequent text writing.
 *
 * @param bf the font
 * @param size the font size in points
 */
 public override void SetFontAndSize(BaseFont bf, float size)
 {
     CheckWriter();
     state.size = size;
     if (bf.FontType == BaseFont.FONT_TYPE_DOCUMENT) {
         state.fontDetails = new FontDetails(null, ((DocumentFont)bf).IndirectReference, bf);
     }
     else
         state.fontDetails = writer.AddSimple(bf);
     PdfName psn = (PdfName)stdFieldFontNames[bf.PostscriptFontName];
     if (psn == null) {
         if (bf.Subset && bf.FontType == BaseFont.FONT_TYPE_TTUNI)
             psn = state.fontDetails.FontName;
         else {
             psn = new PdfName(bf.PostscriptFontName);
             state.fontDetails.Subset = false;
         }
     }
     PageResources prs = PageResources;
     prs.AddFont(psn, state.fontDetails.IndirectReference);
     content.Append(psn.GetBytes()).Append(' ').Append(size).Append(" Tf").Append_i(separator);
 }