Exemplo n.º 1
1
    public override void OnStartPage(PdfWriter writer, Document document)
    {
        base.OnStartPage(writer, document);

        if ((tipoDocumento == "contrato") || (tipoDocumento == "contrato_preimpreso")) //no se ponen cabeceras ni fotter
        {

        }
        else
        {
            if (tipoDocumento == "clausula")
            {
                //imagen de la cabecera
                float escala = 85; //%

                Image imagenHeader = Image.GetInstance(dirImagenHeader);
                imagenHeader.ScalePercent(escala);

                PdfPTable table = new PdfPTable(1);
                table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;

                //logo
                PdfPCell cell = new PdfPCell(imagenHeader);
                cell.Border = 0;
                cell.BorderWidth = 0;
                table.AddCell(cell);

                table.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - 20, writer.DirectContent);
            }
            else
            {
                if (tipoDocumento == "apertura_cuenta")
                {
                    //imagen de la cabecera
                    float escala = 70; //%

                    Image imagenHeader = Image.GetInstance(dirImagenHeader);
                    imagenHeader.ScalePercent(escala);

                    PdfPTable table = new PdfPTable(1);
                    table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;

                    //logo
                    PdfPCell cell = new PdfPCell(imagenHeader);
                    cell.Border = 0;
                    cell.BorderWidth = 0;
                    table.AddCell(cell);

                    table.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - 90, writer.DirectContent);
                }
                else
                {
                    if (tipoDocumento == "autos_recomendacion")
                    {
                        //imagen de la cabecera
                        float escala = 70; //%

                        Image imagenHeader = Image.GetInstance(dirImagenHeader);
                        imagenHeader.ScalePercent(escala);

                        PdfPTable table = new PdfPTable(1);
                        table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;

                        //logo
                        PdfPCell cell = new PdfPCell(imagenHeader);
                        cell.Border = 0;
                        cell.BorderWidth = 0;
                        table.AddCell(cell);

                        table.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - 20, writer.DirectContent);
                    }
                    else
                    {
                        if (tipoDocumento == "orden_compra")
                        {
                            //imagen de la cabecera
                            float escala = 70; //%

                            Image imagenHeader = Image.GetInstance(dirImagenHeader);
                            imagenHeader.ScalePercent(escala);

                            PdfPTable table = new PdfPTable(1);
                            table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;

                            //logo
                            PdfPCell cell = new PdfPCell(imagenHeader);
                            cell.Border = 0;
                            cell.BorderWidth = 0;
                            table.AddCell(cell);

                            table.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - 20, writer.DirectContent);
                        }
                        else
                        {
                            if (tipoDocumento == "entrevista")
                            {
                                //imagen de la cabecera
                                float escala = 85; //%

                                Image imagenHeader = Image.GetInstance(dirImagenHeader);
                                imagenHeader.ScalePercent(escala);

                                PdfPTable table = new PdfPTable(1);
                                table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;

                                //logo
                                PdfPCell cell = new PdfPCell(imagenHeader);
                                cell.Border = 0;
                                cell.BorderWidth = 0;
                                table.AddCell(cell);

                                table.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - 20, writer.DirectContent);
                            }
                            else
                            {
                                if (tipoDocumento == "referencia")
                                {
                                    //imagen de la cabecera
                                    float escala = 80; //%

                                    Image imagenHeader = Image.GetInstance(dirImagenHeader);
                                    imagenHeader.ScalePercent(escala);

                                    PdfPTable table = new PdfPTable(1);
                                    table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;

                                    //logo
                                    PdfPCell cell = new PdfPCell(imagenHeader);
                                    cell.Border = 0;
                                    cell.BorderWidth = 0;
                                    table.AddCell(cell);

                                    table.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - 20, writer.DirectContent);
                                }
                                else
                                {
                                    if (tipoDocumento == "afiliaciones")
                                    {
                                        //imagen de la cabecera
                                        float escala = 85; //%

                                        Image imagenHeader = Image.GetInstance(dirImagenHeader);
                                        imagenHeader.ScalePercent(escala);

                                        PdfPTable table = new PdfPTable(1);
                                        table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;

                                        //logo
                                        PdfPCell cell = new PdfPCell(imagenHeader);
                                        cell.Border = 0;
                                        cell.BorderWidth = 0;
                                        table.AddCell(cell);

                                        table.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - 20, writer.DirectContent);
                                    }
                                    else
                                    {
                                        if (tipoDocumento == "manualServicio")
                                        {
                                            int pageN = writer.PageNumber;

                                            Image imagenHeader = Image.GetInstance(dirImagenHeader);
                                            imagenHeader.ScaleToFit(100, 100);
                                            //imagenHeader.ScalePercent(escala);

                                            PdfPTable table = new PdfPTable(5);
                                            table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;

                                            Font fuente = new Font(Font.FontFamily.HELVETICA, 9);
                                            PdfPCell cell = new PdfPCell(imagenHeader);
                                            cell.Colspan = 2;
                                            cell.Padding = 3;
                                            cell.Border = 1;
                                            cell.BorderWidthBottom = 1;
                                            cell.BorderWidthLeft = 1;
                                            cell.BorderWidthRight = 1;
                                            cell.BorderWidthTop = 1;
                                            cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                            cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                                            table.AddCell(cell);

                                            PdfPCell cell1 = new PdfPCell(new Phrase("PROCESO GESTIÓN COMERCIAL", fuente));
                                            cell1.Colspan = 3;
                                            cell1.Padding = 3;
                                            cell1.Border = 1;
                                            cell1.BorderWidthBottom = 1;
                                            cell1.BorderWidthLeft = 1;
                                            cell1.BorderWidthRight = 1;
                                            cell1.BorderWidthTop = 1;
                                            cell1.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                            cell1.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                                            table.AddCell(cell1);

                                            PdfPCell cell2 = new PdfPCell(new Phrase("MANUAL DE SERVICIO", fuente));
                                            cell2.Colspan = 5;
                                            cell2.Padding = 3;
                                            cell2.Border = 1;
                                            cell2.BorderWidthBottom = 1;
                                            cell2.BorderWidthLeft = 1;
                                            cell2.BorderWidthRight = 1;
                                            cell2.BorderWidthTop = 1;
                                            cell2.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                            cell2.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                                            table.AddCell(cell2);

                                            PdfPCell cell3 = new PdfPCell(new Phrase("FECHA DE EMISIÓN\n" + DateTime.Now.ToShortDateString(), fuente));
                                            //cell3.Colspan = 5;
                                            cell3.Padding = 3;
                                            cell3.Border = 1;
                                            cell3.BorderWidthBottom = 1;
                                            cell3.BorderWidthLeft = 1;
                                            cell3.BorderWidthRight = 1;
                                            cell3.BorderWidthTop = 1;
                                            cell3.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                            cell3.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                                            table.AddCell(cell3);

                                            PdfPCell cell4 = new PdfPCell(new Phrase("VERSION:\n" + versionManual, fuente));
                                            cell4.Colspan = 2;
                                            cell4.Padding = 3;
                                            cell4.Border = 1;
                                            cell4.BorderWidthBottom = 1;
                                            cell4.BorderWidthLeft = 1;
                                            cell4.BorderWidthRight = 1;
                                            cell4.BorderWidthTop = 1;
                                            cell4.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                            cell4.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                                            table.AddCell(cell4);

                                            PdfPCell cell5 = new PdfPCell(new Phrase("APLICA A PARTIR:\n" + fechaApartirDe.ToShortDateString(), fuente));
                                            //cell4.Colspan = 2;
                                            cell5.Padding = 3;
                                            cell5.Border = 1;
                                            cell5.BorderWidthBottom = 1;
                                            cell5.BorderWidthLeft = 1;
                                            cell5.BorderWidthRight = 1;
                                            cell5.BorderWidthTop = 1;
                                            cell5.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                            cell5.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                                            table.AddCell(cell5);

                                            PdfPCell cell6 = new PdfPCell(new Phrase("PAGINA " + pageN.ToString(), fuente));
                                            //cell4.Colspan = 2;
                                            cell6.Padding = 3;
                                            cell6.Border = 1;
                                            cell6.BorderWidthBottom = 1;
                                            cell6.BorderWidthLeft = 1;
                                            cell6.BorderWidthRight = 1;
                                            cell6.BorderWidthTop = 1;
                                            cell6.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                            cell6.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                                            table.AddCell(cell6);

                                            table.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - 20, writer.DirectContent);
                                        }
                                        else
                                        {
                                            if (tipoDocumento == "entrevista_retiro")
                                            {
                                                //imagen de la cabecera
                                                float escala = 85; //%

                                                Image imagenHeader = Image.GetInstance(dirImagenHeader);
                                                imagenHeader.ScalePercent(escala);

                                                PdfPTable table = new PdfPTable(1);
                                                table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;

                                                //logo
                                                PdfPCell cell = new PdfPCell(imagenHeader);
                                                cell.Border = 0;
                                                cell.BorderWidth = 0;
                                                table.AddCell(cell);

                                                table.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - 20, writer.DirectContent);
                                            }
                                            else
                                            {
                                                if (tipoDocumento == "apertura_cuenta_avvillas")
                                                {
                                                    //imagen de la cabecera
                                                    float escala = 70; //%

                                                    Image imagenHeader = Image.GetInstance(dirImagenHeader);
                                                    imagenHeader.ScalePercent(escala);

                                                    PdfPTable table = new PdfPTable(1);
                                                    table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;

                                                    //logo
                                                    PdfPCell cell = new PdfPCell(imagenHeader);
                                                    cell.Border = 0;
                                                    cell.BorderWidth = 0;
                                                    table.AddCell(cell);

                                                    table.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - 20, writer.DirectContent);
                                                }
                                            }
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
Exemplo n.º 2
0
 protected override void CheckGState(PdfWriter writer, int key, Object obj1) {
     PdfDictionary gs = (PdfDictionary) obj1;
     PdfObject obj = gs.Get(PdfName.BM);
     if (obj != null && !allowedBlendModes.Contains((PdfName)obj)) {
         throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("blend.mode.1.not.allowed", obj.ToString()));
     }
 }
Exemplo n.º 3
0
 public UserReport()
 {
     doc = new Document(PageSize.A4.Rotate(), 35, 35, 35, 35);
     writer = PdfWriter.GetInstance(doc, ms);
     MyPageEvents events = new MyPageEvents();
     writer.PageEvent = events;
 }
 /**
  * The verification constructor. This class should only be created with
  * PdfStamper.getLtvVerification() otherwise the information will not be
  * added to the Pdf.
  * @param stp the PdfStamper to apply the validation to
  */
 public LtvVerification(PdfStamper stp)
 {
     this.stp = stp;
     writer = stp.Writer;
     reader = stp.Reader;
     acroFields = stp.AcroFields;
 }
Exemplo n.º 5
0
        protected override void CheckFileSpec(PdfWriter writer, int key, Object obj1) {
            if (obj1 is PdfFileSpecification) {
                PdfDictionary fileSpec = (PdfFileSpecification) obj1;
                if (!fileSpec.Contains(PdfName.UF) || !fileSpec.Contains(PdfName.F)
                    || !fileSpec.Contains(PdfName.DESC)) {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("file.specification.dictionary.shall.contain.f.uf.and.desc.entries"));
                }

                PdfObject obj = fileSpec.Get(PdfName.AFRELATIONSHIP);

                if (obj == null || !obj.IsName() || !allowedAFRelationships.Contains(obj as PdfName)) {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("file.specification.dictionary.shall.contain.correct.afrelationship.key"));
                }

                if (fileSpec.Contains(PdfName.EF)) {
                    PdfDictionary dict = GetDirectDictionary(fileSpec.Get(PdfName.EF));
                    if (dict == null || !dict.Contains(PdfName.F)) {
                        throw new PdfAConformanceException(obj1,
                            MessageLocalization.GetComposedMessage("ef.key.of.file.specification.dictionary.shall.contain.dictionary.with.valid.f.key"));
                    }

                    PdfDictionary embeddedFile = GetDirectDictionary(dict.Get(PdfName.F));
                    if (embeddedFile == null) {
                        throw new PdfAConformanceException(obj1,
                            MessageLocalization.GetComposedMessage("ef.key.of.file.specification.dictionary.shall.contain.dictionary.with.valid.f.key"));
                    }

                    CheckEmbeddedFile(embeddedFile);
                }
            }
        }
Exemplo n.º 6
0
 // we override the onCloseDocument method
 public override void OnCloseDocument(PdfWriter writer, Document document)
 {
     template.BeginText();
     template.SetFontAndSize(bf, 8);
     template.ShowText((writer.PageNumber - 1).ToString());
     template.EndText();
 }
Exemplo n.º 7
0
        /// <summary>
        ///     Writes the cross reference section to the passed PDF writer.
        /// </summary>
        internal void Write(PdfWriter writer)
        {
            // Write the 'xref' keyword.
            writer.WriteKeywordLine(Keyword.XRef);

            // Get the one and only subsection to write itself.
            subsection.Write(writer);
        }
Exemplo n.º 8
0
 protected internal override void Write(PdfWriter writer)
 {
     writer.WriteKeyword(Keyword.ArrayBegin);
     writer.WriteSpace();
     writer.Write(startCID);
     writer.WriteSpace();
     array.Write(writer);
     writer.WriteKeyword(Keyword.ArrayEnd);
 }
Exemplo n.º 9
0
 // we override the onChapter method
 public override void OnChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title)
 {
     System.Text.StringBuilder buf = new System.Text.StringBuilder();
     foreach (Chunk chunk in title.Chunks)
     {
         buf.Append(chunk.Content);
     }
     act = buf.ToString();
 }
Exemplo n.º 10
0
 protected internal override void Write(PdfWriter writer)
 {
     writer.WriteKeywordLine(Keyword.Trailer);
     base.Write(writer);
     writer.WriteLine();
     writer.WriteKeywordLine(Keyword.StartXRef);
     writer.WriteLine(xrefOffset);
     writer.WriteKeyword(Keyword.Eof);
 }
Exemplo n.º 11
0
 protected internal override void Write(PdfWriter writer)
 {
     PdfArray dest = new PdfArray();
     dest.Add(pageReference);
     dest.Add(PdfName.Names.XYZ);
     dest.Add(new PdfNumeric(xPosition));
     dest.Add(new PdfNumeric(yPosition));
     dest.Add(PdfNull.Null);
     this[PdfName.Names.D] = dest;
     base.Write(writer);
 }
