Untitled

mail@pastecode.io avatar
unknown
csharp
a month ago
13 kB
2
Indexable
Never
    private bool GenerarContratoConRepresentanteLegal(DataRow datos, ref string pdfSalida, string firmaSrc = "", string firmaRepresLegalSrc = "")
    {
        Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
        Microsoft.Office.Interop.Word.Document wordDoc = null;
        object paramMissing = Type.Missing;

        var rutaDocx = "";

        try
        {
            rutaDocx = GetRutaDoumento(Server.MapPath(string.Format("~/plantillas/CONTRATO_VIAJE_COMBINADO_MENOR.docx")));

            //var camposStr = _gui.RecuperaUnCampo("m_documento_pdf", "CAMPOS_PDF", string.Format("DOCUMENTO_PDF='CONTRATO_VOLUNTARIO_MENOR'"));
            var camposStr = "NOMBRE_COMPLETO,NOMBRE_COMPLETO2,NOMBRE_COMPLETO3,NOMBRE_COMPLETO4,NOMBRE_COMPLETO5,IDENTIFICACION,IDENTIFICACION2,IDENTIFICACION3,IDENTIFICACION4,IDENTIFICACION5,DIRECCION,CALLE,CIUDAD,TELEFONO,TELEFONO2,EMAIL,EMAIL2,NACIONALIDAD,NACIONALIDAD2,TIEMPO_ESTANCIA,FECHA_INICIO,DIA,MES,TASA_INSCRIPCION,TASA_INSCRIPCION2,TASA_PROGRAMA,TOTAL,REPRES_LEGAL_DIRECCION,REPRES_LEGAL_EMAIL,REPRES_LEGAL_LOCALIDAD,REPRES_LEGAL_LOCALIDAD1,REPRES_LEGAL_NACIONALIDAD,REPRES_LEGAL_NIF,REPRES_LEGAL_NIF1,REPRES_LEGAL_NIF2,REPRES_LEGAL_NIF3,REPRES_LEGAL_NIF4,REPRES_LEGAL_NIF5,REPRES_LEGAL_NIF6,REPRES_LEGAL_NIF7,REPRES_LEGAL_NIF8,REPRES_LEGAL_NOMBRE,REPRES_LEGAL_NOMBRE1,REPRES_LEGAL_NOMBRE2,REPRES_LEGAL_NOMBRE3,REPRES_LEGAL_NOMBRE4,REPRES_LEGAL_NOMBRE5,REPRES_LEGAL_NOMBRE6,REPRES_LEGAL_NOMBRE7,REPRES_LEGAL_NOMBRE8,REPRES_LEGAL_FECHA_FIRMA,REPRES_LEGAL_TLF_FIJO,REPRES_LEGAL_TLF_MOVIL";
            var campos = camposStr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            pdfSalida = GetSafeFilename(string.Format("{0}_{1}.pdf", "CONTRATO", txtUsuario.Text));
            var rutaPdfSalida = Server.MapPath(string.Format("~/plantillas/{0}", pdfSalida));

            if (!System.IO.File.Exists(rutaDocx))
            {
                return false;
            }

            wordApp.Visible = false;
            object oPath = rutaDocx;
            wordDoc = wordApp.Documents.Open(ref oPath, ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing);

            foreach (Microsoft.Office.Interop.Word.Bookmark bookmark in wordDoc.Bookmarks)
            {
                Microsoft.Office.Interop.Word.Range rng = bookmark.Range;

                var campo = campos.Where(c => c == bookmark.Name).FirstOrDefault();
                

                if (campo != null && !string.IsNullOrEmpty(campo))
                {
                    if (datos.Table.Columns.Contains(campo))
                    {
                        var valorCampo = datos[campo] != DBNull.Value ? datos[campo].ToString() : "";
                        rng.Text = valorCampo;
                    }
                    if (campo == "DIA")
                    {
                        var fechaString = DateTime.Now.ToString("D");
                        rng.Text = fechaString;

                    }
                    if (campo == "FIRMA" && !string.IsNullOrEmpty(firmaRepresLegalSrc))
                    {
                        object oRange = (object)rng;
                        object saveWithDocument = true;
                        object missing = Type.Missing;
                        var shape = bookmark.Range.InlineShapes.AddPicture(firmaRepresLegalSrc, ref paramMissing, ref paramMissing, ref paramMissing);

                        Size imgSize = new Size((int)shape.Width, (int)shape.Height);
                        var resize = ResizeKeepAspect(imgSize, 200, 120);
                        shape.Height = resize.Height;
                        shape.Width = resize.Width;

                        shape.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoTrue;
                    }

                    if (campo == "FIRMA_MENOR_CONDUCTA")
                    {
                        object oRange = (object)rng;
                        object saveWithDocument = true;
                        object missing = Type.Missing;
                        var shape = bookmark.Range.InlineShapes.AddPicture(firmaSrc, ref paramMissing, ref paramMissing, ref paramMissing);

                        Size imgSize = new Size((int)shape.Width, (int)shape.Height);
                        var resize = ResizeKeepAspect(imgSize, 200, 120);
                        shape.Height = resize.Height;
                        shape.Width = resize.Width;

                        shape.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoTrue;
                    }

                }
            }

            string dateFormat = "dd/MM/yyyy";
            var provider = new CultureInfo("es-ES");
            var fechaNacimientoStr = _gui.RecuperaUnCampo("trans_contactos", "FECHA_NACIMIENTO", "IDCONTACTO=" + txtUsuario.Text);

            DateTime fechaNacimiento = DateTime.Now;
            bool esMenor = false;
            if (!string.IsNullOrEmpty(fechaNacimientoStr))
            {
                if (DateTime.TryParseExact(fechaNacimientoStr, dateFormat, provider, DateTimeStyles.None, out fechaNacimiento))
                {
                    int edadUsuario = (int)Math.Floor((DateTime.Now - fechaNacimiento).TotalDays / 365.25D);
                    esMenor = edadUsuario < 18;
                }
            }
            if (!string.IsNullOrEmpty(firmaSrc))
            {
                if (!esMenor)
                {
                foreach (Microsoft.Office.Interop.Word.Bookmark bookmark in wordDoc.Bookmarks)
                {
                    string valorbm = bookmark.Name.ToUpper();
                    if (bookmark.Name.ToUpper() == "FIRMA" || bookmark.Name.ToUpper() == "FIRMA1" || bookmark.Name.ToUpper() == "FIRMA2" || bookmark.Name.ToUpper() == "FIRMA3" || bookmark.Name.ToUpper() == "FIRMA4")
                    {
                        Microsoft.Office.Interop.Word.Range rng = bookmark.Range;
                        object oRange = (object)rng;
                        object saveWithDocument = true;
                        object missing = Type.Missing;
                        var shape = bookmark.Range.InlineShapes.AddPicture(firmaSrc, ref paramMissing, ref paramMissing, ref paramMissing);

                        Size imgSize = new Size((int)shape.Width, (int)shape.Height);
                        var resize = ResizeKeepAspect(imgSize, 200, 120);
                        shape.Height = resize.Height;
                        shape.Width = resize.Width;

                        shape.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoTrue;
                    }
                    //if (s.AlternativeText.ToUpper().Contains("CUADRO"))
                    //{
                    //    object A = s.Anchor;
                    //    Shape newImage = wordDoc.Shapes.AddPicture(firmaSrc, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref A);
                    //    newImage.Top = s.Top;
                    //    newImage.Left = s.Left;
                    //    newImage.Width = s.Width;
                    //    newImage.Height = s.Height;
                    //    s.Delete();
                    //}
                }
            }
            }


            if (!string.IsNullOrEmpty(firmaRepresLegalSrc))
            {

                if (esMenor)
                {
                    foreach (Microsoft.Office.Interop.Word.Bookmark bookmark in wordDoc.Bookmarks)
                    {
                        string valorbm = bookmark.Name.ToUpper();
                        if (bookmark.Name.ToUpper() == "FIRMA" || bookmark.Name.ToUpper() == "FIRMA1" || bookmark.Name.ToUpper() == "FIRMA2" || bookmark.Name.ToUpper() == "FIRMA3" || bookmark.Name.ToUpper() == "FIRMA4")
                        {
                            Microsoft.Office.Interop.Word.Range rng = bookmark.Range;
                            object oRange = (object)rng;
                            object saveWithDocument = true;
                            object missing = Type.Missing;
                            var shape = bookmark.Range.InlineShapes.AddPicture(firmaRepresLegalSrc, ref paramMissing, ref paramMissing, ref paramMissing);

                            Size imgSize = new Size((int)shape.Width, (int)shape.Height);
                            var resize = ResizeKeepAspect(imgSize, 200, 120);
                            shape.Height = resize.Height;
                            shape.Width = resize.Width;

                            shape.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoTrue;
                        }
                        //if (s.AlternativeText.ToUpper().Contains("CUADRO"))
                        //{
                        //    object A = s.Anchor;
                        //    Shape newImage = wordDoc.Shapes.AddPicture(firmaSrc, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref A);
                        //    newImage.Top = s.Top;
                        //    newImage.Left = s.Left;
                        //    newImage.Width = s.Width;
                        //    newImage.Height = s.Height;
                        //    s.Delete();
                        //}
                    }
                }
                foreach (Microsoft.Office.Interop.Word.Shape s in wordApp.ActiveDocument.Shapes)
                {

                    if (s.AlternativeText.ToUpper().Contains("FIRMA_REPRES_LEGL"))
                    {
                        object A = s.Anchor;
                        Shape newImage = wordDoc.Shapes.AddPicture(firmaRepresLegalSrc, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref A);
                        newImage.Top = s.Top;
                        newImage.Left = s.Left;
                        newImage.Width = s.Width;
                        newImage.Height = s.Height;
                        s.Delete();
                    }
                }
            }


            ////ANEXO
            //Microsoft.Office.Interop.Word.Document tableDoc = GenerateAnexoDoc(datos, firmaSrc, wordApp);
            //var tableDocPath = tableDoc.FullName;

            //object docStart = wordDoc.Content.End - 1;
            //object docEnd = wordDoc.Content.End;

            //object start = tableDoc.Content.Start;
            //object end = tableDoc.Content.End;

            //tableDoc.Range(ref start, ref end).Copy();
            //Microsoft.Office.Interop.Word.Range docRng = wordDoc.Range(ref docStart, ref docEnd);
            //docRng.InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak);

            //docRng.Paste();



            //tableDoc = GenerateConsentimientoImagenesDoc(datos, firmaSrc, wordApp);
            //tableDocPath = tableDoc.FullName;

            //docStart = wordDoc.Content.End - 1;
            //docEnd = wordDoc.Content.End;

            //start = tableDoc.Content.Start;
            //end = tableDoc.Content.End;

            //tableDoc.Range(ref start, ref end).Copy();
            //docRng = wordDoc.Range(ref docStart, ref docEnd);
            //docRng.InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak);

            //docRng.Paste();



            if (System.IO.File.Exists(rutaPdfSalida))
                System.IO.File.Delete(rutaPdfSalida);

            wordDoc.ExportAsFixedFormat(rutaPdfSalida, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF, false,
                    Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument, 0, 100,
                    Microsoft.Office.Interop.Word.WdExportItem.wdExportDocumentContent, true, true, Microsoft.Office.Interop.Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks,
                    true, true, true, ref paramMissing);

            return true;

        }
        catch (Exception ex)
        {
            return false;
            //throw ex;
        }
        finally
        {

            if (wordDoc != null)
                wordDoc.Close(false);

            if (wordApp != null)
                wordApp.Quit(false);

            // Release all Interop objects.
            if (wordDoc != null)
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc);
            if (wordApp != null)
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);

            wordDoc = null;
            wordApp = null;

            GC.Collect();

            if (System.IO.File.Exists(rutaDocx))
                System.IO.File.Delete(rutaDocx);
        }
    }
Leave a Comment