Exemplo n.º 12
0
 internal void CheckPdfAConformance(PdfWriter writer, int key, Object obj1) {
     if(writer == null || !writer.IsPdfIso())
         return;
     switch(key) {
         case PdfIsoKeys.PDFISOKEY_FONT:
             CheckFont(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_IMAGE:
             CheckImage(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_GSTATE:
             CheckGState(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_LAYER:
             CheckLayer(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_TRAILER:
             CheckTrailer(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_STREAM:
             CheckStream(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_FILESPEC:
             CheckFileSpec(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_OBJECT:
             CheckPdfObject(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_CANVAS:
             CheckCanvas(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_COLOR:
         case PdfIsoKeys.PDFISOKEY_CMYK:
         case PdfIsoKeys.PDFISOKEY_RGB:
             CheckColor(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_ANNOTATION:
             CheckAnnotation(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_ACTION:
             CheckAction(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_FORM:
             CheckForm(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_STRUCTELEM:
             if(CheckStructure(conformanceLevel))
                 CheckStructElem(writer, key, obj1);
             break;
         default:
             break;
     }
 }
Exemplo n.º 13
0
 protected internal override void Write(PdfWriter writer)
 {
     if (fonts.Count > 0)
     {
         this[PdfName.Names.Font] = fonts;
     }
     if (xObjects.Count > 0)
     {
         this[PdfName.Names.XObject] = xObjects;
     }
     base.Write(writer);
 }
Exemplo n.º 14
0
 public void Generate(Document doc, DocumentType docType, string addSheet,PdfWriter writer)
 {
     GenerateDocument(doc, docType, addSheet,writer);
     /* Temporary moving this code to Method Statement as Continuation sheet needs to be printed on the
      * back of main sheet before the additional notes. After a proper solution we will try
      * to put it back or otherwise.
     if (overflowTable != null)
     {
         doc.NewPage();
         doc.Add(overflowTable);
     }
      * */
 }
Exemplo n.º 15
0
        protected internal override void Write(PdfWriter writer)
        {
            // Add a dictionary entry for /Count (the number of leaf 
            // nodes (page objects) that are descendants of this
            // node within the page tree.
            int count = 0;
            for (int x = 0; x < kids.Count; x++)
            {
                count++; // TODO: test if it is a leaf.
            }
            this[PdfName.Names.Count] = new PdfNumeric(count);

            base.Write(writer);
        }
Exemplo n.º 16
0
 protected override void CheckGState(PdfWriter writer, int key, Object obj1) {
     PdfDictionary gs = (PdfDictionary) obj1;
     PdfObject obj = gs.Get(PdfName.BM);
     if (obj != null && !PdfGState.BM_NORMAL.Equals(obj) && !PdfGState.BM_COMPATIBLE.Equals(obj))
         throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("blend.mode.1.not.allowed", obj.ToString()));
     obj = gs.Get(PdfName.CA);
     double v = 0.0;
     if (obj != null && (v = ((PdfNumber) obj).DoubleValue) != 1.0)
         throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("transparency.is.not.allowed.ca.eq.1", v));
     obj = gs.Get(PdfName.ca_);
     v = 0.0;
     if (obj != null && (v = ((PdfNumber) obj).DoubleValue) != 1.0)
         throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("transparency.is.not.allowed.ca.eq.1", v));
 }
Exemplo n.º 17
0
    protected override void CheckImage(PdfWriter writer, int key, Object obj1) {
        PdfImage pdfImage = (PdfImage) obj1;
        if (pdfImage != null && (pdfImage.Image is Jpeg2000)) {
            Jpeg2000 jpeg2000 = (Jpeg2000) pdfImage.Image;
            if (!jpeg2000.IsJp2()) {
                throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("only.jpx.baseline.set.of.features.shall.be.used"));
            }
            if (jpeg2000.GetNumOfComps() != 1 && jpeg2000.GetNumOfComps() != 3 && jpeg2000.GetNumOfComps() != 4) {
                throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("the.number.of.colour.channels.in.the.jpeg2000.data.shall.be.123"));
            }
            if (jpeg2000.Bpc < 1 || jpeg2000.Bpc > 38) {
                throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("the.bit-depth.of.the.jpeg2000.data.shall.have.a.value.in.the.range.1to38"));
            }
            if (jpeg2000.GetBpcBoxData() != null) {
                throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("all.colour.channels.in.the.jpeg2000.data.shall.have.the.same.bit-depth"));
            }
            List<Jpeg2000.ColorSpecBox> colorSpecBoxes = jpeg2000.GetColorSpecBoxes();
            if (colorSpecBoxes != null) {
                if (colorSpecBoxes.Count > 1) {
                    int approx0x01 = 0;
                    foreach (Jpeg2000.ColorSpecBox colorSpecBox in colorSpecBoxes) {
                        if (colorSpecBox.GetApprox() == 1)
                            approx0x01++;
                    }
                    if (approx0x01 != 1) {
                        throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("exactly.one.colour.space.specification.shall.have.the.value.0x01.in.the.approx.field"));
                    }
                }
                foreach (Jpeg2000.ColorSpecBox colorSpecBox in colorSpecBoxes) {
                    if (colorSpecBox.GetMeth() != 1 && colorSpecBox.GetMeth() != 2 && colorSpecBox.GetMeth() != 3) {
                        throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("the.value.of.the.meth.entry.in.colr.box.shall.be.123"));
                    }
                    if (colorSpecBox.GetEnumCs() == 19) {
                        throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("jpeg2000.enumerated.colour.space.19.(CIEJab).shall.not.be.used"));
                    }
                    byte[] colorProfileBytes = colorSpecBox.GetColorProfile();
                    if (colorProfileBytes != null) {
                        //ICC profile verification should follow here.
                    }
                }

            }
        }
    }
Exemplo n.º 18
0
 public override void OnEndPage(PdfWriter writer, Document document)
 {
     PdfPTable table = new PdfPTable(3);
     try
     {
         table.SetWidths(new int[] { 24, 24, 2 });
         table.TotalWidth = 527;
         table.LockedWidth = true;
         table.DefaultCell.FixedHeight = 20;
         table.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
         table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
         table.AddCell(string.Format("{0}", writer.PageNumber));
         table.WriteSelectedRows(0, -1, 34, 803, writer.DirectContent);
     }
     catch (DocumentException de)
     {
         throw de;
     }
 }
Exemplo n.º 19
0
 protected override void GenerateDocument(Document doc, DocumentType docType, string addSheet, PdfWriter writer)
 {
     DepartmentOrderDocTableAdapters.DocumentContentTableAdapter ta = new DepartmentOrderDocTableAdapters.DocumentContentTableAdapter();
     IEnumerator iEnum = ta.GetDocumentContentById(docType.DocId, docType.CoId, docType.DeptId).GetEnumerator();
     if (iEnum.MoveNext())
     {
         DepartmentOrderDoc.DocumentContentEntityRow docContent = (DepartmentOrderDoc.DocumentContentEntityRow)iEnum.Current;
         if (docContent.file_contents != null && docContent.file_contents.Length > 0)
         {
             PdfContentByte pdfContentByte = writer.DirectContent;
             PdfReader reader = new PdfReader(docContent.file_contents);
             for (int page = 1; page <= reader.NumberOfPages; page++)
             {
                 doc.NewPage();
                 PdfImportedPage importedPage = writer.GetImportedPage(reader, page);
                 pdfContentByte.AddTemplate(importedPage, 0, 0);
             }
         }
     }
 }
Exemplo n.º 20
0
 internal void CheckPdfAConformance(PdfWriter writer, int key, Object obj1) {
     if(writer == null || !writer.IsPdfIso())
         return;
     switch(key) {
         case PdfIsoKeys.PDFISOKEY_FONT:
             CheckFont(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_IMAGE:
             CheckImage(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_GSTATE:
             CheckGState(writer, key, obj1);
             break;
         case PdfIsoKeys.PDFISOKEY_LAYER:
             CheckLayer(writer, key, obj1);
             break;
         default:
             break;
     }
 }
Exemplo n.º 21
0
 protected override void CheckFont(PdfWriter writer, int key, Object obj1) {
     BaseFont bf = (BaseFont) obj1;
     if (bf.FontType == BaseFont.FONT_TYPE_DOCUMENT) {
         PdfStream prs = null;
         PdfDictionary fontDictionary = ((DocumentFont) bf).FontDictionary;
         PdfDictionary fontDescriptor = fontDictionary.GetAsDict(PdfName.FONTDESCRIPTOR);
         if (fontDescriptor != null) {
             prs = fontDescriptor.GetAsStream(PdfName.FONTFILE);
             if (prs == null) {
                 prs = fontDescriptor.GetAsStream(PdfName.FONTFILE2);
             }
             if (prs == null) {
                 prs = fontDescriptor.GetAsStream(PdfName.FONTFILE3);
             }
         }
         if (prs == null) {
             throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("all.the.fonts.must.be.embedded.this.one.isn.t.1", ((BaseFont) obj1).PostscriptFontName));
         }
     } else {
         if (!bf.IsEmbedded())
             throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("all.the.fonts.must.be.embedded.this.one.isn.t.1", ((BaseFont) obj1).PostscriptFontName));
     }
 }
Exemplo n.º 22
0
 // we override the onEndPage method
 public override void OnEndPage(PdfWriter writer, Document document)
 {
     int pageN = writer.PageNumber;
     String text = "Page " + pageN + " of ";
     float len = bf.GetWidthPoint(text, 8);
     cb.BeginText();
     cb.SetFontAndSize(bf, 8);
     cb.SetTextMatrix(760, 25);
     cb.ShowText(text);
     cb.EndText();
     cb.AddTemplate(template, 760 + len, 25);
     cb.BeginText();
     cb.SetFontAndSize(bf, 8);
     cb.SetTextMatrix(760, 820);
     if (pageN % 2 == 1)
     {
         cb.ShowText("Report");
     }
     else
     {
         cb.ShowText(act);
     }
     cb.EndText();
 }
Exemplo n.º 23
0
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);
            bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            cb = writer.DirectContent;


            headerTemplate = cb.CreateTemplate(100, 100);
            footerTemplate = cb.CreateTemplate(50, 50);

            var tabFot = new PdfPTable(4);
            // Dim cell As PdfPCell
            // tabFot.TotalWidth = 300.0F
            // '//cell = New PdfPCell(New Phrase("Footer"))
            // '//tabFot.AddCell(cell)
            // tabFot.WriteSelectedRows(0, -1, 150, document.Bottom, writer.DirectContent)
            var Text = "Pagina: " + writer.PageNumber + "  ";

            // cb.BeginText()
            // cb.SetFontAndSize(bf, 12)
            // cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45))
            // cb.ShowText(Text)
            // cb.EndText()
            // Dim len1 As Single = bf.GetWidthPoint(Text, 12)
            // '//Adds "12" in Page 1 of 12
            // cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) & len1, document.PageSize.GetTop(45))

            // //Add paging to footer
            // (
            float len = bf.GetWidthPoint(Text, 8);

            // cb.BeginText()
            // cb.SetFontAndSize(bf, 18)
            // cb.SetTextMatrix(document.PageSize.GetLeft(300), document.PageSize.GetBottom(700))
            // cb.ShowText("TITULO")
            // cb.EndText()
            // len = bf.GetWidthPoint("TITULO", 18)
            // cb.AddTemplate(footerTemplate, document.PageSize.GetLeft(300) & len, document.PageSize.GetBottom(700))


            string fechareporte = "FECHA EMISION: " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();

            cb.BeginText();
            cb.SetFontAndSize(bf, 7);
            cb.SetTextMatrix(document.PageSize.GetLeft(50), document.PageSize.GetBottom(20));
            cb.ShowText(fechareporte);
            cb.EndText();
            len = bf.GetWidthPoint(fechareporte, 7);
            cb.AddTemplate(footerTemplate, document.PageSize.GetLeft(50) + len, document.PageSize.GetBottom(20));

            cb.BeginText();
            cb.SetFontAndSize(bf, 7);
            cb.SetTextMatrix(document.PageSize.GetLeft(300), document.PageSize.GetBottom(20));
            cb.ShowText(Text);
            cb.EndText();
            len = bf.GetWidthPoint(Text, 7);
            cb.AddTemplate(footerTemplate, document.PageSize.GetLeft(300) + len, document.PageSize.GetBottom(20));

            string usuario = "<< " + UsuarioActivo + " >>";

            cb.BeginText();
            cb.SetFontAndSize(bf, 7);
            cb.SetTextMatrix(document.PageSize.GetRight(150), document.PageSize.GetBottom(20));
            cb.ShowText(usuario);
            cb.EndText();
            len = bf.GetWidthPoint(usuario, 7);
            cb.AddTemplate(footerTemplate, document.PageSize.GetRight(150) + len, document.PageSize.GetBottom(20));

            //string linea = "————  ARGUMENTOS  ——————————————————————————————————————————————————————————————————";
            //cb.BeginText();
            //cb.SetFontAndSize(bf, 7);
            //cb.SetTextMatrix(document.PageSize.GetLeft(35), document.PageSize.GetBottom(60));
            //cb.ShowText(linea);
            //cb.EndText();
            //len = bf.GetWidthPoint(linea, 7);
            //cb.AddTemplate(footerTemplate, document.PageSize.GetLeft(35) + len, document.PageSize.GetBottom(60));



            //PdfContentByte rectangulo; // declaración del rectángulo
            //rectangulo = writer.DirectContent; // código necesario antes de dar coordenadas del rectángulo

            //rectangulo.SetLineWidth(1); // configurando el ancho de linea
            //rectangulo.SetColorStroke(BaseColor.BLACK); // dar color a trazo. Sin esto el rectángulo se dibuja con el ultimo color de trazo configurado
            //rectangulo.Rectangle(33.0F, 763.0F, 555.0F, -730.0F); // 100.0F, 580.0F, coordenada punto de inicio
            //rectangulo.Stroke(); // traza el rectangulo actual       '200.0F, ancho del rectángulo. '-100.0F alto del rectángulo

            // ----------------------------------------------------------------------------------------------------------------
            // ARGUMENTOS PIE DE PAGINA
            // ----------------------------------------------------------------------------------------------------------------
            //string busqueda = "BUSQUEDA: -" + buscar_ + "-";
            //cb.BeginText();
            //cb.SetFontAndSize(bf, 7);
            //cb.SetTextMatrix(document.PageSize.GetLeft(50), document.PageSize.GetBottom(45));
            //cb.ShowText(busqueda);
            //cb.EndText();

            //len = bf.GetWidthPoint(busqueda, 7);
            //cb.AddTemplate(footerTemplate, document.PageSize.GetLeft(50) + len, document.PageSize.GetBottom(45));

            //string atributo = "ATRIBUTO: " + atributo_ + "";
            //cb.BeginText();
            //cb.SetFontAndSize(bf, 7);
            //cb.SetTextMatrix(document.PageSize.GetLeft(280), document.PageSize.GetBottom(45));
            //cb.ShowText(atributo);
            //cb.EndText();

            //len = bf.GetWidthPoint(atributo, 7);
            //cb.AddTemplate(footerTemplate, document.PageSize.GetLeft(280) + len, document.PageSize.GetBottom(45));

            //string estado = "ESTADO: " + estado_ + "";
            //cb.BeginText();
            //cb.SetFontAndSize(bf, 7);
            //cb.SetTextMatrix(document.PageSize.GetRight(150), document.PageSize.GetBottom(45));
            //cb.ShowText(estado);
            //cb.EndText();
            //len = bf.GetWidthPoint(estado_, 7);
            //cb.AddTemplate(footerTemplate, document.PageSize.GetRight(150) + len, document.PageSize.GetBottom(45));
        }
Exemplo n.º 24
0
        public ActionResult GerarRelatorioLista()
        {
            // Prepara geração
            if ((String)Session["Ativa"] == null)
            {
                return(RedirectToAction("Login", "ControleAcesso"));
            }
            String data = DateTime.Today.Date.ToShortDateString();

            data = data.Substring(0, 2) + data.Substring(3, 2) + data.Substring(6, 4);
            String        nomeRel  = "AgendaLista" + "_" + data + ".pdf";
            List <AGENDA> lista    = (List <AGENDA>)Session["ListaAgenda"];
            AGENDA        filtro   = (AGENDA)Session["FiltroAgenda"];
            Font          meuFont  = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
            Font          meuFont1 = FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
            Font          meuFont2 = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

            // Cria documento
            Document  pdfDoc    = new Document(PageSize.A4.Rotate(), 10, 10, 10, 10);
            PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

            pdfDoc.Open();

            // Linha horizontal
            Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLUE, Element.ALIGN_LEFT, 1)));

            pdfDoc.Add(line);

            // Cabeçalho
            PdfPTable table = new PdfPTable(5);

            table.WidthPercentage     = 100;
            table.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
            table.SpacingBefore       = 1f;
            table.SpacingAfter        = 1f;

            PdfPCell cell = new PdfPCell();

            cell.Border = 0;
            Image image = Image.GetInstance(Server.MapPath("~/Images/5.png"));

            image.ScaleAbsolute(50, 50);
            cell.AddElement(image);
            table.AddCell(cell);

            cell = new PdfPCell(new Paragraph("Agenda - Listagem", meuFont2))
            {
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                HorizontalAlignment = Element.ALIGN_CENTER
            };
            cell.Border  = 0;
            cell.Colspan = 4;
            table.AddCell(cell);
            pdfDoc.Add(table);

            // Linha Horizontal
            Paragraph line1 = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLUE, Element.ALIGN_LEFT, 1)));

            pdfDoc.Add(line1);
            line1 = new Paragraph("  ");
            pdfDoc.Add(line1);

            // Grid
            table = new PdfPTable(new float[] { 60f, 60f, 90f, 200f, 120f, 70f, 50f });
            table.WidthPercentage     = 100;
            table.HorizontalAlignment = 0;
            table.SpacingBefore       = 1f;
            table.SpacingAfter        = 1f;

            cell = new PdfPCell(new Paragraph("Itens de Agenda selecionados pelos parametros de filtro abaixo", meuFont1))
            {
                VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT
            };
            cell.Colspan         = 6;
            cell.BackgroundColor = BaseColor.LIGHT_GRAY;
            table.AddCell(cell);

            cell = new PdfPCell(new Paragraph("Data", meuFont))
            {
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                HorizontalAlignment = Element.ALIGN_LEFT
            };
            cell.BackgroundColor = BaseColor.LIGHT_GRAY;
            table.AddCell(cell);
            cell = new PdfPCell(new Paragraph("Hora", meuFont))
            {
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                HorizontalAlignment = Element.ALIGN_LEFT
            };
            cell.BackgroundColor = BaseColor.LIGHT_GRAY;
            table.AddCell(cell);
            cell = new PdfPCell(new Paragraph("Categoria", meuFont))
            {
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                HorizontalAlignment = Element.ALIGN_LEFT
            };
            cell.BackgroundColor = BaseColor.LIGHT_GRAY;
            table.AddCell(cell);
            cell = new PdfPCell(new Paragraph("Título", meuFont))
            {
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                HorizontalAlignment = Element.ALIGN_LEFT
            };
            cell.BackgroundColor = BaseColor.LIGHT_GRAY;
            table.AddCell(cell);
            cell = new PdfPCell(new Paragraph("Contato", meuFont))
            {
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                HorizontalAlignment = Element.ALIGN_LEFT
            };
            cell.BackgroundColor = BaseColor.LIGHT_GRAY;
            table.AddCell(cell);
            cell = new PdfPCell(new Paragraph("Status", meuFont))
            {
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                HorizontalAlignment = Element.ALIGN_LEFT
            };
            cell.BackgroundColor = BaseColor.LIGHT_GRAY;
            table.AddCell(cell);
            cell = new PdfPCell(new Paragraph("Anexos", meuFont))
            {
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                HorizontalAlignment = Element.ALIGN_LEFT
            };
            cell.BackgroundColor = BaseColor.LIGHT_GRAY;
            table.AddCell(cell);

            foreach (AGENDA item in lista)
            {
                cell = new PdfPCell(new Paragraph(item.AGEN_DT_DATA.ToShortDateString(), meuFont))
                {
                    VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT
                };
                table.AddCell(cell);
                cell = new PdfPCell(new Paragraph(item.AGEN_HR_HORA.ToString(), meuFont))
                {
                    VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT
                };
                table.AddCell(cell);
                cell = new PdfPCell(new Paragraph(item.CATEGORIA_AGENDA.CAAG_NM_NOME, meuFont))
                {
                    VerticalAlignment   = Element.ALIGN_MIDDLE,
                    HorizontalAlignment = Element.ALIGN_LEFT
                };
                table.AddCell(cell);
                cell = new PdfPCell(new Paragraph(item.AGEN_NM_TITULO, meuFont))
                {
                    VerticalAlignment   = Element.ALIGN_MIDDLE,
                    HorizontalAlignment = Element.ALIGN_LEFT
                };
                table.AddCell(cell);
                if (item.USUARIO1 != null)
                {
                    cell = new PdfPCell(new Paragraph(item.USUARIO1.USUA_NM_NOME, meuFont))
                    {
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        HorizontalAlignment = Element.ALIGN_LEFT
                    };
                    table.AddCell(cell);
                }
                else
                {
                    cell = new PdfPCell(new Paragraph("-", meuFont))
                    {
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        HorizontalAlignment = Element.ALIGN_LEFT
                    };
                    table.AddCell(cell);
                }
                if (item.AGEN_IN_STATUS == 1)
                {
                    cell = new PdfPCell(new Paragraph("Ativo", meuFont))
                    {
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        HorizontalAlignment = Element.ALIGN_LEFT
                    };
                    table.AddCell(cell);
                }
                else if (item.AGEN_IN_STATUS == 2)
                {
                    cell = new PdfPCell(new Paragraph("Suspenso", meuFont))
                    {
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        HorizontalAlignment = Element.ALIGN_LEFT
                    };
                    table.AddCell(cell);
                }
                else
                {
                    cell = new PdfPCell(new Paragraph("Encerrado", meuFont))
                    {
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        HorizontalAlignment = Element.ALIGN_LEFT
                    };
                    table.AddCell(cell);
                }
                if (item.AGENDA_ANEXO.Count > 0)
                {
                    cell = new PdfPCell(new Paragraph(item.AGENDA_ANEXO.Count.ToString(), meuFont))
                    {
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        HorizontalAlignment = Element.ALIGN_LEFT
                    };
                    table.AddCell(cell);
                }
                else
                {
                    cell = new PdfPCell(new Paragraph("0", meuFont))
                    {
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        HorizontalAlignment = Element.ALIGN_LEFT
                    };
                    table.AddCell(cell);
                }
            }
            pdfDoc.Add(table);

            // Linha Horizontal
            Paragraph line2 = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLUE, Element.ALIGN_LEFT, 1)));

            pdfDoc.Add(line2);

            // Rodapé
            Chunk chunk1 = new Chunk("Parâmetros de filtro: ", FontFactory.GetFont("Arial", 10, Font.NORMAL, BaseColor.BLACK));

            pdfDoc.Add(chunk1);

            String parametros = String.Empty;
            Int32  ja         = 0;

            if (filtro != null)
            {
                if (filtro.CAAG_CD_ID > 0)
                {
                    parametros += "Categoria: " + filtro.CAAG_CD_ID;
                    ja          = 1;
                }
                if (filtro.AGEN_DT_DATA != null)
                {
                    if (ja == 0)
                    {
                        parametros += "Data: " + filtro.AGEN_DT_DATA.ToShortDateString();
                        ja          = 1;
                    }
                    else
                    {
                        parametros += " e Data: " + filtro.AGEN_DT_DATA.ToShortDateString();
                    }
                }
                if (filtro.AGEN_NM_TITULO != null)
                {
                    if (ja == 0)
                    {
                        parametros += "Título: " + filtro.AGEN_NM_TITULO;
                        ja          = 1;
                    }
                    else
                    {
                        parametros += " e Título: " + filtro.AGEN_NM_TITULO;
                    }
                }
                if (filtro.AGEN_DS_DESCRICAO != null)
                {
                    if (ja == 0)
                    {
                        parametros += "Descrição: " + filtro.AGEN_DS_DESCRICAO;
                        ja          = 1;
                    }
                    else
                    {
                        parametros += " e Descrição: " + filtro.AGEN_DS_DESCRICAO;
                    }
                }
                if (ja == 0)
                {
                    parametros = "Nenhum filtro definido.";
                }
            }
            else
            {
                parametros = "Nenhum filtro definido.";
            }
            Chunk chunk = new Chunk(parametros, FontFactory.GetFont("Arial", 9, Font.NORMAL, BaseColor.BLACK));

            pdfDoc.Add(chunk);

            // Linha Horizontal
            Paragraph line3 = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLUE, Element.ALIGN_LEFT, 1)));

            pdfDoc.Add(line3);

            // Finaliza
            pdfWriter.CloseStream = false;
            pdfDoc.Close();
            Response.Buffer      = true;
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=" + nomeRel);
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(pdfDoc);
            Response.End();

            return(RedirectToAction("MontarTelaAgenda"));
        }
Exemplo n.º 25
0
 abstract public void Close(PdfWriter writer);
Exemplo n.º 26
0
        protected void GeneratePDF()
        {
            Style boldStyle     = new Style().SetTextAlignment(TextAlignment.CENTER).SetFontSize(8).SetBold();
            Style headerMusculo = new Style().SetTextAlignment(TextAlignment.LEFT).SetBold();

            Style styleDatos = new Style().SetFontSize(7);

            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "Pdf Files|*.pdf";
            saveFileDialog1.Title  = "Save an Image File";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string Imagenpath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

                Image logo = new Image(ImageDataFactory.Create(Imagenpath + "\\Resources\\Icons\\OnixLogo.png"));

                string path = saveFileDialog1.FileName;
                try
                {
                    PdfWriter   pw          = new PdfWriter(path);
                    PdfDocument pdfDocument = new PdfDocument(pw);

                    pdfDocument.AddEventHandler(PdfDocumentEvent.START_PAGE, new HeaderEventHandler(logo));
                    Document doc = new Document(pdfDocument, PageSize.A4);
                    doc.SetMargins(55, 30, 15, 30);

                    Table table = new Table(1).UseAllAvailableWidth(); //USAR TODO EL ANCHO DE LA HOJA

                    table.AddCell(new Cell().Add(new Paragraph("Nom:").SetFontSize(8))
                                  .SetTextAlignment(TextAlignment.LEFT)
                                  .SetBold().SetBorder(Border.NO_BORDER));

                    doc.Add(table);


                    Table _table = new Table(7).UseAllAvailableWidth();


                    Cell _cell = new Cell().Add(new Paragraph(NombreTB.Text).SetFontSize(8.5f)).SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    _table.AddCell(_cell);

                    _cell = new Cell().Add(new Paragraph("Data inici rutina")).SetBorder(Border.NO_BORDER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    _table.AddCell(_cell.AddStyle(boldStyle));

                    _cell = new Cell().Add(new Paragraph(FechaTB.Text)).SetFontSize(8.5f).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    _table.AddCell(_cell);

                    _cell = new Cell().Add(new Paragraph("Data final rutina")).SetBorder(Border.NO_BORDER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    _table.AddCell(_cell.AddStyle(boldStyle));

                    _cell = new Cell().Add(new Paragraph(FechaFinTB.Text)).SetFontSize(8.5f).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    _table.AddCell(_cell);

                    _cell = new Cell().Add(new Paragraph("Rutina")).SetBorder(Border.NO_BORDER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    _table.AddCell(_cell.AddStyle(boldStyle));

                    _cell = new Cell().Add(new Paragraph(RutinaNumTB.Text).SetFontSize(8.5f).SetTextAlignment(TextAlignment.RIGHT)).SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    _table.AddCell(_cell);
                    doc.Add(_table);


                    Table tablaPrincipal = new Table(4);
                    tablaPrincipal.SetHorizontalBorderSpacing(0);
                    tablaPrincipal.SetVerticalBorderSpacing(0);
                    var listaDia = ejercicios.OrderBy(x => x.Dia).ToList();


                    foreach (var item in listaDia)
                    {
                        Table ejercicio = new Table(6);

                        Cell celda = new Cell(1, 6).SetBorder(Border.NO_BORDER).SetBackgroundColor(ColorConstants.LIGHT_GRAY);
                        ejercicio.AddCell(celda.Add(new Paragraph(item.Musculo).SetBold().SetFontSize(7).SetTextAlignment(TextAlignment.LEFT)));


                        celda = new Cell(1, 6).SetHorizontalAlignment(iText.Layout.Properties.HorizontalAlignment.LEFT)
                                .Add(new Paragraph(item.Ejercicio)
                                     .SetFontSize(7)).SetBorder(Border.NO_BORDER);
                        ejercicio.AddCell(celda);


                        celda = new Cell().Add(new Paragraph("Dia").SetFontSize(7.5f)).SetBorder(Border.NO_BORDER);
                        ejercicio.AddCell(celda.AddStyle(headerMusculo));

                        celda = new Cell().Add(new Paragraph(item.Dia.ToUpper()).SetTextAlignment(TextAlignment.CENTER)).SetBorder(new SolidBorder(0.5f));
                        ejercicio.AddCell(celda.AddStyle(styleDatos));

                        celda = new Cell().Add(new Paragraph("Ser").SetTextAlignment(TextAlignment.CENTER)).SetBorder(Border.NO_BORDER);
                        ejercicio.AddCell(celda.AddStyle(headerMusculo).SetFontSize(7.5f));

                        celda = new Cell().Add(new Paragraph(item.Series.ToString()).SetTextAlignment(TextAlignment.CENTER)).SetBorder(new SolidBorder(0.5f));
                        ejercicio.AddCell(celda.AddStyle(styleDatos));

                        celda = new Cell().Add(new Paragraph("Rep").SetTextAlignment(TextAlignment.CENTER)).SetBorder(Border.NO_BORDER);
                        ejercicio.AddCell(celda.AddStyle(headerMusculo).SetFontSize(7.5f));

                        celda = new Cell().Add(new Paragraph(item.Repeticiones.ToString()).SetTextAlignment(TextAlignment.CENTER)).SetBorder(new SolidBorder(0.5f));
                        ejercicio.AddCell(celda.AddStyle(styleDatos));

                        celda = new Cell(1, 2).Add(new Paragraph("Descans").SetFontSize(8).SetBold())
                                .Add(new Paragraph(Nullable(item.Descanso)).SetBorder(new SolidBorder(ColorConstants.BLACK, 0.5f)).SetFontSize(8).SetTextAlignment(TextAlignment.CENTER)).SetBorder(Border.NO_BORDER);
                        ejercicio.AddCell(celda);

                        if (string.IsNullOrWhiteSpace(item.ImagePath))
                        {
                            MessageBox.Show("Algun ejercicio no tiene asignada ninguna foto");
                            return;
                        }
                        Image imgEjercicio = new Image(ImageDataFactory.Create(item.ImagePath));


                        celda = new Cell(1, 4).Add(imgEjercicio.SetHeight(63f).SetWidth(85f)).SetBorder(Border.NO_BORDER);
                        ejercicio.AddCell(celda);



                        celda = new Cell(1, 6).Add(new Paragraph("Notes").AddStyle(headerMusculo).SetFontSize(7f)).SetBorder(Border.NO_BORDER);
                        ejercicio.AddCell(celda);

                        celda = new Cell(1, 6).Add(new Paragraph(Nullable(item.Comentario)).SetFontSize(7f));
                        ejercicio.AddCell(celda);

                        tablaPrincipal.AddCell(ejercicio);
                    }


                    doc.Add(tablaPrincipal);

                    doc.Close();

                    MessageBox.Show("Se ha generado el pdf en la ruta: " + path);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Ha ocurrido un error en la creacion de la rutina\nFaltan datos en los ejercicio");
                    return;
                }
            }
        }
Exemplo n.º 27
0
        public override void tsbExportar_Click(object sender, EventArgs e)
        {
            if (dgvPlan.Rows.Count > 0)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter   = "PDF (*.pdf)|*.pdf";
                sfd.FileName = "Output.pdf";
                bool fileError = false;
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    if (File.Exists(sfd.FileName))
                    {
                        try
                        {
                            File.Delete(sfd.FileName);
                        }
                        catch (IOException ex)
                        {
                            fileError = true;
                            MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
                        }
                    }
                    if (!fileError)
                    {
                        try
                        {
                            PdfPTable pdfTable = new PdfPTable(dgvPlan.Columns.Count);
                            pdfTable.DefaultCell.Padding = 3;
                            pdfTable.WidthPercentage     = 100;
                            pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;

                            foreach (DataGridViewColumn column in dgvPlan.Columns)
                            {
                                PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
                                pdfTable.AddCell(cell);
                            }

                            foreach (DataGridViewRow row in dgvPlan.Rows)
                            {
                                foreach (DataGridViewCell cell in row.Cells)
                                {
                                    pdfTable.AddCell(cell.Value.ToString());
                                }
                            }

                            using (FileStream stream = new FileStream(sfd.FileName, FileMode.Create))
                            {
                                Document pdfDoc = new Document(PageSize.A4, 10f, 20f, 20f, 10f);
                                PdfWriter.GetInstance(pdfDoc, stream);
                                pdfDoc.Open();
                                pdfDoc.Add(pdfTable);
                                pdfDoc.Close();
                                stream.Close();
                            }

                            MessageBox.Show("Planes exportados exitosamente", "Info");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Error :" + ex.Message);
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("No existen planes para exportar", "Info");
            }
        }
Exemplo n.º 28
0
        public async Task <IActionResult> OnPostAsync()
        {
            Image image = new Image(ImageDataFactory.Create(@"wwwroot\images\levepo.png"));

            image.ScaleToFit(1700, 1000);
            image.SetHorizontalAlignment(HorizontalAlignment.CENTER);
            image.SetWidth(200);
            using (MemoryStream dest = new MemoryStream())
            {
                var writer   = new PdfWriter(dest);
                var pdf      = new PdfDocument(writer);
                var document = new Document(pdf);
                document.Add(new Paragraph(new Text("Levepo Terms and Conditions (\"Terms\")")
                                           .SetBold()
                                           .SetFontSize(28)
                                           .SetTextAlignment(TextAlignment.CENTER)
                                           .SetHorizontalAlignment(HorizontalAlignment.CENTER)));
                document.Add(new Paragraph(""));
                document.Add(image);
                document.Add(new Paragraph(""));
                document.Add(new Paragraph("Please read these Terms and Conditions (\"Terms\", \"Terms and Conditions\") carefully before using the https://levepo.azurewebsites.com website (the \"Service\") operated by Levepo (\"us\", \"we\", or \"our\")."));
                document.Add(new Paragraph(""));
                document.Add(new Paragraph("\"John doe\" access to and use of the Service is conditioned on your acceptance of and compliance with these Terms. These Terms apply to all visitors, users and others who access or use the Service."));
                document.Add(new Paragraph(""));
                document.Add(new Paragraph(new Text("By accessing or using the Service you agree to be bound by these Terms. If you disagree with any part of the terms then you may not access the Service.").SetBold()));
                document.Add(new Paragraph(""));
                document.Add(new Paragraph(new Text("Purchases").SetBold()));
                document.Add(new Paragraph(""));
                document.Add(new Paragraph("If you wish to purchase any product or service made available through the Service (\"Purchase\"), you may be asked to supply certain information relevant to your Purchase including, without limitation, your name, email address, delivery address and social security number"));
                document.Add(new Paragraph(""));
                document.Add(new Paragraph(new Text("Subscriptions").SetBold()));
                document.Add(new Paragraph(""));
                document.Add(new Paragraph("Some parts of the Service are billed on a subscription basis (\"Subscription(s)\"). You will be billed in advance on a recurring and periodic basis (\"Billing Cycle\"). Billing cycles are set either on a monthly or annual basis, depending on the type of subscription plan you select when purchasing a Subscription."));
                document.Add(new Paragraph(""));
                document.Add(new Paragraph(new Text("Changes")).SetBold());
                document.Add(new Paragraph(""));
                document.Add(new Paragraph("We reserve the right, at our sole discretion, to modify or replace these Terms at any time. If a revision is material we will try to provide at least 30 (change this) days' notice prior to any new terms taking effect. What constitutes a material change will be determined at our sole discretion."));
                document.Add(new Paragraph(""));
                document.Add(new Paragraph(new Text("Contact Us").SetBold()));
                document.Add(new Paragraph(""));
                document.Add(new Paragraph("If you have any questions about these Terms, please contact us."));
                document.Close();

                string base64String = Convert.ToBase64String(dest.ToArray());

                List <DocumentInfo> documents = new List <DocumentInfo>
                {
                    new DocumentInfo()
                    {
                        Name = "John Doe",
                        Data = base64String
                    }
                };

                Signer signer = new Signer()
                {
                    UserId = PersonalNumber,
                    Method = "SE_BANKID"
                };

                var signatureRequest = new SignatureRequest()
                {
                    Documents   = documents,
                    Name        = $"Rent-a-Wood",
                    Message     = "Agree to renting firewood",
                    ResponseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}/api/callback",
                    Signer      = signer
                };

                HttpClient client = await HttpUtil.GetAuthorizedHttpClientAsync();

                MemoryStream ms = new MemoryStream();
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(SignatureRequest));
                ser.WriteObject(ms, signatureRequest);
                byte[] json = ms.ToArray();
                ms.Close();

                var    content      = new StringContent(Encoding.UTF8.GetString(json, 0, json.Length), Encoding.UTF8, "application/json");
                var    response     = client.PostAsync($"{Startup.Configuration["Api:SignApi:Url"]}/sign", content).Result;
                string responseBody = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    RequestId = JsonConvert.DeserializeObject <SignResponse>(responseBody).RequestId;
                    var requestInfoResponse = client.GetAsync($"{Startup.Configuration["Api:SignApi:Url"]}/request/{RequestId}?includeDocs=true").Result;
                    if (requestInfoResponse.IsSuccessStatusCode)
                    {
                        string requestInfoBody = await requestInfoResponse.Content.ReadAsStringAsync();

                        RequestStorage.Upsert(JsonConvert.DeserializeObject <RequestInfo>(requestInfoBody));

                        TempData["RequestId"] = RequestId;
                        return(RedirectToPage("SignStatus"));
                    }

                    return(RedirectToPage("RentItem"));
                }
                else
                {
                    ErrorResponse = JsonConvert.DeserializeObject <ErrorResponse>(responseBody);
                    if (ErrorResponse == null)
                    {
                        ErrorResponse = new ErrorResponse
                        {
                            ErrorCode    = $"{response.StatusCode}",
                            ErrorMessage = responseBody
                        };
                    }
                }
            }

            //ClearResult = false;

            return(Page());
        }
Exemplo n.º 29
0
        protected void getReport()
        {
            try
            {
                List <Entities.ExternalDesignation> listExternalDesignation = ExternalDesignationBLL.getInstance().getAll();
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
                text::Document         pdfDoc       = new text::Document(text::PageSize.A4, 10, 10, 10, 10);
                pdfDoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
                PdfWriter.GetInstance(pdfDoc, memoryStream);
                pdfDoc.Open();

                String imagepath           = Server.MapPath("../../images/page-icons");
                iTextSharp.text.Image deas = iTextSharp.text.Image.GetInstance(imagepath + "/DEAS-logo.jpg");
                deas.ScaleToFit(140f, 120f);
                //Give space before image
                deas.SpacingBefore = 10f;
                //Give some space after the image
                deas.SpacingAfter = 1f;
                deas.Alignment    = text::Element.ALIGN_LEFT;
                pdfDoc.Add(deas);

                text::Paragraph title = new text::Paragraph();
                title.Font      = text::FontFactory.GetFont("dax-black", 32, new text::BaseColor(0, 51, 102));
                title.Alignment = text::Element.ALIGN_CENTER;
                title.Add("\n\n Reporte de Nombramientos Externos\n\n");
                pdfDoc.Add(title);


                if (listExternalDesignation.Count > 0)
                {
                    foreach (Entities.ExternalDesignation pExternalDesignation in listExternalDesignation)
                    {
                        PdfPTable oPTable = new PdfPTable(5);
                        oPTable.TotalWidth = 100;
                        oPTable.AddCell("Funcionario");
                        oPTable.AddCell("Cargo");
                        oPTable.AddCell("Lugar de Trabajo");
                        oPTable.AddCell("Inicio - Fin");
                        oPTable.AddCell("Horas");
                        oPTable.AddCell(pExternalDesignation.oTeacher.name + " " + pExternalDesignation.oTeacher.lastName);
                        oPTable.AddCell(pExternalDesignation.position);
                        oPTable.AddCell(pExternalDesignation.location);
                        oPTable.AddCell(pExternalDesignation.initial_day.ToShortDateString() + " " + pExternalDesignation.final_day.ToShortDateString());
                        oPTable.AddCell(pExternalDesignation.hours.ToString());
                        pdfDoc.Add(oPTable);

                        PdfPTable oPTable2 = new PdfPTable(7);
                        oPTable2.TotalWidth    = 100;
                        oPTable2.SpacingAfter  = 30f;
                        oPTable2.SpacingBefore = 5f;
                        oPTable2.AddCell("Lunes");
                        oPTable2.AddCell("Martes");
                        oPTable2.AddCell("Miércoles");
                        oPTable2.AddCell("Jueves");
                        oPTable2.AddCell("Viernes");
                        oPTable2.AddCell("Sábado");
                        oPTable2.AddCell("Domingo");

                        Int32 count = 1;
                        while (count <= 7)
                        {
                            Boolean ind = false;

                            for (Int32 i = 0; i < pExternalDesignation.journeys.Count; i++)
                            {
                                if (pExternalDesignation.journeys[i].day.code == count)
                                {
                                    ind = true;
                                    oPTable2.AddCell(pExternalDesignation.journeys[i].start + " / " + pExternalDesignation.journeys[i].finish);
                                }
                            }

                            if (!ind)
                            {
                                oPTable2.AddCell("00:00" + " / " + "00:00");
                            }
                            count++;
                        }

                        pdfDoc.Add(oPTable2);
                    }
                }
                else
                {
                    PdfPTable oPTable = new PdfPTable(5);
                    oPTable.TotalWidth    = 100;
                    oPTable.SpacingBefore = 20f;
                    oPTable.SpacingAfter  = 30f;
                    oPTable.AddCell("Funcionario");
                    oPTable.AddCell("Cargo");
                    oPTable.AddCell("Lugar de Trabajo");
                    oPTable.AddCell("Inicio - Fin");
                    oPTable.AddCell("Horas");
                    PdfPCell cell = new PdfPCell(new text::Phrase("No existen nombramientos externos registrados."));
                    cell.Colspan             = 5;
                    cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                    oPTable.AddCell(cell);
                    pdfDoc.Add(oPTable);
                }


                pdfDoc.Close();

                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();
                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "attachment; filename=Nombramiento_Externo.pdf");
                Response.ContentType = "application/pdf";
                Response.Buffer      = true;
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(bytes);
                Response.End();
                Response.Close();
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }
        public MemoryStream GeneratePdfTemplate(ReturnInvToPurchasingViewModel viewModel, int offset)
        {
            //Declaring fonts.

            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, 9);
            var      bold_font   = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 9);

            //Creating page.

            Document     document = new Document(PageSize.A5.Rotate());
            MemoryStream stream   = new MemoryStream();

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

            writer.CloseStream = false;

            document.Open();

            PdfContentByte cb = writer.DirectContent;

            //Set Header
            #region SetHeader

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

            cb.SetFontAndSize(bf, 10);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "PT DAN LIRIS", 20, 385, 0);

            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Sukoharjo", 20, 370, 0);

            cb.SetFontAndSize(bf_bold, 14);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "BON Returns of Goods", 297, 360, 0);

            cb.SetFontAndSize(bf_bold, 9);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "FM.FP-GB-15-005 / R2", 480, 385, 0);

            cb.SetFontAndSize(bf, 9);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "KEPADA YTH. BAGIAN PURCHASE", 20, 335, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Telah Diretur Ke : " + viewModel.Supplier.Name, 20, 320, 0);

            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "No : " + viewModel.No, 480, 335, 0);

            cb.EndText();

            #endregion

            #region CreateTable
            PdfPTable table = new PdfPTable(5)
            {
                TotalWidth = 553f
            };

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

            var 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
            };

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

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

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

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

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

            //Add all items.
            int index = 1;
            foreach (var item in viewModel.ReturnInvToPurchasingDetails)
            {
                cell.Phrase = new Phrase(index.ToString(), normal_font);
                table.AddCell(cell);

                leftCell.Phrase = new Phrase(item.Product.Name, normal_font);
                table.AddCell(leftCell);

                rightCell.Phrase = new Phrase(string.Format("{0:n}", item.Quantity), normal_font);
                table.AddCell(rightCell);

                rightCell.Phrase = new Phrase(string.Format("{0:n}", item.NecessaryLength), normal_font);
                table.AddCell(rightCell);

                leftCell.Phrase = new Phrase(item.Description, normal_font);
                table.AddCell(leftCell);
                index++;
            }

            //Save tables.

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

            cb.SetFontAndSize(bf, 10);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Sukoharjo : " + DateTime.UtcNow.AddHours(offset).ToString("dd-MM-yyyy"), 460, 260, 0);
            //Set footer
            #region Footer

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

            //LEFT
            cb.SetFontAndSize(bf, 9);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Yang Menyerahkan,", 180, 120, 0);
            cb.SetFontAndSize(bf, 9);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "(..........................)", 180, 50, 0);
            cb.SetFontAndSize(bf, 9);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Bag. Warehouse Material", 180, 35, 0);


            //RIGHT
            cb.SetFontAndSize(bf, 9);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Yang Menerima,", 420, 120, 0);
            cb.SetFontAndSize(bf, 9);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "(..........................)", 420, 50, 0);
            cb.SetFontAndSize(bf, 9);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Bag. PURCHASE", 420, 35, 0);

            cb.EndText();

            #endregion

            document.Close();

            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
Exemplo n.º 31
0
        void BtnConfirmaClick(object sender, EventArgs e)
        {
            string natureza = cbxNaturezas.Text.Trim();

            if (natureza.Length == 0)
            {
                MessageBox.Show("Natureza", "Campo Obrigatório",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
                cbxNaturezas.Focus();
                return;
            }

            int mes = dtpInicial.Value.Month, ano = dtpInicial.Value.Year, n = 0;

            while ((ano < dtpFinal.Value.Year) || ((ano == dtpFinal.Value.Year) && (mes <= dtpFinal.Value.Month)))
            {
                n++;
                mes++;
                if (mes > 12)
                {
                    mes = 1;
                    ano++;
                }
            }
            if (n > 12)
            {
                MessageBox.Show("O período selecionado deve ser de no máximo 12 meses", "Intervalo",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
                cbxNaturezas.Focus();
                return;
            }

            n        = cbxNaturezas.SelectedIndex;
            natureza = cbxCodNaturezas.Items[n].ToString();
            string des_natureza = cbxNaturezas.Items[n].ToString();

            valores.Clear();
            datas.Clear();
            float max = 0;

            if (origem == 'p')
            {
                max = titulos_pagar.SomaPorVencimento(natureza, dtpInicial.Value, dtpFinal.Value, ref valores, ref datas);
            }
            else
            {
                max = titulos_receber.SomaPorVencimento(natureza, dtpInicial.Value, dtpFinal.Value, ref valores, ref datas);
            }

            FileStream fs     = new FileStream("tendencia.pdf", FileMode.Create);
            Document   doc    = new Document(PageSize.LETTER.Rotate());
            PdfWriter  writer = PdfWriter.GetInstance(doc, fs);

            doc.Open();
            PdfContentByte buf = writer.DirectContent;

            Graficos.Cabecalho(doc, "Tendência", des_natureza);
            Graficos.Barras(buf, valores, datas, 150, max);
            doc.Close();
            System.Diagnostics.Process.Start("explorer", "tendencia.pdf");
            Close();

            /*
             * float vlr=100;
             * while (vlr < max) vlr *= 2;
             * d = vlr / 10;
             * label12.Text = vlr.ToString("#,###,##0.00"); vlr-=d;
             * label11.Text = vlr.ToString("#,###,##0.00"); vlr-=d;
             * label10.Text = vlr.ToString("#,###,##0.00"); vlr-=d;
             * label9.Text = vlr.ToString("#,###,##0.00"); vlr-=d;
             * label8.Text = vlr.ToString("#,###,##0.00"); vlr-=d;
             * label7.Text = vlr.ToString("#,###,##0.00"); vlr-=d;
             * label6.Text = vlr.ToString("#,###,##0.00"); vlr-=d;
             * label5.Text = vlr.ToString("#,###,##0.00"); vlr-=d;
             * label4.Text = vlr.ToString("#,###,##0.00"); vlr-=d;
             * label3.Text = vlr.ToString("#,###,##0.00");
             * int i=0;
             * int x=115;
             * Pen pen = new Pen(Color.Black, 1);
             * foreach (string descricao in datas)
             * {
             *      int j = 0;
             *      string valor="";
             *      foreach (float v in valores)
             *      {
             *              valor = v.ToString("#,###,##0.00");
             *              if (j++ == i) break;
             *      }
             *      switch (i++)
             *      {
             *              case 0:
             *                      v1.Text = valor;
             *                      d1.Text = descricao;
             *                      v1.Visible = true;
             *                      c1.Visible = true;
             *                      d1.Visible = true;
             *                      c1.BackColor = Color.FromArgb(255, 255, 0, 0);
             *                      break;
             *              case 1:
             *                      v2.Text = valor;
             *                      d2.Text = descricao;
             *                      v2.Visible = true;
             *                      c2.Visible = true;
             *                      d2.Visible = true;
             *                      c2.BackColor = Color.FromArgb(255, 0, 255, 0);
             *                      break;
             *              case 2:
             *                      v3.Text = valor;
             *                      d3.Text = descricao;
             *                      v3.Visible = true;
             *                      c3.Visible = true;
             *                      d3.Visible = true;
             *                      c3.BackColor = Color.FromArgb(255, 0, 0, 255);
             *                      break;
             *              case 3:
             *                      v4.Text = valor;
             *                      d4.Text = descricao;
             *                      v4.Visible = true;
             *                      c4.Visible = true;
             *                      d4.Visible = true;
             *                      c4.BackColor = Color.FromArgb(255, 255, 255, 0);
             *                      break;
             *              case 4:
             *                      v5.Text = valor;
             *                      d5.Text = descricao;
             *                      v5.Visible = true;
             *                      c5.Visible = true;
             *                      d5.Visible = true;
             *                      c5.BackColor = Color.FromArgb(255, 0, 255, 255);
             *                      break;
             *              case 5:
             *                      v6.Text = valor;
             *                      d6.Text = descricao;
             *                      v6.Visible = true;
             *                      c6.Visible = true;
             *                      d6.Visible = true;
             *                      c6.BackColor = Color.FromArgb(255, 255, 0, 255);
             *                      break;
             *              case 6:
             *                      v7.Text = valor;
             *                      d7.Text = descricao;
             *                      v7.Visible = true;
             *                      c7.Visible = true;
             *                      d7.Visible = true;
             *                      c7.BackColor = Color.FromArgb(255, 255, 128, 0);
             *                      break;
             *              case 7:
             *                      v8.Text = valor;
             *                      d8.Text = descricao;
             *                      v8.Visible = true;
             *                      c8.Visible = true;
             *                      d8.Visible = true;
             *                      c8.BackColor = Color.FromArgb(255, 0, 255, 128);
             *                      break;
             *              case 8:
             *                      v9.Text = valor;
             *                      d9.Text = descricao;
             *                      v9.Visible = true;
             *                      c9.Visible = true;
             *                      d9.Visible = true;
             *                      c9.BackColor = Color.FromArgb(255, 128, 0, 255);
             *                      break;
             *              case 9:
             *                      v10.Text = valor;
             *                      d10.Text = descricao;
             *                      v10.Visible = true;
             *                      c10.Visible = true;
             *                      d10.Visible = true;
             *                      c10.BackColor = Color.FromArgb(255, 255, 128, 128);
             *                      break;
             *              case 10:
             *                      v11.Text = valor;
             *                      d11.Text = descricao;
             *                      v11.Visible = true;
             *                      c11.Visible = true;
             *                      d11.Visible = true;
             *                      c11.BackColor = Color.FromArgb(255, 128, 255, 128);
             *                      break;
             *              case 11:
             *                      v12.Text = valor;
             *                      d12.Text = descricao;
             *                      v12.Visible = true;
             *                      c12.Visible = true;
             *                      d12.Visible = true;
             *                      c12.BackColor = Color.FromArgb(255, 128, 128, 255);
             *                      break;
             *              case 12:
             *                      v13.Text = valor;
             *                      d13.Text = descricao;
             *                      v13.Visible = true;
             *                      c13.Visible = true;
             *                      d13.Visible = true;
             *                      c13.BackColor = Color.FromArgb(255, 128, 128, 0);
             *                      break;
             *      }
             *      x += 40;
             * }
             * pnlGrafico.Refresh();
             */
        }
 /** Creates a new event. This constructor will be used if you need to position fields with a Cell Event. */
 public FieldPositioningEvents(PdfWriter writer, PdfFormField field)
 {
     this.cellField   = field;
     this.fieldWriter = writer;
 }
Exemplo n.º 33
0
        private void btnPdf_Click(object sender, EventArgs e)
        {
            try
            {
                using (SaveFileDialog sfd = new SaveFileDialog()
                {
                    Filter = "PDF file|*.pdf", ValidateNames = true
                })
                {
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        using (ManagerContext db = new ManagerContext())
                        {
                            if (dgvSalesList.CurrentRow != null)
                            {
                                int selectedId = (int)dgvSalesList.CurrentRow.Cells[0].Value;
                                if (selectedId > 0)
                                {
                                    string    invoiceNo    = dgvSalesList.CurrentRow.Cells["Invoice"].Value.ToString();
                                    string    i            = "Invoice No: " + invoiceNo;
                                    string    outletName   = dgvSalesList.CurrentRow.Cells["Outlet"].Value.ToString();
                                    string    o            = "Outlet Name: " + outletName;
                                    string    customerName = dgvSalesList.CurrentRow.Cells["Customer"].Value.ToString();
                                    string    c            = "Customer :" + customerName;
                                    string    employeeName = dgvSalesList.CurrentRow.Cells["Employee"].Value.ToString();
                                    string    emp          = "Employee Name: " + employeeName;
                                    string    salesDate    = dgvSalesList.CurrentRow.Cells["Date"].Value.ToString();
                                    string    sDate        = "Sales Date: " + salesDate;
                                    string    total        = dgvSalesList.CurrentRow.Cells["TotalAmount"].Value.ToString();
                                    Document  pdfDocument  = new Document(iTextSharp.text.PageSize.A4, 20, 20, 42, 35);
                                    PdfWriter pdfwriter    = PdfWriter.GetInstance(pdfDocument, new FileStream(sfd.FileName, FileMode.Create));


                                    pdfDocument.Open();
                                    pdfDocument.NewPage();
                                    pdfDocument.AddAuthor("POS");
                                    pdfDocument.AddCreator("LanguageIntegratedDevelopmentTeam");
                                    pdfDocument.AddSubject("SalesReport");
                                    Paragraph heading = new Paragraph("Purchase Details");
                                    heading.Alignment    = Element.ALIGN_CENTER;
                                    heading.SpacingAfter = 18f;
                                    pdfDocument.Add(heading);

                                    Paragraph invoice = new Paragraph(i);
                                    invoice.Alignment    = Element.ALIGN_CENTER;
                                    invoice.SpacingAfter = 18f;
                                    pdfDocument.Add(invoice);

                                    Paragraph outlet = new Paragraph(o);
                                    outlet.Alignment    = Element.ALIGN_CENTER;
                                    outlet.SpacingAfter = 4f;
                                    pdfDocument.Add(outlet);

                                    Paragraph customer = new Paragraph(c);
                                    customer.Alignment    = Element.ALIGN_CENTER;
                                    customer.SpacingAfter = 5F;
                                    pdfDocument.Add(customer);

                                    Paragraph para2 = new Paragraph(emp);
                                    para2.Alignment    = Element.ALIGN_CENTER;
                                    para2.SpacingAfter = 5F;
                                    pdfDocument.Add(para2);
                                    Paragraph para3 = new Paragraph(sDate);
                                    para3.Alignment    = Element.ALIGN_CENTER;
                                    para3.SpacingAfter = 35F;
                                    pdfDocument.Add(para3);


                                    PdfPTable table = new PdfPTable(4);

                                    table.SpacingAfter = 30f;

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

                                    cell.Colspan             = 4;
                                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                    table.AddCell(cell);
                                    table.AddCell("Name");

                                    table.AddCell("Quantity");

                                    table.AddCell("Cost Price");

                                    table.AddCell("Total Price");


                                    foreach (ListViewItem item in itemListView.Items)
                                    {
                                        foreach (var itm in item.SubItems)
                                        {
                                            table.AddCell(((ListViewItem.ListViewSubItem)itm).Text);
                                        }
                                    }
                                    pdfDocument.Add(table);
                                    pdfDocument.Close();
                                    MessageBox.Show("Your PDF File Has Been Ready....!");
                                }
                            }
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 34
0
 /// <summary>
 /// Creates a new  TextField .
 /// will be included in the field allowing it to be used as a kid field.
 /// </summary>
 /// <param name="writer">the document  PdfWriter </param>
 /// <param name="box">the field location and dimensions</param>
 /// <param name="fieldName">the field name. If  null  only the widget keys</param>
 protected BaseField(PdfWriter writer, Rectangle box, string fieldName)
 {
     this.writer = writer;
     Box = box;
     this.fieldName = fieldName;
 }
Exemplo n.º 35
0
        public FileDocumento CreaIndiceDoc(DocsPaVO.areaConservazione.InfoEsibizione infoEs, DocsPaVO.areaConservazione.ItemsEsibizione[] items)
        {
            // Risultato da restituire
            FileDocumento document = null;

            // Stream in cui produrre il file PDF
            using (MemoryStream stream = new MemoryStream())
            {
                // Creazione del documento PDF
                Document pdfDocument = new Document(PageSize.A4, 10, 10, 10, 10);

                PdfWriter writer = PdfWriter.GetInstance(pdfDocument, stream);
                pdfDocument.Open();
                logger.Debug(stream.Length);

                // Lo stream non deve essere chiuso
                writer.CloseStream = false;
                pdfDocument.NewPage();


                pdfDocument.Add(new Paragraph("Indice dei documenti", FontFactory.GetFont(FontFactory.HELVETICA, 16, Color.BLACK)));

                //intestazione con dati istanza
                Font fontheader = FontFactory.GetFont(FontFactory.HELVETICA, 12, Color.BLACK);
                pdfDocument.Add(new Paragraph(string.Format("Istanza di Esibizione n. {0}", infoEs.SystemID), fontheader));
                pdfDocument.Add(new Paragraph(string.Format("Descrizione: {0}", infoEs.Descrizione), fontheader));
                if (!string.IsNullOrEmpty(infoEs.Note))
                {
                    pdfDocument.Add(new Paragraph(string.Format("Note: {0}", infoEs.Note), fontheader));
                }


                //tabella con documenti
                PdfPTable table = new PdfPTable(6);
                table.WidthPercentage = 100;
                //table.LockedWidth = true;
                //float[] widths = new float[] { 50f, 100f, 300f, 200f };
                float[] widths = new float[] { 70f, 100f, 80f, 220f, 120f, 50f };
                table.SetWidths(widths);
                table.SpacingAfter            = 20f;
                table.SpacingBefore           = 30f;
                table.DefaultCell.BorderWidth = 0;

                //header
                Font fontHeaderTable = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10, Color.BLACK);
                table.AddCell(this.addCell(new Phrase("Tipo", fontHeaderTable)));
                table.AddCell(this.addCell(new Phrase("ID/Segnatura", fontHeaderTable)));
                table.AddCell(this.addCell(new Phrase("Cod. Fasc.", fontHeaderTable)));
                table.AddCell(this.addCell(new Phrase("Oggetto", fontHeaderTable)));
                table.AddCell(this.addCell(new Phrase("Data creazione\n protocollazione", fontHeaderTable)));
                table.AddCell(this.addCell(new Phrase("Rapporto", fontHeaderTable)));

                foreach (DocsPaVO.areaConservazione.ItemsEsibizione itm in items)
                {
                    logger.Debug(itm.numProt_or_id);
                    logger.Debug(itm.relative_path);

                    string relativePathReport = Path.Combine(itm.ID_Conservazione, "rapporto_versamento.xml");
                    logger.DebugFormat("Path rapporto versmamento: {0}", relativePathReport);

                    //font per doc principale
                    //Font link = FontFactory.GetFont("Arial", 10, Font.UNDERLINE, new Color(0, 0, 255));
                    Font link = FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.UNDEFINED, new Color(0, 0, 255));
                    Font font = FontFactory.GetFont(FontFactory.HELVETICA, 10, Color.BLACK);

                    //font per allegato
                    Font linkall = FontFactory.GetFont(FontFactory.HELVETICA, 9, Font.UNDEFINED, new Color(0, 0, 255));
                    Font fontall = FontFactory.GetFont(FontFactory.HELVETICA, 9, Color.BLACK);

                    // hyperlink al documento
                    Anchor anchor = new Anchor(itm.numProt_or_id, link);
                    anchor.Reference = itm.relative_path;
                    Phrase phrase = new Phrase();
                    phrase.Add(anchor);

                    // link al rapporto di versamento
                    Anchor reportAnchor = new Anchor("vedi", link);
                    reportAnchor.Reference = relativePathReport;
                    Phrase reportPhrase = new Phrase();
                    reportPhrase.Add(reportAnchor);

                    //tipo (doc/all)
                    table.AddCell(this.addCell(new Phrase("Documento", font)));
                    // id/segnatura (con hyperlink)
                    table.AddCell(this.addCell(phrase));
                    // codice fascicolo
                    string codfasc = " ";
                    if (!string.IsNullOrEmpty(itm.CodFasc))
                    {
                        codfasc = itm.CodFasc;
                    }
                    table.AddCell(this.addCell(new Phrase(codfasc, font)));
                    // oggetto
                    table.AddCell(this.addCell(new Phrase(itm.desc_oggetto, font)));
                    // data creazione o protocollazione
                    table.AddCell(this.addCell(new Phrase(itm.data_prot_or_create, font)));
                    // rapporto di versamento
                    table.AddCell(this.addCell(reportPhrase));

                    //se ci sono allegati li accodo sotto il doc principale
                    int numAllegati = Convert.ToInt32(itm.numAllegati);
                    if (numAllegati > 0)
                    {
                        int i = 1;
                        foreach (string infoAll in itm.path_allegati)
                        {
                            string idAll   = infoAll.Split('§')[0];
                            string pathAll = infoAll.Split('§')[1];

                            //costruisco il link
                            Anchor anchorAll = new Anchor(idAll, linkall);
                            anchorAll.Reference = pathAll;
                            Phrase phraseAll = new Phrase();
                            phraseAll.Add(anchorAll);

                            // tipo
                            table.AddCell(this.addCell(new Phrase(string.Format("Allegato {0}", i), fontall)));
                            // id/segnatura
                            table.AddCell(this.addCell(phraseAll));
                            // cod fasc
                            table.AddCell(this.addCell(new Phrase(" ", fontall)));
                            // oggetto
                            table.AddCell(this.addCell(new Phrase(" ", fontall)));
                            // data creazione o protocollazione
                            table.AddCell(this.addCell(new Phrase(" ", fontall)));
                            // rapporto di versamento
                            table.AddCell(this.addCell(new Phrase(" ", fontall)));
                            i++;
                        }
                    }
                }
                pdfDocument.Add(table);

                pdfDocument.Close();

                document             = new FileDocumento();
                document.name        = String.Format("Indice.pdf");
                document.path        = String.Empty;
                document.fullName    = document.name;
                document.contentType = "application/pdf";
                document.content     = stream.GetBuffer();
                document.length      = Convert.ToInt32(stream.Length);

                logger.Debug(document.content.Length + " _ " + document.length);
            }

            return(document);
        }
        public ActionResult ExportPDF()
        {
            List <Product> list = ProductsList().ToList();

            #region declaration
            int          maxColumn = 5;
            PdfPTable    pdf       = new PdfPTable(maxColumn);
            MemoryStream memory    = new MemoryStream();
            #endregion
            #region
            Document document = new Document();
            document.SetPageSize(PageSize.A4);
            document.SetMargins(30f, 30f, 30f, 30f);
            pdf.WidthPercentage     = 100;
            pdf.HorizontalAlignment = Element.ALIGN_LEFT;
            Font font = FontFactory.GetFont("Arial", 8f, 1);
            PdfWriter.GetInstance(document, memory);
            document.Open();
            pdf.SetWidths(new float[] { 10f, 80f, 40f, 30f, 150f });
            #endregion
            #region Header
            font = FontFactory.GetFont("Tahoma", 11f, 1);
            PdfPCell cell = new PdfPCell(new Phrase("Products List", font));
            cell.Colspan             = maxColumn;
            cell.Border              = 0;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.BackgroundColor     = BaseColor.WHITE;
            cell.ExtraParagraphSpace = 0;
            pdf.AddCell(cell);
            pdf.CompleteRow();
            font                     = FontFactory.GetFont("Tahoma", 9f, 1);
            cell                     = new PdfPCell(new Phrase("", font));
            cell.Colspan             = maxColumn;
            cell.Border              = 0;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.BackgroundColor     = BaseColor.WHITE;
            cell.ExtraParagraphSpace = 2;
            pdf.AddCell(cell);
            pdf.CompleteRow();
            #endregion
            #region Body
            #region Table Header
            font = FontFactory.GetFont("Tahoma", 8f, 1);
            cell = new PdfPCell(new Phrase("No", font));
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            cell.BackgroundColor     = BaseColor.LIGHT_GRAY;
            pdf.AddCell(cell);
            cell = new PdfPCell(new Phrase("Name", font));
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            cell.BackgroundColor     = BaseColor.LIGHT_GRAY;
            pdf.AddCell(cell);
            cell = new PdfPCell(new Phrase("Price", font));
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            cell.BackgroundColor     = BaseColor.LIGHT_GRAY;
            pdf.AddCell(cell);
            cell = new PdfPCell(new Phrase("Stock", font));
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            cell.BackgroundColor     = BaseColor.LIGHT_GRAY;
            pdf.AddCell(cell);
            cell = new PdfPCell(new Phrase("Description", font));
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            cell.BackgroundColor     = BaseColor.LIGHT_GRAY;
            pdf.AddCell(cell);
            pdf.CompleteRow();
            #endregion
            #region Table Body
            font = FontFactory.GetFont("Tahoma", 8f, 0);
            int number = 1;
            foreach (var product in list)
            {
                cell = new PdfPCell(new Phrase(number++.ToString(), font));
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                cell.BackgroundColor     = BaseColor.WHITE;
                pdf.AddCell(cell);
                cell = new PdfPCell(new Phrase(product.Name, font));
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                cell.BackgroundColor     = BaseColor.WHITE;
                pdf.AddCell(cell);
                cell = new PdfPCell(new Phrase(product.Price.ToString(), font));
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                cell.BackgroundColor     = BaseColor.WHITE;
                pdf.AddCell(cell);
                cell = new PdfPCell(new Phrase(product.Stock.ToString(), font));
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                cell.BackgroundColor     = BaseColor.WHITE;
                pdf.AddCell(cell);
                cell = new PdfPCell(new Phrase(product.Description, font));
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                cell.BackgroundColor     = BaseColor.WHITE;
                pdf.AddCell(cell);
                pdf.CompleteRow();
            }
            #endregion
            #endregion
            pdf.HeaderRows = 2;
            document.Add(pdf);
            document.Close();
            byte[] file = memory.ToArray();
            //return File(file, "application/pdf");
            return(File(
                       fileContents: file,
                       contentType: "application/pdf",
                       fileDownloadName: "ProductsList.pdf"));
        }
Exemplo n.º 37
0
        private void listaDeInscriçõesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Eventos eventoSelecionado = (Eventos)listViewEventos.SelectedItems[0].Tag;

                saveFileDialog_Save.FileName    = "ListaInscricoes_" + eventoSelecionado.Descricao + ".pdf";
                saveFileDialog_Save.Filter      = "All files (*.*)|*.*";
                saveFileDialog_Save.FilterIndex = 0;

                if (saveFileDialog_Save.ShowDialog() == DialogResult.OK)
                {
                    Document doc = new Document(PageSize.A4);
                    doc.SetMargins(60, 60, 30, 30);

                    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(saveFileDialog_Save.FileName, FileMode.Create));

                    doc.Open();

                    //Font fontH1 = new Font(Currier, 16, Font.Bold);

                    // <---------------- Título ---------------->

                    Paragraph titulo = new Paragraph("Lista de Inscrições\n");
                    titulo.Alignment = Element.TITLE;


                    // <---------------- Informações sobre o Evento ---------------->

                    Paragraph evento   = new Paragraph("\n\nEvento: " + eventoSelecionado.Descricao);
                    Paragraph local    = new Paragraph("Local: " + eventoSelecionado.Local);
                    Paragraph data     = new Paragraph(string.Format("Data: {0:dd} de {0:MMMM} de {0:yyyy}", eventoSelecionado.DataHora));
                    Paragraph hora     = new Paragraph(string.Format("Hora: {0:HH:mm:ss}", eventoSelecionado.DataHora));
                    Paragraph limite   = new Paragraph("Limite de Participação: " + eventoSelecionado.LimiteParticipacao + " crianças");
                    Paragraph idadeInf = new Paragraph("Idade Mínima: " + eventoSelecionado.IdadeInferior + " anos");
                    Paragraph idadeSup = new Paragraph("Idade Máxima: " + eventoSelecionado.IdadeSuperior + " anos\n\n\n\n");

                    evento.Alignment   = Element.ALIGN_JUSTIFIED;
                    local.Alignment    = Element.ALIGN_JUSTIFIED;
                    data.Alignment     = Element.ALIGN_JUSTIFIED;
                    hora.Alignment     = Element.ALIGN_JUSTIFIED;
                    limite.Alignment   = Element.ALIGN_JUSTIFIED;
                    idadeInf.Alignment = Element.ALIGN_JUSTIFIED;
                    idadeSup.Alignment = Element.ALIGN_JUSTIFIED;


                    // <---------------- Tabela ---------------->

                    PdfPTable table = new PdfPTable(5);


                    Paragraph coluna1 = new Paragraph("Nome");
                    Paragraph coluna2 = new Paragraph("Idade");
                    Paragraph coluna3 = new Paragraph("Responsável");
                    Paragraph coluna4 = new Paragraph("Telefone");
                    Paragraph coluna5 = new Paragraph("Telemóvel");

                    coluna1.Alignment = Element.ALIGN_CENTER;
                    coluna2.Alignment = Element.ALIGN_CENTER;
                    coluna3.Alignment = Element.ALIGN_CENTER;
                    coluna4.Alignment = Element.ALIGN_CENTER;
                    coluna5.Alignment = Element.ALIGN_CENTER;


                    var cell1 = new PdfPCell();
                    var cell2 = new PdfPCell();
                    var cell3 = new PdfPCell();
                    var cell4 = new PdfPCell();
                    var cell5 = new PdfPCell();

                    cell1.AddElement(coluna1);
                    cell2.AddElement(coluna2);
                    cell3.AddElement(coluna3);
                    cell4.AddElement(coluna4);
                    cell5.AddElement(coluna5);

                    table.AddCell(cell1);
                    table.AddCell(cell2);
                    table.AddCell(cell3);
                    table.AddCell(cell4);
                    table.AddCell(cell5);

                    foreach (Inscricoes i in eventoSelecionado.Inscricoes.ToList <Inscricoes>())
                    {
                        Phrase nome = new Phrase(i.Filhos.Nome);
                        var    cell = new PdfPCell(nome);
                        table.AddCell(cell);

                        Phrase idade = new Phrase(Convert.ToString(i.Filhos.Idade()));
                        cell = new PdfPCell(idade);
                        table.AddCell(cell);

                        Phrase responsavel = new Phrase(i.Filhos.Clientes.Nome);
                        cell = new PdfPCell(responsavel);
                        table.AddCell(cell);

                        Phrase telefone = new Phrase(i.Filhos.Telefone);
                        cell = new PdfPCell(telefone);
                        table.AddCell(cell);

                        Phrase telemovel = new Phrase(i.Filhos.Telemovel);
                        cell = new PdfPCell(telemovel);
                        table.AddCell(cell);
                    }


                    // <---------------- Adicionar os dados todos ao documento ---------------->

                    doc.Add(titulo);
                    doc.Add(evento);
                    doc.Add(local);
                    doc.Add(data);
                    doc.Add(hora);
                    doc.Add(limite);
                    doc.Add(idadeInf);
                    doc.Add(idadeSup);
                    doc.Add(table);

                    doc.Close();

                    MessageBox.Show("Lista de Inscrições guardada com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch
            {
                MessageBox.Show("Selecione o evento primeiro!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Exemplo n.º 38
0
        public static void CreateHistoriaClinica(PacientList filiationData, List <ServiceComponentList> serviceComponent, organizationDto infoEmpresaPropietaria, List <PersonMedicalHistoryList> listMedicoPersonales, List <FamilyMedicalAntecedentsList> listaPatologicosFamiliares, List <NoxiousHabitsList> listaHabitoNocivos, List <DiagnosticRepositoryList> ListDiagnosticRepository, List <MedicationList> ListMedicamentos, string Recomendaciones, string filePDF)
        {
            //
            // step 1: creation of a document-object
            Document document = new Document();

            //Document document = new Document(new Rectangle(500f, 300f), 10, 10, 10, 10);
            //document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
            document.SetPageSize(iTextSharp.text.PageSize.A4);
            //Document document = new Document(PageSize.A4, 0, 0, 20, 20);
            //
            try
            {
                // step 2: we create a writer that listens to the document
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filePDF, FileMode.Create));
                //
                //create an instance of your PDFpage class. This is the class we generated above.
                pdfPage page = new pdfPage();
                //set the PageEvent of the pdfWriter instance to the instance of our PDFPage class
                writer.PageEvent = page;

                // step 3: we open the document
                document.Open();
                // step 4: we Add content to the document
                // we define some fonts

                #region Fonts

                Font fontTitle1               = FontFactory.GetFont(FontFactory.HELVETICA, 18, iTextSharp.text.Font.NORMAL, new BaseColor(System.Drawing.Color.Black));
                Font fontTitle2               = FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.NORMAL, new BaseColor(System.Drawing.Color.Black));
                Font fontTitleTable           = FontFactory.GetFont(FontFactory.HELVETICA, 10, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.White));
                Font fontTitleTableNegro      = FontFactory.GetFont(FontFactory.HELVETICA, 10, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black));
                Font fontSubTitle             = FontFactory.GetFont(FontFactory.HELVETICA, 9, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.White));
                Font fontSubTitleNegroNegrita = FontFactory.GetFont(FontFactory.HELVETICA, 9, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black));

                Font fontColumnValue = FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.NORMAL, new BaseColor(System.Drawing.Color.Black));


                #endregion

                #region Logo

                Image     logo      = HandlingItextSharp.GetImage(infoEmpresaPropietaria.b_Image, 30F);
                PdfPTable headerTbl = new PdfPTable(1);
                headerTbl.TotalWidth = writer.PageSize.Width;
                PdfPCell cellLogo = new PdfPCell(logo);

                cellLogo.VerticalAlignment   = Element.ALIGN_TOP;
                cellLogo.HorizontalAlignment = Element.ALIGN_CENTER;

                cellLogo.Border = PdfPCell.NO_BORDER;
                headerTbl.AddCell(cellLogo);
                document.Add(headerTbl);

                #endregion

                #region Title

                Paragraph cTitle = new Paragraph("HISTORIA CLÍNICA", fontTitle2);
                //Paragraph cTitle2 = new Paragraph(customerOrganizationName, fontTitle2);
                cTitle.Alignment = Element.ALIGN_CENTER;
                //cTitle2.Alignment = Element.ALIGN_CENTER;

                document.Add(cTitle);
                //document.Add(cTitle2);

                #endregion

                #region Declaration Tables
                var             subTitleBackGroundColor = new BaseColor(System.Drawing.Color.White);
                string          include       = string.Empty;
                List <PdfPCell> cells         = null;
                float[]         columnWidths  = null;
                string[]        columnValues  = null;
                string[]        columnHeaders = null;

                //PdfPTable header1 = new PdfPTable(2);
                //header1.HorizontalAlignment = Element.ALIGN_CENTER;
                //header1.WidthPercentage = 100;
                ////header1.TotalWidth = 500;
                ////header1.LockedWidth = true;    // Esto funciona con TotalWidth
                //float[] widths = new float[] { 150f, 200f};
                //header1.SetWidths(widths);


                //Rectangle rec = document.PageSize;
                PdfPTable header2 = new PdfPTable(6);
                header2.HorizontalAlignment = Element.ALIGN_CENTER;
                header2.WidthPercentage     = 100;
                //header1.TotalWidth = 500;
                //header1.LockedWidth = true;    // Esto funciona con TotalWidth
                float[] widths1 = new float[] { 16.6f, 18.6f, 16.6f, 16.6f, 16.6f, 16.6f };
                header2.SetWidths(widths1);
                //header2.SetWidthPercentage(widths1, rec);

                PdfPTable companyData = new PdfPTable(6);
                companyData.HorizontalAlignment = Element.ALIGN_CENTER;
                companyData.WidthPercentage     = 100;
                //header1.TotalWidth = 500;
                //header1.LockedWidth = true;    // Esto funciona con TotalWidth
                float[] widthscolumnsCompanyData = new float[] { 16.6f, 16.6f, 16.6f, 16.6f, 16.6f, 16.6f };
                companyData.SetWidths(widthscolumnsCompanyData);

                PdfPTable filiationWorker = new PdfPTable(4);

                PdfPTable table = null;

                PdfPCell cell = null;

                #endregion

                // Salto de linea
                document.Add(new Paragraph("\r\n"));


                #region Datos Empresa Propietaria

                cells = new List <PdfPCell>()
                {
                    new PdfPCell(new Phrase("Dirección: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(infoEmpresaPropietaria.v_Address, fontColumnValue)),
                    new PdfPCell(new Phrase("Teléfono: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(infoEmpresaPropietaria.v_PhoneNumber, fontColumnValue)),
                    new PdfPCell(new Phrase("Email: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(infoEmpresaPropietaria.v_Mail, fontColumnValue)),
                };

                columnWidths = new float[] { 17f, 17f, 17f, 17f, 17f, 17f };

                filiationWorker = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, PdfPCell.NO_BORDER, null, fontTitleTableNegro, null);

                document.Add(filiationWorker);

                #endregion

                // Salto de linea
                document.Add(new Paragraph("\r\n"));
                #region Cabecera del Reporte

                var xFuncionesVitales = serviceComponent.Find(p => p.v_ComponentId == Sigesoft.Common.Constants.FUNCIONES_VITALES_ID);
                var FrecCar           = "";
                var FrecResp          = "";
                var PResionArterial   = "";
                var PResionDias       = "";
                var Temperatura       = "";
                if (xFuncionesVitales != null || xFuncionesVitales.ServiceComponentFields.Count == 0)
                {
                    PResionArterial = xFuncionesVitales.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FUNCIONES_VITALES_PAS_ID) == null ? "" : xFuncionesVitales.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FUNCIONES_VITALES_PAS_ID).v_Value1;
                    PResionDias     = xFuncionesVitales.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FUNCIONES_VITALES_PAD_ID) == null ? "" : xFuncionesVitales.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FUNCIONES_VITALES_PAD_ID).v_Value1;

                    FrecCar  = xFuncionesVitales.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FUNCIONES_VITALES_FREC_CARDIACA_ID) == null ? "" : xFuncionesVitales.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FUNCIONES_VITALES_FREC_CARDIACA_ID).v_Value1;
                    FrecResp = xFuncionesVitales.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FUNCIONES_VITALES_FREC_RESPIRATORIA_ID) == null ? "" : xFuncionesVitales.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FUNCIONES_VITALES_FREC_RESPIRATORIA_ID).v_Value1;

                    Temperatura = xFuncionesVitales.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FUNCIONES_VITALES_TEMPERATURA_ID) == null ? "" : xFuncionesVitales.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FUNCIONES_VITALES_TEMPERATURA_ID).v_Value1;
                }
                cells = new List <PdfPCell>()
                {
                    new PdfPCell(new Phrase("Código: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(filiationData.v_IdService, fontColumnValue)),
                    new PdfPCell(new Phrase("Fecha: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(filiationData.d_ServiceDate.Value.ToShortDateString(), fontColumnValue)),
                    new PdfPCell(new Phrase("Emp. Seguro: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(filiationData.v_DocNumber, fontColumnValue))
                    {
                        Colspan = 3
                    },


                    new PdfPCell(new Phrase("Paciente: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(filiationData.v_FirstName + " " + filiationData.v_FirstLastName + " " + filiationData.v_SecondLastName, fontColumnValue))
                    {
                        Colspan = 7
                    },
                    new PdfPCell(new Phrase("Dirección: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(filiationData.v_AdressLocation, fontColumnValue))
                    {
                        Colspan = 7
                    },

                    new PdfPCell(new Phrase("Sexo: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(filiationData.v_SexTypeName, fontColumnValue)),
                    new PdfPCell(new Phrase("Teléfono: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(filiationData.v_TelephoneNumber, fontColumnValue)),
                    new PdfPCell(new Phrase("DNI: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(filiationData.v_DocNumber, fontColumnValue)),
                    new PdfPCell(new Phrase("Edad: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(filiationData.i_Age.ToString() + "años", fontColumnValue)),


                    new PdfPCell(new Phrase("F.C: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(FrecCar + " (Lat/min)", fontColumnValue)),
                    new PdfPCell(new Phrase("F.R: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(FrecResp + " (Resp/min)", fontColumnValue)),
                    new PdfPCell(new Phrase("P.A: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(PResionArterial + " (mmHg)", fontColumnValue)),
                    new PdfPCell(new Phrase("T.: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(Temperatura + " C°", fontColumnValue)),


                    new PdfPCell(new Phrase("T. Emfermedad: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(filiationData.TiempoEnfermedad, fontColumnValue)),
                    new PdfPCell(new Phrase("Inicio: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(filiationData.InicioEnfermedad, fontColumnValue)),
                    new PdfPCell(new Phrase("curso: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(filiationData.CursoEnfermedad, fontColumnValue))
                    {
                        Colspan = 3
                    },

                    new PdfPCell(new Phrase("Signos y Síntomas: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(filiationData.v_MainSymptom, fontColumnValue))
                    {
                        Colspan = 7
                    },
                    new PdfPCell(new Phrase("Enfermedad Actual(Motivo): ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(filiationData.v_Story, fontColumnValue))
                    {
                        Colspan = 7
                    },
                };

                columnWidths = new float[] { 12.5f, 12.5f, 12.5f, 12.5f, 12.5f, 12.5f, 12.5f, 12.5f };

                filiationWorker = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, "", fontTitleTableNegro, null);

                document.Add(filiationWorker);

                #endregion


                #region  Antecedentes Personales
                cells = new List <PdfPCell>();

                if (listMedicoPersonales != null && listMedicoPersonales.Count > 0)
                {
                    foreach (var item in listMedicoPersonales)
                    {
                        //Columna DX
                        cell = new PdfPCell(new Phrase(item.v_DiseasesName, fontColumnValue))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        };
                        cells.Add(cell);

                        //Columna FECHA INICIO
                        cell = new PdfPCell(new Phrase(item.d_StartDate.Value.ToShortDateString(), fontColumnValue))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        };
                        cells.Add(cell);

                        //Columna DETALLE
                        cell = new PdfPCell(new Phrase(item.v_TreatmentSite, fontColumnValue))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        };
                        cells.Add(cell);
                    }

                    columnWidths = new float[] { 33f, 33f, 33f };
                }
                else
                {
                    cells.Add(new PdfPCell(new Phrase("No se han registrado datos.", fontColumnValue))
                    {
                        Colspan = 8, HorizontalAlignment = PdfPCell.ALIGN_LEFT
                    });
                    columnWidths = new float[] { 33f, 33f, 33f };
                }

                columnHeaders = new string[] { "Diagnóstico", "Fecha Inicio", "Detalle" };

                table = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, "ANTECEDENTES PERSONALES", fontTitleTableNegro, columnHeaders);

                document.Add(table);

                #endregion

                #region  Antecedentes Familiares
                cells = new List <PdfPCell>();

                if (listaPatologicosFamiliares != null && listaPatologicosFamiliares.Count > 0)
                {
                    foreach (var item in listaPatologicosFamiliares)
                    {
                        //Columna Grupo Familiar
                        cell = new PdfPCell(new Phrase(item.v_TypeFamilyName, fontColumnValue))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        };
                        cells.Add(cell);

                        //Columna DX
                        cell = new PdfPCell(new Phrase(item.v_DiseaseName, fontColumnValue))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        };
                        cells.Add(cell);


                        //Columna DETALLE
                        cell = new PdfPCell(new Phrase(item.v_Comment, fontColumnValue))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        };
                        cells.Add(cell);
                    }
                    columnWidths = new float[] { 33f, 33f, 33f };
                }

                else
                {
                    cells.Add(new PdfPCell(new Phrase("No se han registrado datos.", fontColumnValue))
                    {
                        Colspan = 8, HorizontalAlignment = PdfPCell.ALIGN_LEFT
                    });
                    columnWidths = new float[] { 33f, 33f, 33f };
                }

                columnHeaders = new string[] { "Grupo Familiar", "Diagnostico", "Detalle" };

                table = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, "ANTECEDENTES FAMILIARES", fontTitleTableNegro, columnHeaders);

                document.Add(table);

                #endregion

                #region  Antecedentes Habitos Noscivos
                cells = new List <PdfPCell>();

                if (listaHabitoNocivos != null && listaHabitoNocivos.Count > 0)
                {
                    foreach (var item in listaHabitoNocivos)
                    {
                        //Columna Hábito
                        cell = new PdfPCell(new Phrase(item.v_NoxiousHabitsName, fontColumnValue))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        };
                        cells.Add(cell);

                        //Columna Frecuencia
                        cell = new PdfPCell(new Phrase(item.v_FrecuenciaHabito, fontColumnValue))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        };
                        cells.Add(cell);


                        //Columna Comentario
                        cell = new PdfPCell(new Phrase(item.v_Comment, fontColumnValue))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        };
                        cells.Add(cell);
                    }
                    columnWidths = new float[] { 33f, 33f, 33f };
                }

                else
                {
                    cells.Add(new PdfPCell(new Phrase("No se han registrado datos.", fontColumnValue))
                    {
                        Colspan = 8, HorizontalAlignment = PdfPCell.ALIGN_LEFT
                    });
                    columnWidths = new float[] { 33f, 33f, 33f };
                }

                columnHeaders = new string[] { "Hábito", "Frecuencia", "Comentartio" };

                table = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, "HÁBITOS NOSCIVOS", fontTitleTableNegro, columnHeaders);

                document.Add(table);

                #endregion


                var    xExamenFisico     = serviceComponent.Find(p => p.v_ComponentId == Sigesoft.Common.Constants.EXAMEN_FISICO_ID);
                string ValorExamenFisico = "";
                if (xExamenFisico != null)
                {
                    ValorExamenFisico = xExamenFisico.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.EXAMEN_FISICO_HALLAZGOS_ID).v_Value1;
                }
                else
                {
                    ValorExamenFisico = "";
                }

                cells = new List <PdfPCell>()
                {
                    new PdfPCell(new Phrase("Examen Físico: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(ValorExamenFisico, fontColumnValue)),
                };

                columnWidths = new float[] { 12.5f, 88.5f };

                filiationWorker = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, null, fontTitleTableNegro, null);

                document.Add(filiationWorker);

                #region  Diagnósticos
                cells = new List <PdfPCell>();

                if (ListDiagnosticRepository != null && ListDiagnosticRepository.Count > 0)
                {
                    foreach (var item in ListDiagnosticRepository)
                    {
                        //Columna DX
                        cell = new PdfPCell(new Phrase(item.v_DiseasesName, fontColumnValue))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        };
                        cells.Add(cell);

                        //Columna XIE10
                        cell = new PdfPCell(new Phrase(item.v_Cie10, fontColumnValue))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        };
                        cells.Add(cell);
                    }
                    columnWidths = new float[] { 66f, 33f };
                }

                else
                {
                    cells.Add(new PdfPCell(new Phrase("No se han registrado datos.", fontColumnValue))
                    {
                        Colspan = 8, HorizontalAlignment = PdfPCell.ALIGN_LEFT
                    });
                    columnWidths = new float[] { 66f, 33f };
                }

                columnHeaders = new string[] { "Diagnósticos", "CIE10" };

                table = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, "DIAGNÓSTICOS", fontTitleTableNegro, columnHeaders);

                document.Add(table);

                #endregion

                #region Resultados

                cells = new List <PdfPCell>()
                {
                    new PdfPCell(new Phrase("Resultados: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(filiationData.v_ExaAuxResult, fontColumnValue)),
                };

                columnWidths = new float[] { 12.5f, 88.5f };

                filiationWorker = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, null, fontTitleTableNegro, null);

                document.Add(filiationWorker);

                #endregion


                #region  Medicación
                cells = new List <PdfPCell>();

                if (ListMedicamentos != null && ListMedicamentos.Count > 0)
                {
                    foreach (var item in ListMedicamentos)
                    {
                        cell = new PdfPCell(new Phrase(item.v_GenericName, fontColumnValue))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        };
                        cells.Add(cell);


                        cell = new PdfPCell(new Phrase(item.v_PresentationName, fontColumnValue))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        };
                        cells.Add(cell);


                        cell = new PdfPCell(new Phrase(item.v_Doses, fontColumnValue))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        };
                        cells.Add(cell);


                        cell = new PdfPCell(new Phrase(item.v_ViaName, fontColumnValue))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                        };
                        cells.Add(cell);
                    }

                    columnWidths = new float[] { 25f, 25f, 25f, 25f };
                }
                else
                {
                    cells.Add(new PdfPCell(new Phrase("No se han registrado datos.", fontColumnValue))
                    {
                        Colspan = 8, HorizontalAlignment = PdfPCell.ALIGN_LEFT
                    });
                    columnWidths = new float[] { 25f, 25f, 25f, 25f };
                }

                columnHeaders = new string[] { "Fármaco", "Presentación", "Dosis", "Vía" };

                table = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, "MEDICACIÓN Y RECETA", fontTitleTableNegro, columnHeaders);

                document.Add(table);

                #endregion

                #region Reomendaciones

                cells = new List <PdfPCell>()
                {
                    new PdfPCell(new Phrase("Recomendaciones: ", fontColumnValue))
                    {
                        HorizontalAlignment = Element.ALIGN_RIGHT
                    }, new PdfPCell(new Phrase(Recomendaciones, fontColumnValue)),
                };

                columnWidths = new float[] { 20f, 80f };

                filiationWorker = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, null, fontTitleTableNegro, null);

                document.Add(filiationWorker);

                #endregion


                #region Firma


                #region Creando celdas de tipo Imagen y validando nulls

                // Firma del trabajador ***************************************************
                PdfPCell cellFirmaTrabajador = null;

                if (filiationData.FirmaTrabajador != null)
                {
                    cellFirmaTrabajador = new PdfPCell(HandlingItextSharp.GetImage(filiationData.FirmaTrabajador, 40F));
                }
                else
                {
                    cellFirmaTrabajador = new PdfPCell(new Phrase("Sin Firma Trabajador", fontColumnValue));
                }

                // Huella del trabajador **************************************************
                PdfPCell cellHuellaTrabajador = null;

                if (filiationData.HuellaTrabajador != null)
                {
                    cellHuellaTrabajador = new PdfPCell(HandlingItextSharp.GetImage(filiationData.HuellaTrabajador, 40F));
                }
                else
                {
                    cellHuellaTrabajador = new PdfPCell(new Phrase("Sin Huella", fontColumnValue));
                }

                // Firma del doctor Auditor **************************************************

                PdfPCell cellFirma = null;

                if (filiationData.FirmaMedico != null)
                {
                    cellFirma = new PdfPCell(HandlingItextSharp.GetImage(filiationData.FirmaMedico, 50F));
                }
                else
                {
                    cellFirma = new PdfPCell(new Phrase("Sin Firma", fontColumnValue));
                }

                #endregion

                #region Crear tablas en duro (para la Firma y huella del trabajador)

                cells = new List <PdfPCell>();

                cellFirmaTrabajador.HorizontalAlignment = Element.ALIGN_CENTER;
                cellFirmaTrabajador.VerticalAlignment   = Element.ALIGN_MIDDLE;
                cellFirmaTrabajador.FixedHeight         = 80F;
                cells.Add(cellFirmaTrabajador);
                cells.Add(new PdfPCell(new Phrase("Firma del Examinado", fontColumnValue))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                columnWidths = new float[] { 100f };

                var tableFirmaTrabajador = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, "", fontTitleTable);

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

                cells = new List <PdfPCell>();

                cellHuellaTrabajador.HorizontalAlignment = Element.ALIGN_CENTER;
                cellHuellaTrabajador.VerticalAlignment   = Element.ALIGN_MIDDLE;
                cellHuellaTrabajador.FixedHeight         = 80F;
                cells.Add(cellHuellaTrabajador);
                cells.Add(new PdfPCell(new Phrase("Huella del Examinado", fontColumnValue))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                });

                columnWidths = new float[] { 100f };

                var tableHuellaTrabajador = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, "", fontTitleTable);

                #endregion

                cells = new List <PdfPCell>();

                // 1 celda vacia
                cells.Add(new PdfPCell(tableFirmaTrabajador));

                // 1 celda vacia
                cells.Add(new PdfPCell(tableHuellaTrabajador));

                // 2 celda
                cell = new PdfPCell(new Phrase("Firma y Sello Médico", fontColumnValue))
                {
                    Rowspan = 2
                };
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                cells.Add(cell);

                // 3 celda (Imagen)
                cellFirma.HorizontalAlignment = Element.ALIGN_CENTER;
                cellFirma.VerticalAlignment   = Element.ALIGN_MIDDLE;
                cellFirma.FixedHeight         = 80F;
                cells.Add(cellFirma);

                cells.Add(new PdfPCell(new Phrase("Con la cual declara que la información declarada es veraz", fontColumnValue))
                {
                    Colspan = 2, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                cells.Add(new PdfPCell(new Phrase("", fontColumnValue))
                {
                    Colspan = 2
                });

                columnWidths = new float[] { 25f, 25f, 20f, 30F };
                table        = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, " ", fontTitleTable);

                document.Add(table);

                #endregion

                // step 5: we close the document
                document.Close();
                writer.Close();
                writer.Dispose();
                //RunFile(filePDF);
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 39
0
 public override void OnCloseDocument(PdfWriter writer, Document document)
 {
     base.OnCloseDocument(writer, document);
 }
Exemplo n.º 40
0
 public override void OnStartPage(PdfWriter writer, Document document)
 {
     base.OnStartPage(writer, document);
 }
Exemplo n.º 41
0
        public override void ExecuteResult(ControllerContext context)
        {
            var Response = context.HttpContext.Response;

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "filename=foo.pdf");

            dt = Util.Now;

            doc = new Document(PageSize.LETTER.Rotate(), 36, 36, 64, 64);
            var w = PdfWriter.GetInstance(doc, Response.OutputStream);

            var i = (from m in DbUtil.Db.Meetings
                     where m.MeetingId == mtgid
                     select new
            {
                m.Organization.OrganizationName,
                m.Organization.LeaderName,
                m.MeetingDate
            }).SingleOrDefault();

            w.PageEvent = new HeadFoot
            {
                HeaderText = "Guests/Absents Report: {0} - {1} {2:g}".Fmt(
                    i.OrganizationName, i.LeaderName, i.MeetingDate),
                FooterText = "Guests/Absents Report"
            };
            doc.Open();

            var q = VisitsAbsents(mtgid.Value);

            if (!mtgid.HasValue || i == null || q.Count() == 0)
            {
                doc.Add(new Paragraph("no data"));
            }
            else
            {
                var mt = new PdfPTable(1);
                mt.SetNoPadding();
                mt.HeaderRows = 1;

                float[] widths = new float[] { 4f, 6f, 7f, 2.6f, 2f, 3f };
                var     t      = new PdfPTable(widths);
                t.DefaultCell.Border            = PdfPCell.NO_BORDER;
                t.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_TOP;
                t.DefaultCell.SetLeading(2.0f, 1f);
                t.WidthPercentage = 100;

                t.AddHeader("Name", boldfont);
                t.AddHeader("Address", boldfont);
                t.AddHeader("Phone/Email", boldfont);
                t.AddHeader("Last Att.", boldfont);
                t.AddHeader("Birthday", boldfont);
                t.AddHeader("Guest/Member", boldfont);
                mt.AddCell(t);

                var  color = BaseColor.BLACK;
                bool?v     = null;
                foreach (var p in q)
                {
                    if (color == BaseColor.WHITE)
                    {
                        color = new GrayColor(240);
                    }
                    else
                    {
                        color = BaseColor.WHITE;
                    }

                    t = new PdfPTable(widths);
                    t.SetNoBorder();
                    t.DefaultCell.VerticalAlignment = Element.ALIGN_TOP;
                    t.DefaultCell.BackgroundColor   = color;

                    if (v != p.visitor)
                    {
                        t.Add("             ------ {0} ------".Fmt(p.visitor == true ? "Guests" : "Absentees"), 6, bigboldfont);
                    }
                    v = p.visitor;

                    t.Add(p.Name, font);

                    var ph = new Paragraph();
                    ph.AddLine(p.Address, font);
                    ph.AddLine(p.Address2, font);
                    ph.AddLine(p.CSZ, font);
                    t.AddCell(ph);

                    ph = new Paragraph();
                    ph.AddLine(p.HomePhone.FmtFone("H"), font);
                    ph.AddLine(p.CellPhone.FmtFone("C"), font);
                    ph.AddLine(p.Email, font);
                    t.AddCell(ph);

                    t.Add(p.LastAttend.FormatDate(), font);
                    t.Add(p.Birthday, font);
                    t.Add(p.Status, font);
                    t.CompleteRow();

                    if (!p.Status.StartsWith("Visit"))
                    {
                        t.Add("", font);
                        t.Add("{0}           {1:n1}{2}"
                              .Fmt(p.AttendStr, p.AttendPct, p.AttendPct.HasValue ? "%" : ""), 5, monofont);
                    }

                    mt.AddCell(t);
                }
                doc.Add(mt);
            }
            doc.Close();
        }
Exemplo n.º 42
0
        private String imprimirTicket()
        {
            MessageBox.Show("Total a pagar " + Math.Round(total, 2));

            //Crear Tabla iTextSharp  desde una tabla de datos (datagridView)
            PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount);

            //padding
            pdfTable.DefaultCell.Padding = 3;

            //ancho que va a ocupar la tabla en el pdf
            pdfTable.WidthPercentage = 80;

            //alineación
            pdfTable.HorizontalAlignment = Element.ALIGN_CENTER;

            //borde de las tablas
            pdfTable.DefaultCell.BorderWidth = 1;
            //Añadir fila de cabecera
            foreach (DataGridViewColumn column in dataGridView1.Columns)
            {
                PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
                cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
                pdfTable.AddCell(cell);
            }

            //añadir filas
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    try
                    {
                        pdfTable.AddCell(cell.Value.ToString());
                    }
                    catch { }
                }
            }
            pdfTable.AddCell(DateTime.Now.ToString("MM-dd-yy"));
            pdfTable.AddCell(lbNombre.Text);

            //Exportar a pdf (ruta por defect
            string folderPath = "C:\\ticket\\";

            //si no existe el directoria se crea
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            string nombreTicket = DateTime.Now.ToString("MM-dd-yy_HH-mm-ss") + ".pdf";

            folderPath += nombreTicket;
            using (FileStream stream = new FileStream(folderPath, FileMode.Create))
            {
                Document pdfDoc = new Document(PageSize.A6, 10f, 10f, 10f, 0f);
                PdfWriter.GetInstance(pdfDoc, stream);
                pdfDoc.Open();
                pdfDoc.Add(pdfTable);

                pdfDoc.Close();
                stream.Close();
            }
            Process pc = new Process();

            pc.StartInfo.FileName = folderPath;
            pc.Start();
            dataGridView1.Rows.Add("Total:", 0);
            return(folderPath);
        }
Exemplo n.º 43
0
        static void Main(string[] args)
        {
            Console.WriteLine("Creating PDF...\n");

            string filename = "some.pdf";
            string filepath = Path.Combine(
                Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location),
                filename
                );

            try // creating PDF
            {
                // --- font settings

                // normal font
                string normal_font = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
                    "verdana.ttf"
                    );
                FontFactory.Register(normal_font);
                BaseFont baseFont_normal = BaseFont.CreateFont(
                    normal_font,
                    BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED
                    );
                Font font_main = new Font(baseFont_normal, 10, Font.NORMAL);

                // bold font
                string bold_font = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
                    "verdanab.ttf"
                    );
                FontFactory.Register(bold_font);
                BaseFont baseFont_bold = BaseFont.CreateFont(
                    bold_font,
                    BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED
                    );
                Font font_bold = new Font(baseFont_bold, 10, Font.NORMAL);

                // italic font
                string italic_font = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
                    "verdanai.ttf"
                    );
                FontFactory.Register(italic_font);
                BaseFont baseFont_italic = BaseFont.CreateFont(
                    italic_font,
                    BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED
                    );
                Font font_italic = new Font(baseFont_italic, 10, Font.NORMAL);

                // header font
                string header_font = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
                    "verdanab.ttf"
                    );
                FontFactory.Register(header_font);
                BaseFont baseFont_header = BaseFont.CreateFont(
                    bold_font,
                    BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED
                    );
                Font font_header = new Font(baseFont_header, 16, Font.NORMAL);

                List <string> name_awarded = new List <string>()
                {
                    "Junkrat", "Mercy", "Symmetra"
                };
                List <string> name_reported = new List <string>()
                {
                    "Widowmaker", "Sombra"
                };

                using (FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.None))
                    using (Document doc = new Document(PageSize.A4, 80, 80, 70, 70))
                        using (PdfWriter writer = PdfWriter.GetInstance(doc, fs))
                        {
                            writer.ViewerPreferences = PdfWriter.HideMenubar;
                            doc.Open();

                            // --- meta information

                            doc.AddTitle("Attack on Numbani");
                            doc.AddSubject("Match results");
                            doc.AddKeywords("pdf, example");
                            doc.AddCreator("Overwatch");
                            doc.AddAuthor("Athena");

                            // --- document contents

                            doc.Add(createAlignedParagraph("Overwatch", font_header, Element.ALIGN_CENTER));

                            doc.Add(new Paragraph(" "));
                            doc.Add(new Paragraph(" "));
                            doc.Add(createAlignedParagraph("Resolution #3426", font_main, Element.ALIGN_RIGHT));
                            doc.Add(createAlignedParagraph(
                                        string.Format(
                                            "from {0}",
                                            DateTime.Today.ToShortDateString()
                                            ),
                                        font_main, Element.ALIGN_RIGHT));

                            doc.Add(new Paragraph(" "));
                            doc.Add(new Paragraph(" "));
                            doc.Add(new Paragraph("Regarding last match results.", font_bold));
                            doc.Add(new Paragraph(" "));

                            if (name_awarded.Count != 0)
                            {
                                doc.Add(new Paragraph("For the extradionary performance", font_main));
                                doc.Add(new Paragraph(" "));
                                for (int i = 0; i < name_awarded.Count; i++)
                                {
                                    Paragraph li = new Paragraph(
                                        string.Format(
                                            "{0}. {1}",
                                            (i + 1).ToString(),
                                            name_awarded[i]
                                            ),
                                        font_main
                                        );
                                    li.IndentationLeft = 30;
                                    doc.Add(li);
                                }
                                doc.Add(new Paragraph(" "));
                                doc.Add(new Paragraph("are awarded with gold medals.", font_main));
                                if (name_reported.Count != 0)
                                {
                                    doc.Add(new Paragraph(" "));
                                }
                            }

                            if (name_reported.Count != 0)
                            {
                                doc.Add(new Paragraph("For the lack of teamplay and stupidity in general", font_main));
                                doc.Add(new Paragraph(" "));
                                for (int i = 0; i < name_reported.Count; i++)
                                {
                                    Paragraph li = new Paragraph(
                                        string.Format(
                                            "{0}. {1}",
                                            (i + 1).ToString(),
                                            name_reported[i]
                                            ),
                                        font_main
                                        );
                                    li.IndentationLeft = 30;
                                    doc.Add(li);
                                }
                                doc.Add(new Paragraph(" "));
                                doc.Add(new Paragraph("are reported for being such noobs.", font_main));
                            }

                            if (name_awarded.Count == 0 && name_reported.Count == 0)
                            {
                                doc.Add(new Paragraph("Just a regular match, nothing special.", font_main));
                                doc.Add(new Paragraph("[eats banana]", font_italic));
                            }

                            doc.Add(new Paragraph(" "));
                            // "glue" that allows to have two differently aligned phrases in one paragraph
                            Chunk     glue = new Chunk(new VerticalPositionMark());
                            Paragraph p    = new Paragraph(new Phrase("The head of Overwatch\n", font_bold));
                            p.Add(new Phrase("mighty monkey with Tesla Cannon", font_bold));
                            p.Add(new Chunk(glue));
                            p.Add(new Phrase("Winston", font_bold));
                            doc.Add(p);

                            #region Table as an alternative to "glue"
                            //var table = new PdfPTable(3);
                            //table.SpacingBefore = 35;
                            //PdfPCell cell = null;
                            //cell = new PdfPCell(new Phrase("The head of Overwatch", font_bold));
                            //cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            //cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                            //cell.Colspan = 2;
                            //table.AddCell(cell);
                            //cell = new PdfPCell(new Phrase("Winston", font_bold));
                            //cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            //cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                            //cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                            //cell.Rowspan = 2;
                            //table.AddCell(cell);
                            //cell = new PdfPCell(new Phrase("mighty monkey with Tesla Cannon", font_bold));
                            //cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            //cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                            //cell.Colspan = 2;
                            //table.AddCell(cell);
                            //table.WidthPercentage = 90;
                            //table.HorizontalAlignment = Element.ALIGN_LEFT;
                            //doc.Add(table);
                            #endregion

                            doc.Close();
                        }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Something went wrong. {0}", ex.Message));
                Console.Write("Press any key to exit");
                Console.ReadKey();
            }

            Console.WriteLine(string.Format("File \"{0}\" has been successfully created\n", filepath));
            Console.Write("Press any key to exit");
            Console.ReadKey();
        }
Exemplo n.º 44
0
    protected override void GenerateDocument(Document doc, DocumentType docType, string addSheet,PdfWriter writer)
    {
        PdfPTable table = new PdfPTable(2);
        table.WidthPercentage = 100;
        table.DefaultCell.Colspan = 2;
        table.DefaultCell.Border = Rectangle.NO_BORDER;

        table.AddCell(new Phrase(deptNameShort, FontFactory.GetFont("Arial Black", 30, Font.BOLD, new Color(60, 87, 167))));
        table.AddCell(new Phrase(deptNameLong, FontFactory.GetFont("Arial", 20, Font.BOLD, new Color(86, 137, 113))));

        table.DefaultCell.PaddingLeft = 40f;
        Paragraph paragraph = new Paragraph();
        paragraph.Add(new Chunk("COSHH Risk Assessment     ", FontFactory.GetFont("Arial Black", 20, Font.BOLD)));
        paragraph.Add(new Chunk("Assessment No: " + docName, boldFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.PaddingLeft = 0.0f;
        /**************SUBSTANCE INFORMATION***********************/
        table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
        table.DefaultCell.BackgroundColor = Color.BLACK;
        table.AddCell(new Phrase("SUBSTANCE INFORMATION", normalFontSmallWhite));

        //Reset DefaultCell
        table.DefaultCell.BackgroundColor = Color.WHITE;
        table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
        table.DefaultCell.Colspan = 1;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading() + GetNextSectionText(), boldFontSmall));
        table.AddCell(paragraph);

        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading() + GetNextSectionText(), boldFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Colspan = 2;
        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading() + GetNextSectionText(), boldFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.NO_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionText(), normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        PdfPTable nestedTable = new PdfPTable(new float[] { 70f, 30f });
        nestedTable.WidthPercentage = 100;
        nestedTable.DefaultCell.Border = Rectangle.NO_BORDER;

        nestedTable.AddCell(paragraph);
        nestedTable.AddCell(CreateSectionDetail());
        table.AddCell(nestedTable);

        table.DefaultCell.Border = Rectangle.NO_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading() , boldFontSmall));
        paragraph.Add(new Chunk(GetNextSectionText(), FontFactory.GetFont("Arial", 10, Font.BOLD, new Color(67, 75, 160))));
        table.AddCell(paragraph);

        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        paragraph.Add(new Chunk(GetNextSectionText(),normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        //paragraph.Add(new Chunk(GetNextSectionHeading(), normalFontSmall));
        table.AddCell(paragraph);

        nestedTable = CreateSectionDetail();
        nestedTable.SpacingAfter = 10f;
        table.AddCell(nestedTable);

        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.NO_BORDER;
        table.AddCell(CreateSectionDetail());

        /*********USE OF SUBSTANCE*************/

        table.DefaultCell.Border = Rectangle.NO_BORDER;
        table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
        table.DefaultCell.BackgroundColor = Color.BLACK;
        table.AddCell(new Phrase("USE OF SUBSTANCE", normalFontSmallWhite));

        //Reset DefaultCell
        table.DefaultCell.BackgroundColor = Color.WHITE;
        table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;

        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading() + " ", boldFontSmall));
        paragraph.Add(new Chunk(GetNextSectionText(), normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading() + " " , boldFontSmall));
        paragraph.Add(new Chunk(GetNextSectionText(), normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading() + " ", boldFontSmall));
        paragraph.Add(new Chunk(GetNextSectionText(), normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading() + " " + GetNextSectionText(), boldFontSmall));
        table.AddCell(paragraph);

        /*********CONTROL MEASURES************/
        table.DefaultCell.Border = Rectangle.NO_BORDER;
        table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
        table.DefaultCell.BackgroundColor = Color.BLACK;
        table.AddCell(new Phrase("CONTROL MEASURES", normalFontSmallWhite));

        //Reset DefaultCell
        table.DefaultCell.BackgroundColor = Color.WHITE;
        table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;

        nestedTable = new PdfPTable(new float[] { 60f, 40f });
        nestedTable.DefaultCell.Border = Rectangle.NO_BORDER;
        //table.AddCell(CreateInlineSectionDetail());
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading() + " ", boldFontSmall));
        nestedTable.AddCell(paragraph);
        nestedTable.AddCell(CreateSectionDetail());
        table.AddCell(nestedTable);

        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading() + " ", boldFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.NO_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionText(), normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.NO_BORDER;
        table.AddCell(CreateSectionDetail());

        table.DefaultCell.Colspan = 2;
        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        paragraph.Add(new Chunk(GetNextSectionText(), normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Colspan = 1;
        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        table.AddCell(paragraph);
        table.AddCell(CreateSectionDetail());

        table.DefaultCell.Border = Rectangle.NO_BORDER;
        table.DefaultCell.Colspan = 2;
        table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
        table.DefaultCell.BackgroundColor = Color.BLACK;
        table.AddCell(new Phrase("OTHER PRECAUTIONS AND EMERGENCY PROCEDURES", normalFontSmallWhite));

        //Reset DefaultCell
        table.DefaultCell.BackgroundColor = Color.WHITE;
        table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;

        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        paragraph.Add(new Chunk(GetNextSectionText(), normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk("First aid: ", boldFontSmall));
        paragraph.Add(new Chunk("What actions should be taken if the substance is:", normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Colspan = 1;
        table.DefaultCell.PaddingLeft = 5f;
        table.DefaultCell.FixedHeight = 50f;
        table.DefaultCell.Border = Rectangle.NO_BORDER;
        table.DefaultCell.Border = Rectangle.RIGHT_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        paragraph.Add(new Chunk(GetNextSectionText(), normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.NO_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        paragraph.Add(new Chunk(GetNextSectionText(), normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.NO_BORDER;
        table.DefaultCell.Border = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        paragraph.Add(new Chunk(GetNextSectionText(), normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.NO_BORDER;
        table.DefaultCell.Border = Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        paragraph.Add(new Chunk(GetNextSectionText(), normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Colspan = 2;
        table.DefaultCell.FixedHeight = 0.0f;
        table.DefaultCell.Border = Rectangle.NO_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        paragraph.Add(new Chunk(GetNextSectionText(), normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        table.DefaultCell.PaddingLeft = 0.0f;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        paragraph.Add(new Chunk(GetNextSectionText(), normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        paragraph.Add(new Chunk(GetNextSectionText(), normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        paragraph.Add(new Chunk(GetNextSectionText(), normalFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        nestedTable = new PdfPTable(new float[] { 60f, 40f });
        nestedTable.DefaultCell.Border = Rectangle.NO_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        string healthText = GetNextSectionText();
        paragraph.Add(new Chunk(GetNextSectionHeading(), normalFontSmall));
        nestedTable.AddCell(paragraph);
        nestedTable.AddCell(CreateSectionDetail());
        table.AddCell(nestedTable);

        table.DefaultCell.Border = Rectangle.NO_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(healthText, normalFontSmall));
        table.AddCell(paragraph);

        /*****************ASSESSMENT OF RISK***********************/

        table.DefaultCell.Colspan = 2;
        table.DefaultCell.Border = Rectangle.NO_BORDER;
        table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
        table.DefaultCell.BackgroundColor = Color.BLACK;
        table.AddCell(new Phrase("ASSESSMENT OF RISK", normalFontSmallWhite));

        //Reset DefaultCell
        table.DefaultCell.BackgroundColor = Color.WHITE;
        table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;

        table.DefaultCell.Border = Rectangle.NO_BORDER;
        nestedTable = new PdfPTable(new float[] { 60f,40f });
        nestedTable.DefaultCell.Border = Rectangle.NO_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        nestedTable.AddCell(paragraph);
        nestedTable.AddCell(CreateSectionDetail());
        table.AddCell(nestedTable);

        table.DefaultCell.Border = Rectangle.TOP_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk("If these controls are not in place or additional controls are required, state action to be taken.", boldFontSmall));
        table.AddCell(paragraph);

        table.DefaultCell.Border = Rectangle.NO_BORDER;
        paragraph = new Paragraph();
        paragraph.Add(new Chunk("Note - ", boldFontSmall));
        paragraph.Add(new Chunk("COSHH substances must NOT be used if adequate control measures are not in place.", normalFontSmall));
        table.AddCell(paragraph);

        nestedTable = new PdfPTable(new float[] { 80f, 20f });
        nestedTable.WidthPercentage = 100;
        nestedTable.AddCell(new Phrase(GetNextSectionHeading(), boldFontSmall));
        nestedTable.AddCell(new Phrase("Date for completion", boldFontSmall));
        nestedTable.AddCell(new Phrase(GetNextSectionText(), normalFontSmall));
        nestedTable.AddCell(new Phrase(""));
        table.AddCell(nestedTable);

        table.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
        table.DefaultCell.BorderWidthBottom = 2;
        table.DefaultCell.FixedHeight = 20f;
        nestedTable = new PdfPTable(2);
        paragraph = new Paragraph();
        paragraph.Add(new Chunk(GetNextSectionHeading(), boldFontSmall));
        nestedTable.AddCell(paragraph);
        nestedTable.AddCell(CreateSectionDetail());
        table.AddCell(nestedTable);

        table.DefaultCell.FixedHeight = 0.0f;
        table.DefaultCell.Border = Rectangle.NO_BORDER;
        nestedTable = new PdfPTable(new float[] { 40f, 40f, 20f });
        nestedTable.WidthPercentage = 100;
        nestedTable.AddCell(new Phrase("Assessor(s) name: " + assessorName, boldFontSmall));
        nestedTable.AddCell(new Phrase("Assessor(s) signature:", boldFontSmall));
        nestedTable.AddCell(new Phrase("Date:", boldFontSmall));

        nestedTable.DefaultCell.Colspan = 3;
        nestedTable.AddCell(new Phrase("The Supervisors should sign below to show that the assessment is a correct and reasonable reflection of the hazards and of the control measures and actions required.", normalFontSmall));

        nestedTable.DefaultCell.Colspan = 1;
        nestedTable.DefaultCell.FixedHeight = 30f;
        nestedTable.AddCell(new Phrase("Supervisors name:", boldFontSmall));
        nestedTable.AddCell(new Phrase("Supervisors signature:", boldFontSmall));
        nestedTable.AddCell(new Phrase("Date:", boldFontSmall));

        nestedTable.DefaultCell.FixedHeight = 40f;
        nestedTable.AddCell(new Phrase("Remedial actions complete: (Date)", boldFontSmall));
        nestedTable.AddCell(new Phrase("Supervisors signature:", boldFontSmall));
        nestedTable.AddCell(new Phrase("Reviewed on: (Date)", boldFontSmall));
        table.AddCell(nestedTable);

        table.DefaultCell.HorizontalAlignment = Rectangle.ALIGN_CENTER;
        table.AddCell(new Phrase("A copy of the product safety data sheet must be attached this assessment.", boldFontSmall));
        doc.Add(table);
    }
Exemplo n.º 45
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 firstRow = new PdfPTable(1);
            var cell1    = new PdfPCell(new Phrase("VISHWA VIDYA SAMSTHE'S", FontFactory.GetFont("Arial", 12)));
            var cell2    = new PdfPCell(new Phrase("P.B. COLLEGE OF PHARMACY", FontFactory.GetFont("Arial", 15)));
            var cell3    = new PdfPCell(new Phrase("Hyderabad Road, Station Area YADGIR - 585 202", FontFactory.GetFont("Arial", 12)));

            cell1.HorizontalAlignment = 1;
            cell2.HorizontalAlignment = 1;
            cell3.HorizontalAlignment = 1;
            cell1.BorderWidth         = 0;
            cell2.BorderWidth         = 0;
            cell3.BorderWidth         = 0;

            firstRow.AddCell(cell1);
            firstRow.AddCell(cell2);
            firstRow.AddCell(cell3);
            var secondRow = new PdfPTable(3);
            var cell11    = new PdfPCell(new Phrase("No.", FontFactory.GetFont("Arial", 12)));
            var cell12    = new PdfPCell(new Phrase("Receipt", FontFactory.GetFont("Arial", 12)));
            var cell13    = new PdfPCell(new Phrase("Date :  " + student.DateOfAdmission.FormatDate("/"), FontFactory.GetFont("Arial", 12)));

            cell11.BorderWidth = 0;
            cell12.BorderWidth = 0;
            cell13.BorderWidth = 0;
            var cell21 = new PdfPCell(new Phrase("Name :  " + student.Name, FontFactory.GetFont("Arial", 12)));

            cell21.Colspan = 3;
            var cell22 = new PdfPCell(new Phrase("S/o :  " + student.FatherName, FontFactory.GetFont("Arial", 12)));

            cell22.Colspan     = 3;
            cell21.BorderWidth = 0;
            cell22.BorderWidth = 0;

            var cell31 = new PdfPCell(new Phrase("Class : " + student.Year + " year, " + student.BranchName, FontFactory.GetFont("Arial", 12)));
            var cell32 = new PdfPCell(new Phrase("Roll No.", FontFactory.GetFont("Arial", 12)));
            var cell33 = new PdfPCell(new Phrase("Adm. No.", FontFactory.GetFont("Arial", 12)));

            cell31.BorderWidth = 0;
            cell32.BorderWidth = 0;
            cell33.BorderWidth = 0;
            secondRow.AddCell(cell11);
            secondRow.AddCell(cell12);
            secondRow.AddCell(cell13);
            secondRow.AddCell(cell21);
            secondRow.AddCell(cell22);
            secondRow.AddCell(cell31);
            secondRow.AddCell(cell32);
            secondRow.AddCell(cell33);
            var firstrow = new PdfPCell(firstRow);

            firstrow.BorderWidth = 0;
            var secondrow = new PdfPCell(secondRow);

            secondrow.BorderWidth = 0;
            var header = new PdfPTable(1);

            header.AddCell(firstrow);
            header.AddCell(secondrow);
            var mainheader = new PdfPTable(1);

            mainheader.AddCell(header);
            document.Add(mainheader);
            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 = "Laboratary Fee", Amount = student.LabFee
                }, new FeeStructure {
                    Description = "Home Exam Fee", Amount = student.HomeExamFee
                },
                new FeeStructure {
                    Description = "Library Fee", Amount = student.LibraryFee
                }, new FeeStructure {
                    Description = "Sports & Games Fee", Amount = student.SportsFee
                },
                new FeeStructure {
                    Description = "Medical Fee", Amount = student.MedicalFee
                }, new FeeStructure {
                    Description = "Caution Fee", Amount = student.CautionDepositFee
                },
                new FeeStructure {
                    Description = "Mis Fee", Amount = student.MisFee
                }, new FeeStructure {
                    Description = "Laboratary Deposit", Amount = student.LabDepositFee
                },
                new FeeStructure {
                    Description = "Identity Cards Fee", Amount = student.IdentityCardFee
                }, new FeeStructure {
                    Description = "Student Aid Fund", Amount = student.StudentAidFundFee
                },
                new FeeStructure {
                    Description = "Magazine Fee", Amount = student.MagazineFee
                }, new FeeStructure {
                    Description = "Journal Fee", Amount = student.JournalFee
                },
                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 footer = new PdfPTable(1);

            var c4 = new PdfPCell(new Phrase("Received Rs : " + changeToWords(student.PaidFee.ToString(), false) + " only", FontFactory.GetFont("Arial", 12)));

            footer.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            var c6 = new PdfPCell(new Phrase("Clerk / Accountant", FontFactory.GetFont("Arial", 12)));

            c6.HorizontalAlignment = 2;
            footer.AddCell(c4);
            footer.AddCell(c6);
            document.Add(footer);
            document.Close();
            ms.Close();
            return(ms);
        }
Exemplo n.º 46
0
 /**
  * Creates a new instance of PushbuttonField
  * @param writer the document <CODE>PdfWriter</CODE>
  * @param box the field location and dimensions
  * @param fieldName the field name. If <CODE>null</CODE> only the widget keys
  * will be included in the field allowing it to be used as a kid field.
  */
 public PushbuttonField(PdfWriter writer, Rectangle box, String fieldName) : base(writer, box, fieldName)
 {
 }
Exemplo n.º 47
0
    private bool generatePdf()
    {
        bool      result          = false;
        int       orderid         = Convert.ToInt32(Encrypt_Decrypt.Decrypt(Session["sOrderID"].ToString().Trim(), true));
        DataTable dtPOProductList = orderObj.OrderProductList(orderid);
        string    path            = string.Empty;

        for (int count = 0; count < dtPOProductList.Rows.Count; count++)
        {
            string strpdf = string.Empty;
            strpdf += "<table align='center' style='font-family: Verdana; width: 885px ;font-size:9px'><tr bgcolor='#ffcc66'>";
            strpdf += "<td colspan='4'><table align='center' style='font-family: Verdana;'><tr><td align='center' style='font-size: 12px;'>Mudar India Exports</td></tr><tr>";
            strpdf += "<td colspan='4' align='center' style='font-size: 10px;'>6-1-744, Kovur Nagar,ANANTAPUR - 515 004,Andhra Pradesh,India</td></tr></table></td></tr><tr>";
            strpdf += "<td colspan='4'></td></tr><tr>";
            strpdf += "<td colspan='2' align='left'><table width='40%'align='left' border='1'><tr><td>COA No</td><td>02657</td></tr></table></td><td colspan='2' align='center'><table width='55%'align='right' border='1'><tr><td>Date</td><td align='center'>" + lblTodayDate.Text + "</td></tr></table></td></tr><tr>";
            strpdf += "<td colspan='4'></td></tr><tr>";
            strpdf += "<td align='center' colspan='4'>Certificate of Analysis</td></tr><tr>";
            strpdf += "<td colspan='4'></td></tr><tr>";
            strpdf += "<td colspan='4'><table  width='100%' border='1'><tr align='center'>";
            strpdf += "<td rowspan='4'>" + lblConsigneeAddress.Text + "</td>";
            strpdf += "<td>Buyers PO</td><td>" + lblPO.Text + "</td></tr><tr align='center'>";
            strpdf += "<td>PO Date<br /></td><td>" + lblPODate.Text + "</td></tr><tr align='center'>";
            strpdf += "<td>Invoice No #</td><td>" + lblInvoice.Text + "</td></tr><tr align='center'>";
            strpdf += "<td>Invoice Date</td><td>" + lblInvoiceDate.Text + "</td></tr></table></td></tr><tr>";
            strpdf += "<td colspan='4'></td></tr>";
            strpdf += "<td colspan='4'><table width='100%' border='1'><tr align='center'>";
            strpdf += "<td colspan='2'>Name of the Product </td><td colspan='2'>" + dtPOProductList.Rows[count]["ProductName"].ToString() + "</td></tr><tr align='center'>";
            strpdf += "<td>Lot Qty in KG</td><td>" + dtPOProductList.Rows[count]["Quantity"].ToString() + "</td><td>Year of Production</td><td>" + (dlCOAdetails.Items[count].FindControl("txtYearProduction") as TextBox).Text + "</td></tr><tr align='center'>";
            strpdf += "<td>Lot No</td><td>" + dtPOProductList.Rows[count]["Blending_BatchID"].ToString() + "</td><td>Drums Ref</td><td>" + dtPOProductList.Rows[count]["TotalDrums"].ToString() + "</td></tr><tr></table></td></tr><tr align='center'>";
            strpdf += "<td colspan='4'></td></tr><tr>";
            strpdf += "<td colspan='4'><table width='100%' border='1'><tr>";
            strpdf += "<td rowspan='2' align='center'>Parameter</td><td rowspan='2'align='center'>Analysis Value </td><td colspan='2'align='center'>Standard Specification</td><td rowspan='2'align='center'>Testing Method<br />Adopted</td></tr><tr>";
            strpdf += "<td align='center'>Low</td><td align='center'>High</td></tr><tr align='center'>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtApperance") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtApperanceAnalysis") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtApperanceLow") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtApperanceHigh") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtApperanceTMA") as TextBox).Text + "</td></tr><tr align='center'>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtOdor") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtOdorAnalysis") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtOdorLow") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtOdorHigh") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtOdorTMA") as TextBox).Text + "</td></tr><tr align='center'>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtLMenthol") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtLMentholAnalysis") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtLMentholLow") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtLMentholHigh") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtLMentholTMA") as TextBox).Text + "</td></tr><tr align='center'>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtMenthafuron") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtMenthafuronAnalysis") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtMenthafuronLow") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtMenthafuronHigh") as TextBox).Text + "</td>";
            strpdf += "<td>" + (dlCOAdetails.Items[count].FindControl("txtMenthafuronTMA") as TextBox).Text + "</td></tr></table></td></tr><tr>";
            strpdf += "<td colspan='4'></td></tr></table>";

            Document document = new Document();
            try
            {
                string Pdf_path = string.Empty;
                Pdf_path = mu.createfolder(orderid.ToString(), MudarUser.OrderPDF) ? WebConfigurationManager.AppSettings["orderpdf"].ToString() + orderid.ToString() + "/COA-PP(" + orderid.ToString() + "_" + dtPOProductList.Rows[count]["ProductID"].ToString() + ").pdf" : WebConfigurationManager.AppSettings["orderpdf"].ToString() + "/COA-PP(" + orderid.ToString() + "_" + dtPOProductList.Rows[count]["ProductID"].ToString() + ").pdf";
                path    += Pdf_path;
                if (count < dtPOProductList.Rows.Count - 1)
                {
                    path += "$";
                }
                //writer - have our own path!!!
                PdfWriter.GetInstance(document, new FileStream(Server.MapPath(Pdf_path), FileMode.Create));
                document.Open();



                //Here is where your HTML source goes................
                String htmlText = strpdf.ToString();


                //make an arraylist ....with STRINGREADER since its no IO reading file...

                List <IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(htmlText), null);

                ////add the collection to the document
                //for (int k = 0; k < htmlarraylist.Count; k++)
                //{
                //    document.Add((IElement)htmlarraylist[k]);
                //}

                //document.Add(new Paragraph("And the same with indentation...."));

                // or add the collection to an paragraph
                // if you add it to an existing non emtpy paragraph it will insert it from
                //the point youwrite -
                Paragraph mypara = new Paragraph();//make an emtphy paragraph as "holder"
                mypara.IndentationLeft = 36;
                mypara.InsertRange(0, htmlarraylist);
                document.Add(mypara);
                document.Close();
                //orderObj.OrderDetails_UPD(orderid, Pdf_path, "bhanu");
                result = true;
            }
            catch (Exception exx)
            {
                Response.Write("<br>____________________________________<br>");
                Response.Write("<br>Error: " + exx + "<br>");
                Response.Write("<br>StackTrace: " + exx.StackTrace + "<br>");
                Response.Write("<br>strPDFDocument: " + strpdf.ToString() + "<br>");
                Response.Write("<br>strSelectUserListBuilder: " + strpdf.ToString() + "<br>");

                //Console.Error.WriteLine(exx.StackTrace);
                //Console.Error.WriteLine(exx.StackTrace);
                result = false;
            }
            finally
            {
                //document.Close();
            }
        }
        result = reportObj.OrderReportsPathInsertandUpdate(Convert.ToInt32(orderid), Convert.ToInt32(Session["BranchOrderID_S"].ToString()), path, "Bhanu", string.Empty, rtypeObj.PP);
        return(result);
    }
Exemplo n.º 48
0
    public override void OnCloseDocument(PdfWriter writer, Document document)
    {
        base.OnCloseDocument(writer, document);

        template.BeginText();
        template.SetFontAndSize(bf, 8);
        template.SetTextMatrix(0, 0);
        template.ShowText("" + (writer.PageNumber - 1));
        template.EndText();
    }
Exemplo n.º 49
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            Style boldStyle     = new Style().SetTextAlignment(TextAlignment.CENTER).SetFontSize(8).SetBold();
            Style headerMusculo = new Style().SetTextAlignment(TextAlignment.LEFT).SetBold();

            Style styleDatos = new Style().SetFontSize(7);



            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "Pdf Files|*.pdf";
            saveFileDialog1.Title  = "Save an Image File";
            saveFileDialog1.ShowDialog();

            string Imagenpath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            Image imgEjercicio = new Image(ImageDataFactory.Create(Imagenpath + "\\Resources\\Ejercicios_Fotos\\Dominadas.jpg"));
            Image logo         = new Image(ImageDataFactory.Create(Imagenpath + "\\Resources\\Icons\\OnixLogo.png"));

            string path = saveFileDialog1.FileName;


            PdfWriter   pw          = new PdfWriter(path);
            PdfDocument pdfDocument = new PdfDocument(pw);

            pdfDocument.AddEventHandler(PdfDocumentEvent.START_PAGE, new HeaderEventHandler(logo));
            Document doc = new Document(pdfDocument, PageSize.A4);

            doc.SetMargins(55, 30, 15, 30);

            Table table = new Table(1).UseAllAvailableWidth(); //USAR TODO EL ANCHO DE LA HOJA

            table.AddCell(new Cell().Add(new Paragraph("Nom:").SetFontSize(8))
                          .SetTextAlignment(TextAlignment.LEFT)
                          .SetBold().SetBorder(Border.NO_BORDER));

            doc.Add(table);


            Table _table = new Table(7).UseAllAvailableWidth();


            Cell _cell = new Cell().Add(new Paragraph("Lorena Vicente").AddStyle(styleDatos)).SetMaxHeight(20f).SetVerticalAlignment(VerticalAlignment.MIDDLE);

            _table.AddCell(_cell);

            _cell = new Cell().Add(new Paragraph("Data inici rutina")).SetBorder(Border.NO_BORDER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
            _table.AddCell(_cell.AddStyle(boldStyle));

            _cell = new Cell().Add(new Paragraph(FechaTB.Text)).AddStyle(styleDatos).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
            _table.AddCell(_cell);

            _cell = new Cell().Add(new Paragraph("Data final rutina")).SetBorder(Border.NO_BORDER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
            _table.AddCell(_cell.AddStyle(boldStyle));

            _cell = new Cell().Add(new Paragraph(FechaFinTB.Text)).AddStyle(styleDatos).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
            _table.AddCell(_cell);

            _cell = new Cell().Add(new Paragraph("Rutina")).SetBorder(Border.NO_BORDER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
            _table.AddCell(_cell.AddStyle(boldStyle));

            _cell = new Cell().Add(new Paragraph("003").AddStyle(styleDatos).SetTextAlignment(TextAlignment.RIGHT)).SetVerticalAlignment(VerticalAlignment.MIDDLE);
            _table.AddCell(_cell);
            doc.Add(_table);


            Table tablaPrincipal = new Table(4);

            tablaPrincipal.SetHorizontalBorderSpacing(0);
            tablaPrincipal.SetVerticalBorderSpacing(0);


            for (int i = 0; i < 24; i++)
            {
                Table ejercicio = new Table(6);

                Cell celda = new Cell(1, 6).SetBorder(Border.NO_BORDER).SetBackgroundColor(ColorConstants.LIGHT_GRAY);
                ejercicio.AddCell(celda.Add(new Paragraph("DELTOIDES").SetFontSize(7).SetTextAlignment(TextAlignment.LEFT)));


                celda = new Cell(1, 6).SetHorizontalAlignment(iText.Layout.Properties.HorizontalAlignment.LEFT)
                        .Add(new Paragraph("Sentadilla_bulgara_con_mancuernas")
                             .SetFontSize(7)).SetBorder(Border.NO_BORDER);
                ejercicio.AddCell(celda);


                celda = new Cell().Add(new Paragraph("Dia").SetFontSize(7.5f)).SetBorder(Border.NO_BORDER);
                ejercicio.AddCell(celda.AddStyle(headerMusculo));

                celda = new Cell().Add(new Paragraph("A")).SetBorder(new SolidBorder(0.5f));
                ejercicio.AddCell(celda.AddStyle(styleDatos));

                celda = new Cell().Add(new Paragraph("Ser")).SetBorder(Border.NO_BORDER);
                ejercicio.AddCell(celda.AddStyle(headerMusculo).SetFontSize(7.5f));

                celda = new Cell().Add(new Paragraph("2")).SetBorder(new SolidBorder(0.5f));
                ejercicio.AddCell(celda.AddStyle(styleDatos));

                celda = new Cell().Add(new Paragraph("Rep")).SetBorder(Border.NO_BORDER);
                ejercicio.AddCell(celda.AddStyle(headerMusculo).SetFontSize(7.5f));

                celda = new Cell().Add(new Paragraph("3")).SetBorder(new SolidBorder(0.5f));
                ejercicio.AddCell(celda.AddStyle(styleDatos));

                celda = new Cell(1, 2).Add(new Paragraph("Descans").SetFontSize(8).SetBold())
                        .Add(new Paragraph("\n").SetBorder(new SolidBorder(ColorConstants.BLACK, 0.5f)).SetFontSize(8).SetTextAlignment(TextAlignment.CENTER)).SetBorder(Border.NO_BORDER);
                ejercicio.AddCell(celda);

                celda = new Cell(1, 4).Add(imgEjercicio.SetHeight(63f).SetWidth(85f)).SetBorder(Border.NO_BORDER);
                ejercicio.AddCell(celda);



                celda = new Cell(1, 6).Add(new Paragraph("Notes").AddStyle(headerMusculo).SetFontSize(7f)).SetBorder(Border.NO_BORDER);
                ejercicio.AddCell(celda);

                celda = new Cell(1, 6).Add(new Paragraph("\n").SetFontSize(7f));
                ejercicio.AddCell(celda);

                tablaPrincipal.AddCell(ejercicio);
            }

            doc.Add(tablaPrincipal);

            doc.Close();
        }
Exemplo n.º 50
0
    public override void OnOpenDocument(PdfWriter writer, Document document)
    {
        try
        {
            bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            cb = writer.DirectContent;
            template = cb.CreateTemplate(100, 100);
        }
        catch //(DocumentException de)
        {

        }
        //catch //(System.IO.IOException ioe)
        //{

        //}
    }
Exemplo n.º 51
0
 abstract protected void CheckOutputIntent(PdfWriter writer, int key, Object obj1);
    //private void ExportToPDF()
    //{
    //    Document document = new Document(PageSize.A4, 0, 0, 10, 10);
    //    System.IO.MemoryStream msReport = new System.IO.MemoryStream();

    //    try
    //    {
    //        // creation of the different writers
    //        PdfWriter writer = PdfWriter.GetInstance(document, msReport);

    //        // we add some meta information to the document
    //        document.AddAuthor("Maruf");
    //        document.AddSubject("Report");

    //        document.Open();

    //        iTextSharp.text.Table datatable = new iTextSharp.text.Table(5);

    //        datatable.Padding = 2;
    //        datatable.Spacing = 0;

    //        float[] headerwidths = { 30, 15, 15, 15,25 };
    //        datatable.Widths = headerwidths;

    //        // the first cell spans 7 columns
    //        Cell cell = new Cell(new Phrase("Agent Wise Commission", FontFactory.GetFont(FontFactory.HELVETICA, 16, Font.BOLD)));
    //        cell.HorizontalAlignment = Element.ALIGN_CENTER;
    //        cell.Leading = 30;
    //        cell.Colspan = 5;
    //        cell.Border = Rectangle.NO_BORDER;
    //        cell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.Gray);
    //        datatable.AddCell(cell);


    //        int parentGridCount = 0;
    //        parentGridCount = gvAgent.Rows.Count;


    //        //int rowCount = gvFoodTransactionItemRelation.Rows.Count;

    //        for (int i = 0; i < parentGridCount; i++)
    //        {

    //            Label lblLocationName = (Label)gvAgent.Rows[i].FindControl("lblLocationName");

    //            Cell cell1 = new Cell(new Phrase("Agent Name : " + lblLocationName.Text, FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
    //            cell1.HorizontalAlignment = Element.ALIGN_LEFT;
    //            cell1.Leading = 30;
    //            cell1.Colspan = 5;
    //            cell1.Border = Rectangle.NO_BORDER;
    //            cell1.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.WhiteSmoke);
    //            datatable.AddCell(cell1);

    //            datatable.DefaultCellBorderWidth = 1;
    //            datatable.DefaultHorizontalAlignment = 1;
    //            datatable.DefaultRowspan = 2;
    //            datatable.AddCell("Location");
    //            datatable.AddCell("Trans Count");
    //            datatable.AddCell("Rate");
    //            datatable.AddCell("Fees");

    //            datatable.AddCell("Agent Commision");



    //            GridView gvTRANS = (GridView)gvAgent.Rows[i].FindControl("gvPayment");



    //            for (int j = 0; j < gvTRANS.Rows.Count; j++)
    //            {
    //                datatable.DefaultHorizontalAlignment = Element.ALIGN_LEFT;



    //                Label lbllocationName = (Label)gvTRANS.Rows[j].FindControl("lbllocationName");
    //                Label lblTransCount = (Label)gvTRANS.Rows[j].FindControl("lblTransCount");
    //                Label lblRate = (Label)gvTRANS.Rows[j].FindControl("lblRate");
    //                Label lblFees = (Label)gvTRANS.Rows[j].FindControl("lblFees");

    //                Label lblAgentCommision = (Label)gvTRANS.Rows[j].FindControl("lblAgentCommision");

    //                datatable.Alignment = Element.ALIGN_CENTER;
    //                datatable.AddCell(lbllocationName.Text);
    //                datatable.AddCell(lblTransCount.Text);
    //                datatable.AddCell(lblRate.Text);
    //                datatable.AddCell(lblFees.Text);

    //                datatable.AddCell(lblAgentCommision.Text);


    //                //Label lblTotalAgentCommission = (Label)gvTRANS.Rows[0].FindControl("lblTotalAgentCommission");



    //                Cell cell2 = new Cell(new Phrase("Sub Total : $999999 ", FontFactory.GetFont(FontFactory.HELVETICA, 12, Font.BOLD)));
    //                cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
    //                cell2.Leading = 30;
    //                cell2.Colspan = 6;
    //                cell2.Border = Rectangle.NO_BORDER;
    //                cell2.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.White);
    //                datatable.AddCell(cell2);


    //            }


    //            //Label lblSubTotalTotalAmount = (Label)gvAgent.Rows[i].FindControl("lblSubTotalTotalAmount");



    //        }

    //        document.Add(datatable);
    //    }
    //    catch (Exception e)
    //    {
    //        Console.Error.WriteLine(e.Message);
    //    }

    //    // we close the document
    //    document.Close();

    //    Response.Clear();
    //    Response.AddHeader("content-disposition", "attachment;filename=AgentWiseCommissionReport.pdf");
    //    Response.ContentType = "application/pdf";
    //    Response.BinaryWrite(msReport.ToArray());
    //    Response.End();
    //}


    private void ExportToPDF()
    {
        Document document = new Document(PageSize.A4, 0, 0, 10, 10);

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

        try
        {
            // creation of the different writers
            PdfWriter writer = PdfWriter.GetInstance(document, msReport);

            // we add some meta information to the document
            document.AddAuthor("Maruf");
            document.AddSubject("Report");

            document.Open();

            iTextSharp.text.Table datatable = new iTextSharp.text.Table(5);

            datatable.Padding = 2;
            datatable.Spacing = 0;

            float[] headerwidths = { 30, 15, 15, 15, 25 };
            datatable.Widths = headerwidths;

            // the first cell spans 7 columns
            Cell cell = new Cell(new Phrase("Agent Wise Commission Report", FontFactory.GetFont(FontFactory.HELVETICA, 16, Font.BOLD)));
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.Leading             = 30;
            cell.Colspan             = 5;
            cell.Border          = Rectangle.NO_BORDER;
            cell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.Gray);
            datatable.AddCell(cell);


            int parentGridCount = 0;
            parentGridCount = gvAgent.Rows.Count;


            //int rowCount = gvFoodTransactionItemRelation.Rows.Count;

            for (int i = 0; i < parentGridCount; i++)
            {
                Label lblLocationName = (Label)gvAgent.Rows[i].FindControl("lblLocationName");

                Cell cell1 = new Cell(new Phrase("Agent Name : " + lblLocationName.Text, FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
                cell1.HorizontalAlignment = Element.ALIGN_LEFT;
                cell1.Leading             = 30;
                cell1.Colspan             = 5;
                cell1.Border          = Rectangle.NO_BORDER;
                cell1.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.WhiteSmoke);
                datatable.AddCell(cell1);

                datatable.DefaultCellBorderWidth     = 1;
                datatable.DefaultHorizontalAlignment = 1;
                datatable.DefaultRowspan             = 2;
                datatable.AddCell("Location");
                datatable.AddCell("Trans Count");
                datatable.AddCell("Rate");
                datatable.AddCell("Fees");
                datatable.AddCell("Agent Commision");



                GridView gvPayment = (GridView)gvAgent.Rows[i].FindControl("gvPayment");



                for (int j = 0; j < gvPayment.Rows.Count; j++)
                {
                    datatable.DefaultHorizontalAlignment = Element.ALIGN_LEFT;



                    Label lbllocationName   = (Label)gvPayment.Rows[j].FindControl("lbllocationName");
                    Label lblTransCount     = (Label)gvPayment.Rows[j].FindControl("lblTransCount");
                    Label lblRate           = (Label)gvPayment.Rows[j].FindControl("lblRate");
                    Label lblFees           = (Label)gvPayment.Rows[j].FindControl("lblFees");
                    Label lblAgentCommision = (Label)gvPayment.Rows[j].FindControl("lblAgentCommision");

                    datatable.Alignment = Element.ALIGN_CENTER;
                    datatable.AddCell(lbllocationName.Text);
                    datatable.AddCell(lblTransCount.Text);
                    datatable.AddCell(lblRate.Text);
                    datatable.AddCell(lblFees.Text);
                    datatable.AddCell(lblAgentCommision.Text);
                }

                //gvPayment.FooterRow.FindControl
                Label lblTotalAgentCommission = (Label)gvPayment.FooterRow.FindControl("lblTotalAgentCommission");


                Cell cell2 = new Cell(new Phrase("Sub Total : " + lblTotalAgentCommission.Text, FontFactory.GetFont(FontFactory.HELVETICA, 12, Font.BOLD)));
                cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell2.Leading             = 30;
                cell2.Colspan             = 5;
                cell2.Border          = Rectangle.NO_BORDER;
                cell2.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.White);
                datatable.AddCell(cell2);
            }



            document.Add(datatable);
        }
        catch (Exception e)
        {
            Console.Error.WriteLine(e.Message);
        }

        // we close the document
        document.Close();

        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=AgentWiseCommissionReport.pdf");
        Response.ContentType = "application/pdf";
        Response.BinaryWrite(msReport.ToArray());
        Response.End();
    }
Exemplo n.º 53
0
    protected override void GenerateDocument(Document doc, DocumentType docType, string addSheet, PdfWriter writer)
    {
        Font normalFontSmall = FontFactory.GetFont("Arial", 10, Font.NORMAL);
        Font normalFontLarge = FontFactory.GetFont("Arial", 11, Font.NORMAL);
        Font boldFontSmall = FontFactory.GetFont("Arial", 10, Font.BOLD);
        Font boldFontLarge = FontFactory.GetFont("Arial", 11, Font.BOLD);

        // Create a table with 3 columns
        PdfPTable table = new PdfPTable(3);
        table.WidthPercentage = 100;
        // Define the table header
        table.DefaultCell.Colspan = 3;
        table.DefaultCell.Border = Rectangle.NO_BORDER;
        table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
        table.AddCell(new Phrase("PERMIT TO WORK – HOT WORKS", FontFactory.GetFont("Arial", 18)));

        // First Row to draw
        // -----------------------------------------------------------------------------------------
        // |Applicable to:                                                                          |
        // |HOT WORK: All operations involving flame , spark or heat sufficient to start a fire     |
        // -----------------------------------------------------------------------------------------
        table.DefaultCell.Border = Rectangle.BOX;
        table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
        Paragraph paragraph = new Paragraph();
        ArrayList arrayList = new ArrayList();

        arrayList.Add(new Phrase("Applicable to:\n", boldFontSmall));
        arrayList.Add(new Phrase("HOT WORK:", boldFontSmall));
        arrayList.Add(new Phrase(" All operations involving flame , spark or heat sufficient to start a fire", normalFontSmall));

        paragraph.AddAll(arrayList);
        table.AddCell(paragraph);

        // -----------------------------------------------------------------------------------------------------------------------------------
        // |N.B Work specified  in the Permit is conditional on all contractors/workers having signed and understood the West Gate Maintenance|
        // |Health & Safety                                                                                                                   |
        // |Contractor Guidelines and duly completed the company competence questionnaire                                                     |
        // -----------------------------------------------------------------------------------------------------------------------------------

        table.AddCell(new Paragraph("N.B Work specified  in the Permit is conditional on all contractors/workers having signed and understood the West Gate Maintenance \n" +
                      "Health & Safety\n" +
                      "Contractor Guidelines and duly completed the company competence questionnaire", normalFontSmall));

        // |-------------------------------------------------------------------------|
        // |SECTION 1 -  TO BE COMPLETED BY THE WEST GATE MAINTENANCE LTD SUPERVISOR |
        // |-------------------------------------------------------------------------|
        table.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
        table.AddCell(new Paragraph("SECTION 1 -  TO BE COMPLETED BY THE " + companyName + " SUPERVISOR", boldFontLarge));

        // |-------------------------------------------------------------------------|
        // Details of Work and Personnel                              Date:          |
        // |-------------------------------------------------------------------------|
        table.DefaultCell.FixedHeight = 25;
        table.DefaultCell.VerticalAlignment = Element.ALIGN_TOP;
        table.DefaultCell.Colspan = 2;
        table.DefaultCell.Border = Rectangle.LEFT_BORDER;
        table.AddCell(new Paragraph("Details of Work and Personnel", normalFontSmall));
        table.DefaultCell.Border = Rectangle.RIGHT_BORDER;
        table.AddCell(new Paragraph("Date:", normalFontSmall));

        // |-------------------------------------------------------------------------|
        // Authorised Person (Print Name)                                            |
        // |-------------------------------------------------------------------------|
        table.DefaultCell.Border = Rectangle.BOX;
        table.DefaultCell.Colspan = 3;
        table.DefaultCell.FixedHeight = 0;
        table.AddCell(new Paragraph("Authorised Person (Print Name)", boldFontLarge));
        // |-------------------------------------------------------------------------|
        // |Timescale: P.T.W. Issued	            |From:	                |To:     |
        // |-------------------------------------------------------------------------|
        table.DefaultCell.Colspan = 1;
        table.DefaultCell.FixedHeight = 0;
        table.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
        table.AddCell(new Paragraph("Timescale: P.T.W. Issued", normalFontSmall)); table.AddCell(new Paragraph("From:", normalFontSmall)); table.AddCell(new Paragraph("To:", normalFontSmall));

        // |-------------------------------------------------------------------------|
        // |Work Method:                                                             |
        // |-------------------------------------------------------------------------|
        table.DefaultCell.Colspan = 3;
        table.DefaultCell.FixedHeight = 25;
        table.DefaultCell.VerticalAlignment = Element.ALIGN_TOP;
        table.AddCell(new Paragraph("Work Method:", normalFontLarge));

        // Two Empty rows
        table.AddCell(""); table.AddCell("");

        // |-------------------------------------------------------------------------|
        // |Mandatory Safety Requirements:                                           |
        // |-------------------------------------------------------------------------|

        PdfPCell cell = new PdfPCell(new Paragraph("Mandatory Safety Requirements:", normalFontLarge));
        cell.BorderWidthTop = 1f;
        cell.Colspan = 3;
        table.AddCell(cell);

        // |----------------------------------------------------------------------------------------------------------------|
        // |1.	All areas to be checked and combustibles removed or protected before commencement of work.                  |
        // |2.	All areas to be screened, protected and warning notices displayed before commencement of work               |
        // |3.	Hand held extinguishers (appropriate to the task) within easy reach and operative be competent in their use.|
        // |4.	Area to be inspected for combustion on completion of work and 60 minutes after.                             |
        // |5.	Site specific safety method statement and appropriated risk assessment to be completed.                     |
        // |----------------------------------------------------------------------------------------------------------------|
        table.DefaultCell.FixedHeight = 0;
        table.AddCell(new Paragraph("1.	All areas to be checked and combustibles removed or protected before commencement of work.\n" +
            "2.	All areas to be screened, protected and warning notices displayed before commencement of work.\n" +
            "3.	Hand held extinguishers (appropriate to the task) within easy reach and operative be competent in their use.\n" +
            "4.	Area to be inspected for combustion on completion of work and 60 minutes after.\n" +
            "5.	Site specific safety method statement and appropriated risk assessment to be completed.", boldFontSmall));

        // |-------------------------------------------------------------------------|
        // |Name of Applicant in Charge of Works (print name):                       |
        // |-------------------------------------------------------------------------|
        table.AddCell(new Paragraph("Name of Applicant in Charge of Works (print name):", normalFontSmall));

        // |-------------------------------------------------------------------------|
        // |Applicant’s Company (print name):                                        |
        // |-------------------------------------------------------------------------|
        table.AddCell(new Paragraph("Applicant's Company (print name):", normalFontLarge));

        // |-------------------------------------------------------------------------|
        // |Other Personnel Engaged in Works (print names):                          |
        // |-------------------------------------------------------------------------|
        table.AddCell(new Paragraph("Other Personnel Engaged in Works (print names):", normalFontLarge));

        // |-------------------------------------------------------------------------|
        // |1.                                  | 2.                                 |
        // |3.                                  | 4.                                 |
        // |5.                                  | 6.                                 |
        // |-------------------------------------------------------------------------|

        PdfPTable nestedTable = new PdfPTable(2);
        for (int i = 1; i <= 6; i++)
        {
            nestedTable.AddCell(new Paragraph(string.Concat(i.ToString(), "."), normalFontLarge));
        }
        table.DefaultCell.Padding = 0;
        table.AddCell(nestedTable);
        table.DefaultCell.Padding = 2;
        // |--------------------------------------------------------------------------|
        // |AUTHORISATION                                                             |
        // |I have verified the above information and authorise the works to commence.|
        // |--------------------------------------------------------------------------|
        paragraph = new Paragraph();
        paragraph.Add(new Phrase("AUTHORISATION\n", boldFontLarge));
        paragraph.Add(new Phrase("I have verified the above information and authorise the works to commence.", normalFontSmall));
        table.AddCell(paragraph);

        // |--------------------------------------------------------------------------|
        // |Authorised persons                     | Time:             | Date:        |
        // |Signature:	                           | (Print Name)      |              |
        // |--------------------------------------------------------------------------|
        table.DefaultCell.Colspan = 1;
        table.DefaultCell.Rowspan = 2;
        table.AddCell(new Paragraph("Authorised persons\nSignature:", normalFontLarge));
        table.DefaultCell.Rowspan = 1;
        table.AddCell(new Paragraph("Time:", normalFontLarge));
        table.AddCell(new Paragraph("Date:", normalFontLarge));
        table.DefaultCell.Colspan = 2;
        table.AddCell(new Paragraph("(Print Name)", normalFontLarge));

        // |--------------------------------------------------------------------------|
        // |SECTION 2  -TO BE COMPLETED BY THE OPERATIVE IN CHARGE                    |
        // |--------------------------------------------------------------------------|

        table.DefaultCell.Colspan = 3;
        cell = new PdfPCell(new Paragraph("SECTION 2  -TO BE COMPLETED BY THE OPERATIVE IN CHARGE", boldFontLarge));
        cell.Colspan = 3;
        cell.BorderWidthTop = 0.8f;
        cell.BorderWidthBottom = 0.0f;
        table.AddCell(cell);

        // |----------------------------------------------------------------------------------------------------------------------|
        // |ACCEPTANCE                                                                                                            |
        // |I will accept responsibility for the work/personnel stated and agree to implement safe working procedures and confirm |
        // |that all personnel are adequately trained and will only work on the job/equipment specified.                          |
        // |----------------------------------------------------------------------------------------------------------------------|
        paragraph = new Paragraph();
        paragraph.Add(new Phrase("ACCEPTANCE\n\n", FontFactory.GetFont("Arial", 8, Font.UNDERLINE | Font.BOLD)));
        paragraph.Add(new Phrase("I will accept responsibility for the work/personnel stated and agree to implement safe working procedures and confirm that all personnel are adequately trained and will only work on the job/equipment specified.", normalFontSmall));
        table.AddCell(paragraph);

        // |--------------------------------------------------------------------------|
        // |Applicant in charge                    | Time:             | Date:        |
        // |Signature:	                           | 	               |              |
        // |--------------------------------------------------------------------------|
        table.DefaultCell.Colspan = 1;
        table.AddCell(new Paragraph("Applicant in charge\nSignature:", normalFontLarge));
        table.AddCell(new Paragraph("Time:", normalFontLarge));
        table.AddCell(new Paragraph("Date:", normalFontLarge));

        // |--------------------------------------------------------------------------|
        // |SECTION 3 - TO BE COMPLETED BY OPERATIVE IN CHARGE                        |
        // |--------------------------------------------------------------------------|
        table.DefaultCell.Colspan = 3;
        table.AddCell(new Paragraph("SECTION 3 - TO BE COMPLETED BY OPERATIVE IN CHARGE", boldFontLarge));

        // |----------------------------------------------------------------------------------------------------------------------|
        // |CLEARANCE                                                                                                             |
        // |I confirm that personnel and equipment have been withdrawn. The work has/has not been completed and that              |
        // |uncompleted work will not be restarted until a new Permit is issued. (*Delete which is not applicable)                |
        // |----------------------------------------------------------------------------------------------------------------------|
        paragraph = new Paragraph();
        paragraph.Add(new Phrase("CLEARANCE\n\n", FontFactory.GetFont("Arial", 8, Font.UNDERLINE | Font.BOLD)));
        paragraph.Add(new Phrase("I confirm that personnel and equipment have been withdrawn. The work has/has not been completed and that uncompleted work will not be restarted until a new Permit is issued. (*Delete which is not applicable)", normalFontSmall));
        table.AddCell(paragraph);

        // |--------------------------------------------------------------------------|
        // |Applicant in charge                    | Time:             | Date:        |
        // |Signature:	                           | 	               |              |
        // |--------------------------------------------------------------------------|
        table.DefaultCell.Colspan = 1;
        table.AddCell(new Paragraph("Applicant in charge\nSignature:", normalFontLarge));
        table.AddCell(new Paragraph("Time:", normalFontLarge));
        table.AddCell(new Paragraph("Date:", normalFontLarge));

        // |--------------------------------------------------------------------------|
        // |SECTION 4 – TO BE COMPLETED BY THE SUPERVISOR                             |
        // |--------------------------------------------------------------------------|
        table.DefaultCell.Colspan = 3;
        table.AddCell(new Paragraph("SECTION 4 – TO BE COMPLETED BY THE SUPERVISOR", boldFontLarge));

        // |--------------------------------------|
        // |CANCELLATION                          |                                                                                |
        // |This permit is cancelled and invalid  |
        // |--------------------------------------|
        paragraph = new Paragraph();
        paragraph.Add(new Phrase("CANCELLATION\n\n", FontFactory.GetFont("Arial", 8, Font.UNDERLINE | Font.BOLD)));
        paragraph.Add(new Phrase("This permit is cancelled and invalid", normalFontSmall));
        table.AddCell(paragraph);

        // |--------------------------------------------------------------------------|
        // |Authorised Persons                     | Time:             | Date:        |
        // |Signature:	                           | 	               |              |
        // |--------------------------------------------------------------------------|
        table.DefaultCell.Colspan = 1;
        table.SetWidths(new float[] { 50, 20, 30 });
        table.AddCell(new Paragraph("Authorised Persons\nSignature:", normalFontLarge));
        table.AddCell(new Paragraph("Time:", normalFontLarge));
        table.AddCell(new Paragraph("Date:", normalFontLarge));

        doc.Add(table);
    }
Exemplo n.º 54
0
    public void pdfGenerate(string ProjectID, string projectunit)
    {
        string pdftype  = projectunit;
        string boxid    = ProjectID;
        string AuthorID = ProjectID;

        Document doc = new Document(PageSize.A4, 88f, 88f, 10f, 10f);


        iTextSharp.text.Font NormalFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);



        string filelocationpath       = "";
        string actualfilenamewithtime = "";
        string fileid1    = "";
        string servername = ConfigurationManager.AppSettings["ServerName"].ToString();
        string domainame  = ConfigurationManager.AppSettings["DomainName"].ToString();
        string username   = ConfigurationManager.AppSettings["UserName"].ToString();
        string password   = ConfigurationManager.AppSettings["Password"].ToString();
        string mainpath   = ConfigurationManager.AppSettings["PdfPath"].ToString();

        actualfilenamewithtime = ProjectID + "_" + "merged" + ".pdf";
        try
        {
            using (NetworkShareAccesser.Access(servername, domainame, username, password))
            {
                path1 = Path.Combine(mainpath, "PublicationPrintEvaluation");
                // Create a new PdfWriter object, specifying the output stream
                if (Directory.Exists(path1))
                {
                    //string patientid = PatientID;
                    foreach (var files in Directory.GetFiles(path1))
                    {
                        FileInfo info     = new FileInfo(files);
                        var      fileName = Path.GetFileName(info.FullName);
                        if (info.Exists)
                        {
                            info.Delete();
                        }
                    }

                    filelocationpath = Path.Combine(path1, actualfilenamewithtime);

                    var output = new FileStream(filelocationpath, FileMode.Create);
                    var writer = PdfWriter.GetInstance(doc, output);
                }
                else
                {
                    Directory.CreateDirectory(path1);
                    string path   = Path.Combine(path1, actualfilenamewithtime);
                    var    output = new FileStream(filelocationpath, FileMode.Create);
                    var    writer = PdfWriter.GetInstance(doc, output);
                }


                doc.Open();
                //User p5 = new User();
                //Journal_DataObject obj5 = new Journal_DataObject();
                //p5 = obj5.ImagePath();
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(HttpContext.Current.Request.MapPath("~/Images/MAHE-logo.png"));
                img.Alignment = iTextSharp.text.Image.TEXTWRAP | iTextSharp.text.Image.ALIGN_RIGHT;
                img.ScaleToFit(150f, 150f);
                img.SetAbsolutePosition(58, 760); // left  top
                img.SpacingAfter = 20f;

                doc.Add(img);
                PdfPCell             cell    = null;
                Paragraph            para    = null;
                Paragraph            para1   = null;
                Paragraph            para2   = null;
                Paragraph            para3   = null;
                Paragraph            para4   = null;
                iTextSharp.text.Font times   = null;
                iTextSharp.text.Font times1  = null;
                BaseFont             bfTimes = null;
                bfTimes              = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
                times                = new iTextSharp.text.Font(bfTimes, 11, iTextSharp.text.Font.BOLD);
                times1               = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.BOLD);
                para                 = new Paragraph("CERTIFICATE FROM THE INVESTIGATORS", times);
                para.SpacingBefore   = 15f;
                para.IndentationLeft = 140f;
                doc.Add(para);


                para4 = new Paragraph("For", times);
                para4.SpacingBefore   = 15f;
                para4.IndentationLeft = 200f;
                doc.Add(para4);
                para2 = new Paragraph("Unique Tracking Number (UTN) of the Proposal", times);
                para2.SpacingBefore   = 5f;
                para2.IndentationLeft = 130f;
                doc.Add(para2);
                para3 = new Paragraph("(To be submitted by the Principal Investigator before obtaining a letter of endorsement from the Head of the", times1);

                para3.SpacingBefore   = 15f;
                para3.IndentationLeft = -20f;
                doc.Add(para3);
                para3 = new Paragraph("    Institution/Organization)", times1);
                para3.SpacingBefore   = 3f;
                para3.IndentationLeft = 140f;
                doc.Add(para3);


                PdfPTable table = new PdfPTable(2);
                table.SpacingBefore = 10f;
                //cell.BorderColor = new BaseColor(0, 0, 0);
                table.TotalWidth = 320f;
                //fix the absolute width of the table
                table.LockedWidth   = true;
                table.SpacingBefore = 10f;
                table.SpacingAfter  = 40f;
                times = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.NORMAL);
                Journal_DataObject obj = new Journal_DataObject();
                User p1 = new User();
                User p2 = new User();
                User p3 = new User();
                p1 = obj.fnfindProject(ProjectID, projectunit);
                string agency = obj.FindAgencyName(p1.AgencyId);
                //iTextSharp.text.Font t = null;
                //t = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.BOLD);

                Journal_DataObject obj2 = new Journal_DataObject();
                p2 = obj.ProjectCount(ProjectID, projectunit);



                times1 = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.BOLD);
                para1  = new Paragraph("", times1);
                para1.SpacingBefore   = 40f;  // spacing from the top
                para1.SpacingAfter    = 10f;  // spacing from the bottom
                para1.IndentationLeft = -30f; // left space
                doc.Add(para1);
                times1 = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.BOLD);
                para1  = new Paragraph("Project Title:  ", times1);

                para1.SpacingBefore   = -25f; // spacing from the top
                para1.SpacingAfter    = 5f;   // spacing from the bottom
                para1.IndentationLeft = -20f; // left space

                doc.Add(para1);
                times1 = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.NORMAL);
                para1  = new Paragraph("" + p1.Title, times1);

                para1.SpacingBefore   = -20f; // spacing from the top
                para1.SpacingAfter    = 5f;   // spacing from the bottom
                para1.IndentationLeft = 36f;  // left space

                doc.Add(para1);

                times1 = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.BOLD);
                para1  = new Paragraph("", times1);

                para1.SpacingBefore   = 10f;  // spacing from the top
                para1.SpacingAfter    = 50f;  // spacing from the bottom
                para1.IndentationLeft = -30f; // left space
                doc.Add(para1);
                times1 = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.BOLD);
                para1  = new Paragraph("Date of Application to funding Agency:    ", times1);
                para1.SpacingBefore   = -60f; // spacing from the top
                para1.SpacingAfter    = -20f; // spacing from the bottom
                para1.IndentationLeft = -20f; // left space
                doc.Add(para1);
                times1 = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.NORMAL);
                para1  = new Paragraph("" + p1.AppliedDate.ToShortDateString(), times1);
                para1.SpacingBefore   = 6f;   // spacing from the top
                para1.SpacingAfter    = 5f;   // spacing from the bottom
                para1.IndentationLeft = 143f; // left space
                doc.Add(para1);

                PdfPTable tabl_Orth026 = new PdfPTable(2);
                cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_LEFT);
                cell.PaddingBottom = 10f;
                tabl_Orth026.AddCell(cell);
                tabl_Orth026.SpacingBefore = 30f;
                doc.Add(tabl_Orth026);
                times1              = new iTextSharp.text.Font(bfTimes, 10);
                para1.Alignment     = Element.ALIGN_CENTER;
                para1.SpacingBefore = -50f;
                PdfPTable tabData = new PdfPTable(3);
                tabData.TotalWidth = 480f;
                //fix the absolute width of the table
                tabData.LockedWidth = true;
                times = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.NORMAL);
                float[] widths = new float[] { 1.8f, 3.5f, 3f };
                tabData.AddCell(new PdfPCell(new Phrase(" Investigators", FontFactory.GetFont("Arial", 11, iTextSharp.text.Font.BOLD, BaseColor.BLACK))));
                tabData.AddCell(new PdfPCell(new Phrase(" Name", FontFactory.GetFont("Arial", 11, iTextSharp.text.Font.BOLD, BaseColor.BLACK))));
                tabData.AddCell(new PdfPCell(new Phrase(" Affiliation", FontFactory.GetFont("Arial", 11, iTextSharp.text.Font.BOLD, BaseColor.BLACK))));


                tabData.AddCell(cell);
                tabData.SetWidths(widths);

                tabData.SpacingBefore = 20f;
                para1.IndentationLeft = 30f; // left space
                doc.Add(tabData);

                ArrayList authors = new ArrayList();
                int       a;
                int       b = p2.AuthorCount;


                string s1 = p2.AuthorName1;

                for (a = 0; a < b; a++)
                {
                    authors.Add(a);
                }
                DataSet dz = null;
                string  publicationtype = obj2.CheckPublicationType(ProjectID, projectunit);
                if (publicationtype == "F")
                {
                    dz = obj2.fnInvestigatorsdetail(ProjectID, projectunit);
                }
                else
                {
                    dz = obj2.fnStudentdetail(ProjectID, projectunit);
                }


                int count = dz.Tables[0].Rows.Count;
                for (int i = 0; i < count; i++)
                {
                    int       rownumber = i;
                    PdfPTable tabData2  = new PdfPTable(3);
                    cell.BorderColor       = new BaseColor(0, 0, 0);
                    cell.VerticalAlignment = 10;

                    tabData2.TotalWidth = 480f;
                    //fix the absolute width of the table AuthorName1,EmailId2,DepartmentName,Institute_name
                    tabData2.LockedWidth = true;
                    float[] width = new float[] { 1f, 3f, 2.5f };
                    times = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.NORMAL);
                    string investigatortype = dz.Tables[0].Rows[i]["InvestigatorType"].ToString();
                    if (investigatortype == "P")
                    {
                        tabData2.AddCell(new PdfPCell(new Phrase(" Principal Investigator ", FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK))));
                        string str         = dz.Tables[0].Rows[i]["InvestigatorName"].ToString();
                        string IndexAgency = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
                        tabData2.AddCell(new PdfPCell(new Phrase("  " + IndexAgency, FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK))));
                        string IndexAgency2 = dz.Tables[0].Rows[i]["InstitutionName"].ToString();
                        tabData2.AddCell(new PdfPCell(new Phrase(" " + IndexAgency2, FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK))));
                    }
                    else if (investigatortype == "C")
                    {
                        tabData2.AddCell(new PdfPCell(new Phrase(" Co- Investigator " + rownumber, FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK))));
                        string str         = dz.Tables[0].Rows[i]["InvestigatorName"].ToString();
                        string IndexAgency = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
                        tabData2.AddCell(new PdfPCell(new Phrase("  " + IndexAgency, FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK))));
                        string IndexAgency2 = dz.Tables[0].Rows[i]["InstitutionName"].ToString();
                        tabData2.AddCell(new PdfPCell(new Phrase(" " + IndexAgency2, FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK))));
                    }

                    tabData2.AddCell(cell);
                    tabData2.SetWidths(widths);
                    doc.Add(tabData2);
                    //tabData2.SpacingAfter = 10f;
                }

                PdfPTable tablen2 = new PdfPTable(2);
                //actual width of table in points
                tablen2.TotalWidth = 500f;//216f;

                //fix the absolute width of the table
                tablen2.LockedWidth = true;

                //relative col widths in proportions -  2/3 & 1/3
                float[] widthw2 = new float[] { 0.1f, 2f };
                tablen2.SetWidths(widthw2);
                tablen2.HorizontalAlignment = -50;
                //leave a gap before and after the table


                //PdfPCell cell2 = new PdfPCell(new Phrase("ITEM"));
                PdfPCell cell22 = new PdfPCell(new Phrase("", new iTextSharp.text.Font(iTextSharp.text.Font.NORMAL, 10, iTextSharp.text.Font.BOLD)));
                cell22.Border          = iTextSharp.text.Rectangle.NO_BORDER;
                cell22.BackgroundColor = new iTextSharp.text.BaseColor(233, 233, 233);
                tablen2.SpacingBefore  = -30f;
                tablen2.SpacingAfter   = 0f;
                tablen2.AddCell(cell22);


                PdfPCell cell222 = new PdfPCell(new Phrase("Certified that the proposed project will be carried out at MAHE subject to approval of the proposal for funding from " + agency.ToString() + " agency/organization for a sum of Rs " + p1.AppliedAmount + " for a period of " + p1.DurationOfProject + " months. The research work proposed in the scheme/project does not in any way duplicate the work already done or being carried out elsewhere on the subject nor is under consideration for financial support from any other agency.", new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.NORMAL)));
                cell222.Border          = iTextSharp.text.Rectangle.NO_BORDER;
                cell222.BackgroundColor = new iTextSharp.text.BaseColor(233, 233, 233);

                tablen2.AddCell(cell222);
                tablen2.SpacingBefore = 30f;
                tablen2.SpacingAfter  = 0f;
                doc.Add(tablen2);


                PdfPTable tablen12 = new PdfPTable(2);
                //actual width of table in points
                tablen12.TotalWidth = 500f;//216f;
                //fix the absolute width of the table
                tablen12.LockedWidth = true;
                //relative col widths in proportions -  2/3 & 1/3
                float[] w = new float[] { 0.1f, 2f };
                tablen12.SetWidths(w);
                tablen12.HorizontalAlignment = -50;
                //leave a gap before and after the table
                tablen12.SpacingBefore = 0;
                tablen12.SpacingAfter  = 10f;
                //PdfPCell cell2 = new PdfPCell(new Phrase("ITEM"));
                PdfPCell cellr = new PdfPCell(new Phrase("", new iTextSharp.text.Font(iTextSharp.text.Font.NORMAL, 10, iTextSharp.text.Font.NORMAL)));
                cellr.Border          = iTextSharp.text.Rectangle.NO_BORDER;
                cellr.BackgroundColor = new iTextSharp.text.BaseColor(233, 233, 233);
                tablen12.AddCell(cellr);
                PdfPCell cellr1 = new PdfPCell(new Phrase("\nHaving obtained the Ethical Approval from the Concerned Ethical Committee and agreeing to submit a certificate from the Institutional biosafety committee where applicable, the proposal has been assigned a Unique Tracking Number, UTN MAHE/ " + p1.UTN.ToString() + " dated " + p1.Created_Date.ToShortDateString() + " \n\n", new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.NORMAL)));
                cellr1.Border          = iTextSharp.text.Rectangle.NO_BORDER;
                cellr1.BackgroundColor = new iTextSharp.text.BaseColor(233, 233, 233);
                tablen12.AddCell(cellr1);
                doc.Add(tablen12);


                PdfPTable OfficeUse1 = new PdfPTable(3);
                //actual width of table in points
                OfficeUse1.TotalWidth = 500f;//216f;
                //fix the absolute width of the table
                OfficeUse1.LockedWidth = true;
                //relative col widths in proportions -  2/3 & 1/3
                float[] OfficeUseW1 = new float[] { 7f, 5.3f, 7f };
                OfficeUse1.SetWidths(OfficeUseW1);
                OfficeUse1.HorizontalAlignment = 250;
                //leave a gap before and after the table
                //tablen.SpacingBefore = 20f;
                //OfficeUse.SpacingAfter = 0;
                PdfPCell OfficeUseCell11 = new PdfPCell(new Phrase("\n\n\nName & Signature of the Principal Investigator", new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.BOLD)));
                OfficeUseCell11.Right      = 50f;
                OfficeUseCell11.PaddingTop = 150f;

                OfficeUseCell11.Border = iTextSharp.text.Rectangle.NO_BORDER;
                //OfficeUseCell11.BackgroundColor = new iTextSharp.text.BaseColor(233, 233, 233);
                OfficeUse1.AddCell(OfficeUseCell11);
                PdfPCell OfficeUseCel2 = new PdfPCell(new Phrase("\n\n\n", new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.BOLD)));
                OfficeUseCel2.Right  = 50f;
                OfficeUseCel2.Border = iTextSharp.text.Rectangle.NO_BORDER;
                //OfficeUseCel2.BackgroundColor = new iTextSharp.text.BaseColor(233, 233, 233);
                OfficeUse1.AddCell(OfficeUseCel2);
                PdfPCell OfficeUseCel5 = new PdfPCell(new Phrase("\n\n\n Name & Signature of Head of Institution", new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.BOLD)));
                OfficeUseCel5.Right      = 50f;
                OfficeUseCel5.PaddingTop = 150f;
                OfficeUseCel5.Border     = iTextSharp.text.Rectangle.NO_BORDER;
                //OfficeUseCel5.BackgroundColor = new iTextSharp.text.BaseColor(233, 233, 233);
                OfficeUse1.AddCell(OfficeUseCel5);
                doc.Add(OfficeUse1);

                doc.Close();

                FileInfo myfile = new FileInfo(filelocationpath);
                if (myfile.Exists)
                {
                    log.Info("Evaluation Form Generated Successfully,  for Project ID: " + ProjectID + " of Project Unit: " + projectunit);
                    HttpContext.Current.Response.ClearContent();
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + actualfilenamewithtime);
                    HttpContext.Current.Response.AddHeader("Content-Length", myfile.Length.ToString());
                    HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
                    HttpContext.Current.Response.TransmitFile(myfile.FullName);
                    HttpContext.Current.Response.End();
                }
            }
        }


        catch (Exception e)
        {
            log.Info("Evaluation Form generation failed,  for Project ID: " + ProjectID + " of Project Unit: " + projectunit);
            log.Error("Error: " + e);
        }
    }
Exemplo n.º 55
0
    public override void OnEndPage(PdfWriter writer, Document document)
    {
        base.OnEndPage(writer, document);

        if ((tipoDocumento == "contrato") || (tipoDocumento == "contrato_preimpreso")) //no se ponen cabeceras ni fotter
        {

        }
        else
        {
            if (tipoDocumento == "clausula")
            {
                int pageN = writer.PageNumber;
                String text = "Pag. " + pageN + " de ";
                float len = bf.GetWidthPoint(text, 8);

                Rectangle pageSize = document.PageSize;

                cb.SetRGBColorFill(100, 100, 100);

                cb.BeginText();
                cb.SetFontAndSize(bf, 8);
                cb.SetTextMatrix(pageSize.GetLeft(40), pageSize.GetBottom(30));
                cb.ShowText(text);
                cb.EndText();

                cb.AddTemplate(template, pageSize.GetLeft(40) + len, pageSize.GetBottom(30));

                cb.BeginText();
                cb.SetFontAndSize(bf, 8);
                cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT,
                    "Impreso el: " + fechaImpresion.ToLongDateString(),
                    pageSize.GetRight(40),
                    pageSize.GetBottom(30), 0);
                cb.EndText();
            }
            else
            {
                if ((tipoDocumento == "apertura_cuenta") || (tipoDocumento == "apertura_cuenta_avvillas"))
                {

                }
                else
                {
                    if (tipoDocumento == "autos_recomendacion")
                    {

                    }
                    else
                    {
                        if (tipoDocumento == "orden_compra")
                        {
                            int pageN = writer.PageNumber;
                            String text = "Pag. " + pageN + " de ";
                            float len = bf.GetWidthPoint(text, 8);

                            Rectangle pageSize = document.PageSize;

                            cb.SetRGBColorFill(100, 100, 100);

                            cb.BeginText();
                            cb.SetFontAndSize(bf, 8);
                            cb.SetTextMatrix(pageSize.GetLeft(40), pageSize.GetBottom(30));
                            cb.ShowText(text);
                            cb.EndText();

                            cb.AddTemplate(template, pageSize.GetLeft(40) + len, pageSize.GetBottom(30));

                            cb.BeginText();
                            cb.SetFontAndSize(bf, 8);
                            cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT,
                                "Impreso el: " + fechaImpresion.ToLongDateString(),
                                pageSize.GetRight(40),
                                pageSize.GetBottom(30), 0);
                            cb.EndText();
                        }
                        else
                        {
                            if (tipoDocumento == "manualServicio")
                            {

                            }
                            else
                            {
                                if (tipoDocumento == "entrevista_retiro")
                                {

                                }
                            }
                        }
                    }
                }
            }
        }
    }
Exemplo n.º 56
0
        private void fichaDeInscriçõesToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                Eventos eventoSelecionado = (Eventos)listViewEventos.SelectedItems[0].Tag;

                saveFileDialog_FichaInscricao.FileName    = "FichaInscricoes_" + eventoSelecionado.Descricao + ".pdf";
                saveFileDialog_FichaInscricao.Filter      = "All files (*.*)|*.*";
                saveFileDialog_FichaInscricao.FilterIndex = 0;

                if (saveFileDialog_FichaInscricao.ShowDialog() == DialogResult.OK)
                {
                    Document doc = new Document(PageSize.A4);
                    doc.SetMargins(60, 60, 30, 30);

                    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(saveFileDialog_FichaInscricao.FileName, FileMode.Create));

                    doc.Open();


                    // <---------------- Título ---------------->

                    Paragraph titulo = new Paragraph("Ficha de Inscrição\n");
                    titulo.Alignment = Element.TITLE;


                    // <---------------- Informações sobre o Evento ---------------->

                    Paragraph evento   = new Paragraph("\n\nEvento: " + eventoSelecionado.Descricao);
                    Paragraph local    = new Paragraph("Local: " + eventoSelecionado.Local);
                    Paragraph data     = new Paragraph(string.Format("Data: {0:dd} de {0:MMMM} de {0:yyyy}", eventoSelecionado.DataHora));
                    Paragraph hora     = new Paragraph(string.Format("Hora: {0:HH:mm:ss}", eventoSelecionado.DataHora));
                    Paragraph limite   = new Paragraph("Limite de Participação: " + eventoSelecionado.LimiteParticipacao + " crianças");
                    Paragraph idadeInf = new Paragraph("Idade Mínima: " + eventoSelecionado.IdadeInferior + " anos");
                    Paragraph idadeSup = new Paragraph("Idade Máxima: " + eventoSelecionado.IdadeSuperior + " anos\n\n\n\n");

                    evento.Alignment   = Element.ALIGN_JUSTIFIED;
                    local.Alignment    = Element.ALIGN_JUSTIFIED;
                    data.Alignment     = Element.ALIGN_JUSTIFIED;
                    hora.Alignment     = Element.ALIGN_JUSTIFIED;
                    limite.Alignment   = Element.ALIGN_JUSTIFIED;
                    idadeInf.Alignment = Element.ALIGN_JUSTIFIED;
                    idadeSup.Alignment = Element.ALIGN_JUSTIFIED;

                    Paragraph paragrafo1 = new Paragraph("Aceita que  o seu filho participe neste evento\n");
                    Paragraph paragrafo2 = new Paragraph("   Sim\n   Não\n");
                    Paragraph paragrafo3 = new Paragraph("Se responder sim preencha as inofrmações do filho que se seguem.\n\n\n");

                    Paragraph paragrafofilho              = new Paragraph("Informação do filho");
                    Paragraph paragrafonomefilho          = new Paragraph("Nome:_________________________________________________________\n");
                    Paragraph paragrafodatanascmentofilho = new Paragraph("Data Nascimento:____/____/______\n");
                    Paragraph paragrafoescolafilho        = new Paragraph("Escola:_________________________________________________________\n\n\n\n");


                    Paragraph paragrafo4 = new Paragraph("Se ainda não for cliente da loja, por favor, preencha os dados que se seguem.\n\n");

                    Paragraph paragrafocliente           = new Paragraph("Informação do cliente");
                    Paragraph paragrafonomecliente       = new Paragraph("Nome:________________________________________________________\n");
                    Paragraph paragrafomoradacliente     = new Paragraph("Morada:_______________________________________________________\n");
                    Paragraph paragrafolocalidadecliente = new Paragraph("Localidade:________________________________  Codigo Postal: ____-___\n");
                    Paragraph paragrafotelefonecliente   = new Paragraph("Telefone: ___ ___ ___\n");
                    Paragraph paragrafotelemovelcliente  = new Paragraph("Telemóvel: ___ ___ ___\n");
                    Paragraph paragrafomailcliente       = new Paragraph("Mail:__________________________________________________________\n");



                    // <---------------- Adicionar os dados todos ao documento ---------------->

                    doc.Add(titulo);
                    doc.Add(evento);
                    doc.Add(local);
                    doc.Add(data);
                    doc.Add(hora);
                    doc.Add(limite);
                    doc.Add(idadeInf);
                    doc.Add(idadeSup);
                    doc.Add(paragrafo1);
                    doc.Add(paragrafo2);
                    doc.Add(paragrafo3);
                    doc.Add(paragrafofilho);
                    doc.Add(paragrafonomefilho);
                    doc.Add(paragrafodatanascmentofilho);
                    doc.Add(paragrafoescolafilho);
                    doc.Add(paragrafo4);
                    doc.Add(paragrafocliente);
                    doc.Add(paragrafonomecliente);
                    doc.Add(paragrafomoradacliente);
                    doc.Add(paragrafolocalidadecliente);

                    doc.Add(paragrafotelefonecliente);
                    doc.Add(paragrafotelemovelcliente);
                    doc.Add(paragrafomailcliente);

                    doc.Close();

                    MessageBox.Show("Lista de Inscrições guardada com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch
            {
                MessageBox.Show("Selecione o evento primeiro!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Exemplo n.º 57
0
        private void BtnPrn_Click(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            String date = "";

            date = DateTime.Now.ToString("yyyy-MM-dd");
            DataTable dt = new DataTable();

            dt = ebC.eB20DB.cntDB.selectByDate(date);
            if (dt.Rows.Count <= 0)
            {
                return;
            }

            BaseFont  bfR, bfR1;
            BaseColor clrBlack = new iTextSharp.text.BaseColor(0, 0, 0);
            String    myFont   = Environment.CurrentDirectory + "\\THSarabun.ttf";

            bfR  = BaseFont.CreateFont(myFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            bfR1 = BaseFont.CreateFont(myFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            iTextSharp.text.Font fntHead = new iTextSharp.text.Font(bfR, 12, iTextSharp.text.Font.NORMAL, clrBlack);
            var logo = iTextSharp.text.Image.GetInstance(Environment.CurrentDirectory + "\\logo.png");

            logo.SetAbsolutePosition(10, PageSize.A4.Height - 90);
            logo.ScaleAbsoluteHeight(70);
            logo.ScaleAbsoluteWidth(70);

            Document doc = new Document(PageSize.A4, 36, 36, 36, 36);

            try
            {
                if (File.Exists(Environment.CurrentDirectory + "\\report.pdf"))
                {
                    File.Delete(Environment.CurrentDirectory + "\\report.pdf");
                }

                FileStream output = new FileStream(Environment.CurrentDirectory + "\\report.pdf", FileMode.Create);
                PdfWriter  writer = PdfWriter.GetInstance(doc, output);
                doc.Open();

                doc.Add(logo);

                int i = 0, r = 0, row2 = 0, rowEnd = 24;
                r = dt.Rows.Count;
                int next = r / 24;
                for (int p = 0; p <= next; p++)
                {
                    PdfContentByte canvas = writer.DirectContent;
                    canvas.BeginText();
                    canvas.SetFontAndSize(bfR, 12);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "บริษัท เคาเตอร์ พลัส จำกัด", 100, 800, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "99/19 ซอยประเสริฐมนูกิจ 29 ถนนประเสริฐมนูกิจ แขวงจรเข้บัว เขตลาดพร้าว กรุงเทพฯ 10230", 100, 780, 0);
                    canvas.EndText();

                    canvas.BeginText();
                    canvas.SetFontAndSize(bfR, 18);
                    canvas.ShowTextAligned(Element.ALIGN_CENTER, "รายงานสรุปการนับเงินที่จำหน่ายจากตู้ ตามวันที่ ", PageSize.A4.Width / 2, 740, 0);
                    canvas.EndText();

                    canvas.BeginText();
                    canvas.SetFontAndSize(bfR, 16);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "ลำดับ ", 60, 720, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "สถานที่ ", 60, 700, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "จำนวนเงินที่นับได้จริง ", 60, 680, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "ยอดรวม ", 360, 720, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "รวมเงิน ", 360, 700, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "เงินเกิน ", 360, 680, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "เงินขาด ", 360, 660, 0);
                    canvas.EndText();

                    canvas.SaveState();
                    canvas.SetLineWidth(0.05f);
                    canvas.MoveTo(40, 640);//vertical
                    canvas.LineTo(40, 110);

                    canvas.MoveTo(40, 640);//Hericental
                    canvas.LineTo(560, 640);

                    canvas.MoveTo(560, 640);//vertical
                    canvas.LineTo(560, 110);

                    canvas.MoveTo(40, 610);//Hericental
                    canvas.LineTo(560, 610);

                    canvas.MoveTo(40, 110);//Hericental
                    canvas.LineTo(560, 110);

                    canvas.MoveTo(100, 640);//vertical
                    canvas.LineTo(100, 110);

                    canvas.MoveTo(400, 640);//vertical
                    canvas.LineTo(400, 110);

                    canvas.MoveTo(440, 640);//vertical QTY
                    canvas.LineTo(440, 110);

                    canvas.MoveTo(500, 640);//vertical Price
                    canvas.LineTo(500, 110);

                    //canvas.MoveTo(520, 640);//vertical Amount
                    //canvas.LineTo(520, 110);
                    canvas.Stroke();
                    canvas.RestoreState();
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                doc.Close();
                System.Threading.Thread.Sleep(1000);

                Process          pp = new Process();
                ProcessStartInfo s  = new ProcessStartInfo(Environment.CurrentDirectory + "\\report.pdf");
                //s.Arguments = "/c dir *.cs";
                pp.StartInfo = s;

                pp.Start();
            }
        }
Exemplo n.º 58
0
        public ActionResult cvdownload(int js_id)
        {
            jobseeker_info js             = db.jobseeker_info.Find(js_id);
            StringBuilder  status         = new StringBuilder("");
            DateTime       dTime          = DateTime.Now;
            string         strPDFFileName = string.Format("CvPdf" + dTime.ToString("yyyyMMdd") + "-" + ".pdf");
            string         strAttachment  = Server.MapPath("~/Content/pdfs/" + strPDFFileName);

            status.Append("<!DOCTYPE html>");
            status.Append("<html>");
            status.Append("<head><title></title></head>");
            status.Append("<body style='margin: 20px 100px;'><h2 style='text-align:center'>Curriculum Vitae</h2>");
            status.Append("<b>" + js.full_name + "</b><br>");
            status.Append("<b>(+977)" + js.contact + "</b><br>");
            status.Append("<b>" + js.email + "</b><br>");
            status.Append("<b>" + js.current_address + "</b><br><br>");
            List <jobseeker_education> ed = db.jobseeker_education.Where(a => a.js_id == js_id).OrderByDescending(a => a.jsed_id).ToList();

            if (ed.Count > 0)
            {
                status.Append("<h3><b>Education</b></h3>");
                foreach (var item in ed)
                {
                    status.Append("<b>" + item.education_level + "</b><br><ul>");
                    status.Append("<li>" + item.start_date + " - " + item.end_date + "</li>");
                    status.Append("<li>" + item.institution + "</li></ul>");
                }
            }
            List <js_experience> ex = db.js_experience.Where(a => a.js_id == js_id).ToList();

            if (ex.Count > 0)
            {
                status.Append("<h3><b>Experience</b></h3><br>");
                foreach (var item in ex)
                {
                    status.Append("<b>" + item.title + "</b><br><ul>");
                    status.Append("<li>" + item.start_date + " - " + item.end_date + "</li>");
                    status.Append("<li>" + item.institution + "</li></ul>");
                }
            }
            List <string> skills = js.skills.Split(',').ToList();

            if (skills.Count > 0)
            {
                status.Append("<h3><b>Skills</b></h3><br><ul>");
                foreach (var item in ex)
                {
                    status.Append("<b>" + item + "</b><br><br>");
                }
                status.Append("</ul>");
            }
            string cv = db.tbl_cv.Where(a => a.jobseeker_id == js.js_id).Select(a => a.cv).FirstOrDefault().ToString();

            status.Append(cv);
            status.Append("</body>");
            status.Append("</html>");
            StringReader str = new StringReader(status.ToString());
            MemoryStream ms  = new MemoryStream();

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4);

            PdfWriter pdfwriter = iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms);

            document.Open();
            using (TextReader sReader = new StringReader(status.ToString()))
            {
                List <IElement> list = HTMLWorker.ParseToList(sReader, new StyleSheet());
                foreach (IElement elm in list)
                {
                    document.Add(elm);
                }
            }
            document.Close();
            document.Dispose();
            Response.Buffer = true;
            Response.Clear();
            Response.AppendHeader("Content-Type", "application/x-pdf");
            Response.AppendHeader("Content-disposition", "attachment; filename=" + js.full_name + "cv.pdf");
            Response.BinaryWrite(ms.GetBuffer());
            Response.Flush();
            Response.Close();
            return(View());
        }
 private static void DrawLine(PdfWriter writer, float x1, float y1, float x2, float y2, Color color)
 {
     PdfContentByte contentByte = writer.DirectContent;
     contentByte.SetColorStroke(color);
     contentByte.MoveTo(x1, y1);
     contentByte.LineTo(x2, y2);
     contentByte.Stroke();
 }
Exemplo n.º 60
0
        private void DoReport(string query, string firstParam, string secondParam)
        {
            SqlDataReader sqlReader = null; // инициализируем reader

            using (WinForms.SaveFileDialog saveFileDialog = new WinForms.SaveFileDialog()
            {
                Filter = "PDF file|*.pdf", ValidateNames = true // выбираем фильтр для сохранения
            })
                if (saveFileDialog.ShowDialog() == WinForms.DialogResult.OK)
                {
                    iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4);
                    try
                    {
                        if (tbPercent.Text == "" || cmbGroup.Text == "") // проверяем выбраны ли все параметры
                        {
                            MessageBox.Show("Необходимо выбрать все параметры", "Внимание", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else if (Convert.ToDouble(tbPercent.Text) < 0 || Convert.ToDouble(tbPercent.Text) > 100) // проверяем правильный ли диапазон процента
                        {
                            MessageBox.Show("Введите коректный параметр процента посещения (от 0 до 100)", "Внимание", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            PdfWriter.GetInstance(doc, new FileStream(saveFileDialog.FileName, FileMode.Create));

                            doc.Open();
                            BaseFont             bf    = BaseFont.CreateFont(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "Verdana.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                            BaseFont             italf = BaseFont.CreateFont(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "Verdanai.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                            iTextSharp.text.Font itf   = new iTextSharp.text.Font(bf, 10f, iTextSharp.text.Font.ITALIC);
                            iTextSharp.text.Font htf   = new iTextSharp.text.Font(bf, 20f, iTextSharp.text.Font.NORMAL);
                            iTextSharp.text.Font ttf   = new iTextSharp.text.Font(bf, 10f, iTextSharp.text.Font.NORMAL);
                            iTextSharp.text.Font stf   = new iTextSharp.text.Font(bf, 8f, iTextSharp.text.Font.NORMAL);

                            doc.Add(new iTextSharp.text.Paragraph("ХНЭУ", htf));
                            doc.Add(new iTextSharp.text.Paragraph("им. Семена Кузнеца", ttf));
                            PdfPTable table = new PdfPTable(5);
                            PdfPCell  cell  = new PdfPCell(new Phrase("Список студентов", ttf));
                            cell.Colspan             = 5;
                            cell.HorizontalAlignment = Element.ALIGN_CENTER;
                            table.AddCell(cell);
                            table.AddCell(new Phrase("ФИО", ttf));
                            table.AddCell(new Phrase("Тел.", ttf));
                            table.AddCell(new Phrase("Всего часов", ttf));
                            table.AddCell(new Phrase("Пропущено", ttf));
                            table.AddCell(new Phrase("По ув. причине", ttf));
                            doc.Add(new iTextSharp.text.Paragraph("\n", ttf));
                            if (rbMore.IsChecked == true)
                            {
                                doc.Add(new iTextSharp.text.Paragraph("Список студентов, у которых % пропусков больше " + tbPercent.Text, ttf));
                            }
                            else if (rbLess.IsChecked == true)
                            {
                                doc.Add(new iTextSharp.text.Paragraph("Список студентов, у которых % пропусков меньше " + tbPercent.Text, ttf));
                            }
                            doc.Add(new iTextSharp.text.Paragraph("Группа: " + cmbGroup.Text, ttf));
                            doc.Add(new iTextSharp.text.Paragraph("\n", ttf));
                            SqlCommand command = new SqlCommand(query, sqlConnection); // создаем SQL запрос к БД
                            command.Parameters.AddWithValue("@group", firstParam);     // подставляем параметры в запрос
                            command.Parameters.AddWithValue("@percent", secondParam);
                            sqlReader = command.ExecuteReader();                       // исполняем SQL запрос

                            while (sqlReader.Read())                                   // пока sqlReader содержит строки добавляем их в отчет
                            {
                                table.AddCell(new Phrase(sqlReader["name"].ToString(), stf));
                                table.AddCell(new Phrase(sqlReader["number"].ToString(), stf));
                                table.AddCell(new Phrase(sqlReader["allhours"].ToString(), stf));
                                table.AddCell(new Phrase(sqlReader["losthours"].ToString(), stf));
                                table.AddCell(new Phrase(sqlReader["reason"].ToString(), stf));
                            }
                            doc.Add(table);
                            doc.Add(new iTextSharp.text.Paragraph("\n", ttf));
                            PdfPTable dateTable = new PdfPTable(1);
                            cell = new PdfPCell(new Phrase("Дата: " + DateTime.Now, ttf));
                            cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            cell.Border = 0;
                            dateTable.AddCell(cell);
                            doc.Add(dateTable);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, ex.Source, MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    finally
                    {
                        doc.Close();
                        sqlReader.Close();
                    }
                }
        }