protected void Page_Load(object sender, EventArgs e) { long auditoryId = Convert.ToInt64(Request.QueryString["id"]); int companyId = Convert.ToInt32(Request.QueryString["companyId"]); var company = new Company(companyId); var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var auditory = Auditory.ById(auditoryId, user.CompanyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } string formatedDescription = auditory.Description.Replace("?", string.Empty); formatedDescription = formatedDescription.Replace("#", string.Empty); formatedDescription = formatedDescription.Replace("/", string.Empty); formatedDescription = formatedDescription.Replace("\\", string.Empty); formatedDescription = formatedDescription.Replace(":", string.Empty); formatedDescription = formatedDescription.Replace(";", string.Empty); formatedDescription = formatedDescription.Replace(".", string.Empty); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_Auditory"], formatedDescription, DateTime.Now); // FONTS var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts); } this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); this.arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK); var document = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55); var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create)); var pageEventHandler = new TwoColumnHeaderFooter() { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName), CompanyId = auditory.CompanyId, CompanyName = company.Name, Title = dictionary["Item_Auditory"] }; writer.PageEvent = pageEventHandler; document.Open(); #region Dades bàsiques // Ficha pincipal var planning = AuditoryPlanning.ByAuditory(auditory.Id, auditory.CompanyId); var table = new PdfPTable(4) { WidthPercentage = 100, HorizontalAlignment = 0 }; table.SetWidths(new float[] { 30f, 50f, 30f, 50f }); table.AddCell(new PdfPCell(new Phrase(auditory.Description, descriptionFont)) { Colspan = 4, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Type"])); table.AddCell(TitleData(dictionary["Item_Adutory_Type_Label_" + auditory.Type.ToString()])); if (auditory.Provider.Id > 0) { table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Provider"])); table.AddCell(TitleData(auditory.Provider.Description)); } else if (auditory.Customer.Id > 0) { table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Customer"])); table.AddCell(TitleData(auditory.Customer.Description)); } else { table.AddCell(TitleData(string.Empty, 2)); } table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Rules"])); var rulesText = string.Empty; bool firstRule = true; foreach (var rule in auditory.Rules) { if (firstRule) { firstRule = false; } else { rulesText += ", "; } rulesText += rule.Description; } table.AddCell(TitleData(rulesText, 3)); var previewDateText = string.Empty; if (planning != null && planning.Count > 0) { previewDateText = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", planning.OrderBy(p => p.Date).First().Date); } table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_InternalResponsible"])); table.AddCell(TitleData(auditory.InternalResponsible.FullName, 3)); //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_PannedDate"])); //table.AddCell(TitleData(previewDateText)); table.AddCell(TitleLabel(dictionary["Item_Audiotry_PDF_Planned"])); if (auditory.PlannedBy.Id > 0) { var planningText = string.Format( CultureInfo.InvariantCulture, "{0} {1} {2}", auditory.PlannedBy.FullName, dictionary["Item_Auditory_PDF_Label_date"], string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.PlannedOn) ?? "-"); table.AddCell(TitleData(planningText, 3)); } else { table.AddCell(TitleData(string.Empty, 3)); } //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_PlanningDate"])); //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.PlannedOn) ?? "-")); table.AddCell(TitleLabel(dictionary["Item_Auditory_PDF_Closing"])); if (auditory.ClosedBy.Employee.Id > 0) { var closedText = string.Format( CultureInfo.InvariantCulture, "{0} {1} {2}", auditory.ClosedBy.Employee.FullName, dictionary["Item_Auditory_PDF_Label_date"], string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ClosedOn) ?? "-"); table.AddCell(TitleData(closedText, 3)); } else { table.AddCell(TitleData(string.Empty, 3)); } //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_ClosedOn"])); //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ClosedOn) ?? "-")); table.AddCell(TitleLabel(dictionary["Item_Auditory_PDF_Validation"])); if (auditory.ValidatedBy.Id > 0) { var validatedText = string.Format( CultureInfo.InvariantCulture, "{0} {1} {2}", auditory.ValidatedBy.FullName, dictionary["Item_Auditory_PDF_Label_date"], string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ValidatedOn) ?? "-"); table.AddCell(TitleData(validatedText, 3)); } else { table.AddCell(TitleData(string.Empty, 3)); } //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_ValidatedOn"])); //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ValidatedOn) ?? "-")); table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Scope"])); table.AddCell(TitleData(auditory.Scope, 3)); table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Address"])); table.AddCell(TitleData(auditory.EnterpriseAddress, 3)); table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Notes"])); table.AddCell(TitleData(string.IsNullOrEmpty(auditory.Notes.Trim()) ? "-" : auditory.Notes, 3)); document.Add(table); #endregion if (auditory.Status > 2) { var widthsPlanning = new float[] { 30f, 20f, 25f, 60f, 60f, 60f }; var tablePlanning = new PdfPTable(widthsPlanning.Length) { WidthPercentage = 100, HorizontalAlignment = 0 }; tablePlanning.SetWidths(widthsPlanning); tablePlanning.AddCell(new PdfPCell(new Phrase(dictionary["Item_Auditory_PlanningTable_Title"], descriptionFont)) { Colspan = 6, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Date"])); tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Hour"])); tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Duration"])); tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Process"])); tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Auditor"])); tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Audited"])); foreach (var pla in planning) { var hourText = string.Empty; var hours = 0; var minutes = pla.Hour; while (minutes > 59) { hours++; minutes -= 60; } hourText = string.Format(CultureInfo.InvariantCulture, "{0:0}:{1:00}", hours, minutes); var auditedText = pla.ProviderName; if (string.IsNullOrEmpty(auditedText)) { auditedText = pla.Audited.FullName; } tablePlanning.AddCell(ToolsPdf.DataCellCenter(pla.Date)); tablePlanning.AddCell(ToolsPdf.DataCellCenter(hourText)); tablePlanning.AddCell(ToolsPdf.DataCellCenter(pla.Duration)); tablePlanning.AddCell(ToolsPdf.DataCell(pla.Process.Description)); tablePlanning.AddCell(ToolsPdf.DataCell(pla.Auditor.Description)); tablePlanning.AddCell(ToolsPdf.DataCell(auditedText)); } document.Add(tablePlanning); document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var widthsTroballes = new float[] { 30f, 30f, 20f, 8f }; var tableTroballes = new PdfPTable(widthsTroballes.Length) { WidthPercentage = 100, HorizontalAlignment = 0 }; tableTroballes.SetWidths(widthsTroballes); tableTroballes.AddCell(new PdfPCell(new Phrase(dictionary["Item_Auditory_Title_Found"], descriptionFont)) { Colspan = 4, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Found"])); tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Requirement"])); tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Result"])); tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Action"])); var troballes = AuditoryCuestionarioFound.ByAuditory(auditory.Id, auditory.CompanyId); foreach (var troballa in troballes) { tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Text)); tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Requeriment)); tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Unconformity)); tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Action ? dictionary["Common_Yes"] : dictionary["Common_No"])); } document.Add(tableTroballes); var widthsMillores = new float[] { 80f, 8f }; var tableMillores = new PdfPTable(widthsMillores.Length) { WidthPercentage = 100, HorizontalAlignment = 0 }; tableMillores.SetWidths(widthsMillores); tableMillores.AddCell(new PdfPCell(new Phrase(dictionary["Item_Auditory_Title_Improvements"], descriptionFont)) { Colspan = 4, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); tableMillores.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Improvement"])); tableMillores.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Action"])); var millores = AuditoryCuestionarioImprovement.ByAuditory(auditory.Id, auditory.CompanyId); foreach (var millora in millores) { tableMillores.AddCell(ToolsPdf.DataCell(millora.Text)); tableMillores.AddCell(ToolsPdf.DataCell(millora.Action ? dictionary["Common_Yes"] : dictionary["Common_No"])); } document.Add(tableMillores); if (!string.IsNullOrEmpty(auditory.PuntosFuertes.Trim())) { document.Add(new Phrase(Environment.NewLine)); document.Add(new Phrase(dictionary["Item_Auditory_Label_PuntosFuertes"], new Font(this.arial, 10, Font.BOLD, BaseColor.BLACK))); document.Add(new Phrase(Environment.NewLine)); document.Add(new Phrase(auditory.PuntosFuertes)); } var actions = IncidentAction.ByAuditoryId(auditory.Id, auditory.CompanyId); if (actions != null && actions.Count > 0) { document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var widthsActions = new float[] { 8f, 80f }; var tableActions = new PdfPTable(widthsActions.Length) { WidthPercentage = 100, HorizontalAlignment = 0 }; tableActions.SetWidths(widthsActions); tableActions.AddCell(new PdfPCell(new Phrase(dictionary["Item_IncidentActions"], descriptionFont)) { Colspan = 4, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); tableActions.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Type"])); tableActions.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"])); foreach (var action in actions) { string actionTypeText = string.Empty; switch (action.ActionType) { default: case 1: actionTypeText = dictionary["Item_IncidentAction_Type1"]; break; case 2: actionTypeText = dictionary["Item_IncidentAction_Type2"]; break; case 3: actionTypeText = dictionary["Item_IncidentAction_Type3"]; break; } tableActions.AddCell(ToolsPdf.DataCell(actionTypeText)); tableActions.AddCell(ToolsPdf.DataCell(action.Description)); } document.Add(tableActions); } } document.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf"); Response.ContentType = "application/pdf"; Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName); Response.Flush(); Response.Clear(); }
protected void Page_Load(object sender, EventArgs e) { var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER; var borderBL = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER; var borderBR = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER; var borderTBL = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER; var borderTBR = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER; var alignRight = Element.ALIGN_RIGHT; long oportunityId = Convert.ToInt64(Request.QueryString["id"]); int companyId = Convert.ToInt32(Request.QueryString["companyId"]); var company = new Company(companyId); var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var oportunity = Oportunity.ById(oportunityId, user.CompanyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(oportunity.Description); var alignLeft = Element.ALIGN_LEFT; string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_Oportunity"], formatedDescription, DateTime.Now); var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts); } this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); this.arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK); var document = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55); var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create)); var pageEventHandler = new TwoColumnHeaderFooter { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName), CompanyId = oportunity.CompanyId, CompanyName = company.Name, Title = dictionary["Item_Oportunity"] }; writer.PageEvent = pageEventHandler; document.Open(); #region Dades bàsiques var table = new PdfPTable(4) { WidthPercentage = 100, HorizontalAlignment = 0 }; table.SetWidths(new float[] { 30f, 50f, 30f, 50f }); table.AddCell(new PdfPCell(new Phrase(oportunity.Description, descriptionFont)) { Colspan = 4, Border = Rectangle.NO_BORDER, PaddingTop = 10f, PaddingBottom = 10f, HorizontalAlignment = Element.ALIGN_CENTER }); table.AddCell(TitleCell(dictionary["Item_BusinessRisk_Tab_Basic"], 4)); table.AddCell(TitleLabel(dictionary["Item_BusinessRisk_LabelField_DateStart"])); table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy}", oportunity.DateStart))); table.AddCell(TitleLabel(dictionary["Item_Process"])); table.AddCell(TitleData(oportunity.Process.Description)); table.AddCell(TitleLabel(dictionary["Item_Rule"])); table.AddCell(TitleData(oportunity.Rule.Description)); table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_IPR"])); table.AddCell(TitleData(oportunity.Rule.Limit.ToString())); string costText = oportunity.Cost.ToString(); if (costText == "0") { costText = "-"; } table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Cost"])); table.AddCell(TitleData(costText)); string impactText = oportunity.Impact.ToString(); if (impactText == "0") { impactText = "-"; } table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Impact"])); table.AddCell(TitleData(impactText)); table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Status"])); table.AddCell(TitleData(dictionary["Item_BusinessRisk_Status_Assumed"])); table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Description"])); table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Description, ToolsPdf.BorderAll, alignLeft, 4)); table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Causes"])); table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Causes, ToolsPdf.BorderAll, alignLeft, 4)); table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Control"])); table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Control, ToolsPdf.BorderAll, alignLeft, 4)); table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Notes"])); table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Notes, ToolsPdf.BorderAll, alignLeft, 4)); table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_Oportunity_Tab_Graphics"], 4)); table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_IPR"])); table.AddCell(TitleData(oportunity.Rule.Limit.ToString())); table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Status"])); table.AddCell(TitleData(dictionary["Item_BusinessRisk_Status_Assumed"])); string finalCostText = oportunity.FinalCost.ToString(); if (finalCostText == "0") { finalCostText = "-"; } table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Cost"])); table.AddCell(TitleData(finalCostText)); string finalImpactText = oportunity.FinalImpact.ToString(); if (finalImpactText == "0") { finalImpactText = "-"; } table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Impact"])); table.AddCell(TitleData(finalImpactText)); document.Add(table); #endregion if (user.HasGrantToRead(ApplicationGrant.IncidentActions)) { // Añadir posible acción var action = IncidentAction.ByOportunityId(oportunity.Id, companyId); if (action.Id > 0) { var tableAction = new PdfPTable(4) { WidthPercentage = 100, HorizontalAlignment = 0 }; tableAction.SetWidths(new float[] { 15f, 30f, 15f, 30f }); // Descripción var headerFont = new Font(this.arial, 15, Font.NORMAL, BaseColor.BLACK); tableAction.AddCell(new PdfPCell(new Phrase(dictionary["Item_Incident_PDF_ActionPageTitle"], headerFont)) { Colspan = 4, Border = ToolsPdf.BorderBottom, HorizontalAlignment = Rectangle.ALIGN_CENTER }); tableAction.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Description"], Rectangle.NO_BORDER)); tableAction.AddCell(ValueCell(action.Description, ToolsPdf.BorderNone, alignLeft, 3)); // WhatHappend tableAction.AddCell(SeparationRow()); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"])); tableAction.AddCell(TextAreaCell(Environment.NewLine + action.WhatHappened, borderSides, alignLeft, 4)); tableAction.AddCell(BlankRow()); tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.WhatHappenedBy.FullName, borderBL, alignLeft, 2)); tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.WhatHappenedOn), borderBR, alignRight, 2)); // Causes var causesFullName = string.Empty; var causesDate = string.Empty; if (action.CausesBy != null) { causesFullName = action.CausesBy.FullName; causesDate = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.CausesOn); } tableAction.AddCell(SeparationRow()); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"])); tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Causes, borderSides, alignLeft, 4)); tableAction.AddCell(BlankRow()); tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + causesFullName, borderBL, alignLeft, 2)); tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_Date"], causesDate), borderBR, alignRight, 2)); // Actions var actionFullName = string.Empty; var actionDate = string.Empty; if (action.ActionsBy != null) { actionFullName = action.ActionsBy.FullName; actionDate = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ActionsOn); } tableAction.AddCell(SeparationRow()); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Actions"])); tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Actions, borderSides, alignLeft, 4)); tableAction.AddCell(BlankRow()); tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + actionFullName, borderBL, alignLeft, 2)); tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_DateExecution"], actionDate), borderBR, alignRight, 2)); // Monitoring tableAction.AddCell(SeparationRow()); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Monitoring"])); tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Monitoring, ToolsPdf.BorderAll, alignLeft, 4)); // Close var closedFullName = string.Empty; var closedDate = string.Empty; if (action.ClosedBy != null) { closedFullName = action.ClosedBy.FullName; closedDate = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ClosedOn); } tableAction.AddCell(SeparationRow()); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"])); tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], closedFullName), borderTBL, alignLeft, 2)); tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Common_DateClose"], closedDate), borderTBR, alignRight, 2)); // Notes tableAction.AddCell(SeparationRow()); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"])); tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Notes, ToolsPdf.BorderAll, alignLeft, 4)); document.NewPage(); document.Add(tableAction); } #region Historico acciones var historico = IncidentAction.ByOportunityCode(oportunity.Code, company.Id).Where(ia => ia.Oportunity.Id != oportunity.Id).OrderBy(incidentAction => incidentAction.WhatHappenedOn).ToList(); if (historico.Count > 0) { var backgroundColor = new iTS.BaseColor(225, 225, 225); var rowPair = new iTS.BaseColor(255, 255, 255); var rowEven = new iTS.BaseColor(240, 240, 240); var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK); document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var tableHistoric = new iTSpdf.PdfPTable(5) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f }; tableHistoric.SetWidths(new float[] { 20f, 30f, 120f, 20f, 20f }); tableHistoric.AddCell(new PdfPCell(new Phrase(dictionary["Item_BusinessRisk_Tab_HistoryActions"], descriptionFont)) { Colspan = 5, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); var valueFont = new Font(this.headerFont, 11, Font.BOLD, BaseColor.BLACK); tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"])); tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Status"])); tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"])); tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_ImplementDate"])); tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Close"])); int cont = 0; foreach (var accion in historico) { string statusText = dictionary["Item_Incident_Status1"]; if (accion.CausesOn.HasValue) { statusText = dictionary["Item_Incident_Status2"]; } if (accion.ActionsOn.HasValue) { statusText = dictionary["Item_Incident_Status3"]; } if (accion.ClosedOn.HasValue) { statusText = dictionary["Item_Incident_Status4"]; } tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.WhatHappenedOn, ToolsPdf.LayoutFonts.Times)); tableHistoric.AddCell(ToolsPdf.DataCell(statusText, ToolsPdf.LayoutFonts.Times)); tableHistoric.AddCell(ToolsPdf.DataCell(accion.Description, ToolsPdf.LayoutFonts.Times)); tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.ActionsOn, ToolsPdf.LayoutFonts.Times)); tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.ClosedOn, ToolsPdf.LayoutFonts.Times)); cont++; } tableHistoric.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ": " + cont.ToString(), ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderTop, Colspan = 5, Padding = 8f }); document.Add(tableHistoric); } #endregion #region Costes var costs = IncidentActionCost.ByOportunityId(oportunity.Id, company.Id); if (costs.Count > 0) { var backgroundColor = new iTS.BaseColor(225, 225, 225); var rowPair = new iTS.BaseColor(255, 255, 255); var rowEven = new iTS.BaseColor(240, 240, 240); var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK); document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var tableCost = new iTSpdf.PdfPTable(5) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f }; tableCost.SetWidths(new float[] { 90f, 40f, 30f, 60f, 20f }); tableCost.AddCell(new PdfPCell(new Phrase(dictionary["Item_Incident_Tab_Costs"], descriptionFont)) { Colspan = 5, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); var valueFont = new Font(this.headerFont, 11, Font.BOLD, BaseColor.BLACK); tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Description"])); tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Amount"])); tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Quantity"])); tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Total"])); tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_ReportedBy"])); int cont = 0; decimal costTotal = 0; foreach (var cost in costs) { tableCost.AddCell(ToolsPdf.DataCell(cost.Description, ToolsPdf.LayoutFonts.Times)); tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Amount, ToolsPdf.LayoutFonts.Times)); tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, ToolsPdf.LayoutFonts.Times)); tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Amount * cost.Quantity, ToolsPdf.LayoutFonts.Times)); tableCost.AddCell(ToolsPdf.DataCell(cost.Responsible.FullName, ToolsPdf.LayoutFonts.Times)); costTotal += cost.Amount * cost.Quantity; cont++; } tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_RegisterCount"].ToUpperInvariant() + ": " + cont.ToString(), ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderTop, Colspan = 2, Padding = 8f }); tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderTop, Colspan = 1, Padding = 8f, HorizontalAlignment = alignRight }); tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(costTotal), ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderTop, Colspan = 1, Padding = 8f, HorizontalAlignment = alignRight }); tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderTop, Colspan = 1, Padding = 8f, HorizontalAlignment = alignRight }); document.Add(tableCost); } #endregion } document.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf"); Response.ContentType = "application/pdf"; Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName); Response.Flush(); Response.Clear(); }
protected void Page_Load(object sender, EventArgs e) { var learningId = Convert.ToInt32(Request.QueryString["id"]); var companyId = Convert.ToInt32(Request.QueryString["companyId"]); var company = new Company(companyId); var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary<string, string>; var learning = new Learning(learningId, companyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(learning.Description); var fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_Learning"], formatedDescription, DateTime.Now); // FONTS var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts); } this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); this.arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK); var document = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55); var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create)); var pageEventHandler = new TwoColumnHeaderFooter() { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName), CompanyId = learning.CompanyId, CompanyName = company.Name, Title = dictionary["Item_Learning"] }; writer.PageEvent = pageEventHandler; var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER + Rectangle.BOTTOM_BORDER; document.Open(); #region Dades bàsiques // Ficha pincipal var table = new PdfPTable(6) { WidthPercentage = 100, HorizontalAlignment = 0 }; table.SetWidths(new float[] { 30f, 30f, 30f, 30f, 30f, 30f }); table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Course"])); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(learning.Description, descriptionFont)) { Border = 0, BackgroundColor = new iTS.BaseColor(255, 255, 255), Padding = 6f, PaddingTop = 4f, HorizontalAlignment = Rectangle.ALIGN_LEFT, Colspan = 5 }); table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_EstimatedDate"])); table.AddCell(ToolsPdf.DataCell(learning.DateEstimated, descriptionFont)); table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Hours"])); table.AddCell(ToolsPdf.DataCell(learning.Hours, descriptionFont)); string statusText = string.Empty; switch (learning.Status) { case 1: statusText = dictionary["Item_Learning_Status_Started"]; break; case 2: statusText = dictionary["Item_Learning_Status_Finished"]; break; case 3: statusText = dictionary["Item_Learning_Status_Evaluated"]; break; default: statusText = dictionary["Item_Learning_Status_InProgress"]; break; } table.AddCell(TitleLabel(dictionary["Item_Learning_ListHeader_Status"])); table.AddCell(ToolsPdf.DataCell(statusText, descriptionFont)); table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_StartDate"])); table.AddCell(ToolsPdf.DataCell(learning.RealStart, descriptionFont)); table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_EndDate"])); table.AddCell(ToolsPdf.DataCell(learning.RealFinish, descriptionFont)); table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Amount"])); table.AddCell(ToolsPdf.DataCellMoney(learning.Amount, descriptionFont)); table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Coach"])); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(learning.Master, descriptionFont)) { Border = 0, BackgroundColor = new iTS.BaseColor(255, 255, 255), Padding = 6f, PaddingTop = 4f, HorizontalAlignment = Rectangle.ALIGN_LEFT, Colspan = 5 }); // Objective table.AddCell(SeparationRow()); table.AddCell(TitleAreaCell(dictionary["Item_Learning_Objetive"])); table.AddCell(TextAreaCell(Environment.NewLine + learning.Objective, borderSides, Rectangle.ALIGN_LEFT, 6)); // Methodology table.AddCell(SeparationRow()); table.AddCell(TitleAreaCell(dictionary["Item_Learning_FieldLabel_Methodology"])); table.AddCell(TextAreaCell(Environment.NewLine + learning.Methodology, borderSides, Rectangle.ALIGN_LEFT, 6)); // Notes table.AddCell(SeparationRow()); table.AddCell(TitleAreaCell(dictionary["Item_Learning_FieldLabel_Notes"])); table.AddCell(TextAreaCell(Environment.NewLine + learning.Notes, borderSides, Rectangle.ALIGN_LEFT, 6)); document.Add(table); #endregion #region Asistentes var backgroundColor = new iTS.BaseColor(225, 225, 225); var rowPair = new iTS.BaseColor(255, 255, 255); var rowEven = new iTS.BaseColor(240, 240, 240); var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK); document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var tableAssistants = new iTSpdf.PdfPTable(3) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f }; tableAssistants.SetWidths(new float[] { 90f, 20f, 20f }); tableAssistants.AddCell(new PdfPCell(new Phrase(learning.Description, descriptionFont)) { Colspan = 5, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); tableAssistants.AddCell(ToolsPdf.HeaderCell(dictionary["Item_LearningAssistants"])); tableAssistants.AddCell(ToolsPdf.HeaderCell(dictionary["Item_LearningAssistant_Status_Done"])); tableAssistants.AddCell(ToolsPdf.HeaderCell(dictionary["Item_LearningAssistant_Status_Evaluated"])); int cont = 0; bool pair = false; var times = new iTS.Font(arial, 8, iTS.Font.NORMAL, iTS.BaseColor.BLACK); var timesBold = new iTS.Font(arial, 8, iTS.Font.BOLD, iTS.BaseColor.BLACK); learning.ObtainAssistance(); foreach (var assistance in learning.Assistance) { int border = 0; var lineBackground = pair ? rowEven : rowPair; tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(assistance.Employee.FullName, times)) { Border = border, BackgroundColor = lineBackground, Padding = ToolsPdf.PaddingTableCell, PaddingTop = ToolsPdf.PaddingTopTableCell }); string completedText = string.Empty; if (assistance.Completed.HasValue) { completedText = assistance.Completed.Value ? dictionary["Common_Yes"] : dictionary["Common_No"]; } tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(completedText, times)) { Border = border, BackgroundColor = lineBackground, HorizontalAlignment = Element.ALIGN_CENTER, Padding = ToolsPdf.PaddingTableCell, PaddingTop = ToolsPdf.PaddingTopTableCell }); string successText = string.Empty; if (assistance.Success.HasValue) { successText = assistance.Success.Value ? dictionary["Common_Yes"] : dictionary["Common_No"]; } tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(successText, times)) { Border = border, BackgroundColor = lineBackground, HorizontalAlignment = Element.ALIGN_CENTER, Padding = ToolsPdf.PaddingTableCell, PaddingTop = ToolsPdf.PaddingTopTableCell }); cont++; } // TotalRow if(learning.Assistance.Count == 0) { tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_LearningList_NoAssistants"], descriptionFont)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Padding = ToolsPdf.PaddingTableCell, PaddingTop = ToolsPdf.PaddingTopTableCell, Colspan = 3, HorizontalAlignment = Rectangle.ALIGN_CENTER }); } tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", dictionary["Common_RegisterCount"], cont), times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Padding = ToolsPdf.PaddingTableCell, PaddingTop = ToolsPdf.PaddingTopTableCell, Colspan = 3 }); document.Add(tableAssistants); #endregion document.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf"); Response.ContentType = "application/pdf"; Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName); Response.Flush(); Response.Clear(); }
public static ActionResult PDF( long equipmentId, int companyId, bool calibrationInternal, bool calibrationExternal, bool verificationInternal, bool verificationExternal, bool maintenanceInternal, bool maintenanceExternal, bool repairInternal, bool repairExternal, DateTime?dateFrom, DateTime?dateTo, string listOrder) { var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var equipment = Equipment.ById(equipmentId, companyId); var company = new Company(equipment.CompanyId); var data = HttpContext.Current.Session["EquipmentRecordsFilter"] as List <EquipmentRecord>; string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_Equipment"], equipment.Description, DateTime.Now); var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream( string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName), FileMode.Create)); writer.PageEvent = new TwoColumnHeaderFooter() { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName), CompanyId = equipment.CompanyId, CompanyName = company.Name, Title = dictionary["Item_Equipment_PDFTitle"].ToUpperInvariant() }; pdfDoc.Open(); var backgroundColor = new iTS.BaseColor(220, 220, 220); string periode = string.Empty; if (dateFrom.HasValue && dateTo.HasValue) { periode = string.Format( CultureInfo.InvariantCulture, @"Periode: {0:dd/MM/yyyy} - {1:dd/MM/yyyy}", dateFrom.Value, dateTo.Value); } else if (dateFrom.HasValue && dateTo == null) { periode = string.Format( CultureInfo.InvariantCulture, @"{1}: {0:dd/MM/yyyy}", dateFrom.Value, dictionary["Common_From"]); } else if (dateFrom == null && dateTo.HasValue) { periode = string.Format( CultureInfo.InvariantCulture, @"{1}: {0:dd/MM/yyyy}", dateTo.Value, dictionary["Common_To"]); } if (string.IsNullOrEmpty(periode)) { periode = dictionary["Common_PeriodAll"]; } var criteriatable = new iTSpdf.PdfPTable(2) { WidthPercentage = 100 }; criteriatable.SetWidths(new float[] { 25f, 250f }); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_Equipment"], ToolsPdf.LayoutFonts.TimesBold)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Description, ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Period"], ToolsPdf.LayoutFonts.TimesBold)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(periode, ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_Customer_Header_Type"], ToolsPdf.LayoutFonts.TimesBold)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }); string typeText = string.Empty; bool firstType = true; if (calibrationInternal) { firstType = false; typeText += dictionary["Item_EquipmentRecord_Filter_CalibrationInternal"]; } if (calibrationExternal) { if (!firstType) { typeText += " - "; } typeText += dictionary["Item_EquipmentRecord_Filter_CalibrationExternal"]; firstType = false; } if (verificationInternal) { if (!firstType) { typeText += " - "; } typeText += dictionary["Item_EquipmentRecord_Filter_VerificationInternal"]; firstType = false; } if (verificationExternal) { if (!firstType) { typeText += " - "; } typeText += dictionary["Item_EquipmentRecord_Filter_VerificationExternal"]; firstType = false; } if (maintenanceInternal) { if (!firstType) { typeText += " - "; } typeText += dictionary["Item_EquipmentRecord_Filter_MaintenanceInternal"]; firstType = false; } if (maintenanceExternal) { if (!firstType) { typeText += " - "; } typeText += dictionary["Item_EquipmentRecord_Filter_MaintenanceExternal"]; firstType = false; } if (repairInternal) { if (!firstType) { typeText += " - "; } typeText += dictionary["Item_EquipmentRecord_Filter_RepairInternal"]; firstType = false; } if (repairExternal) { if (!firstType) { typeText += " - "; } typeText += dictionary["Item_EquipmentRecord_Filter_RepairExternal"]; } criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(typeText, ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }); pdfDoc.Add(criteriatable); var table = new iTSpdf.PdfPTable(5) { WidthPercentage = 100, HorizontalAlignment = 0, SpacingBefore = 20f, SpacingAfter = 30f }; //relative col widths in proportions - 1/3 and 2/3 table.SetWidths(new float[] { 10f, 20f, 15f, 30f, 15f }); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_EquipmentRepair_HeaderList_Date"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_EquipmentRepair_HeaderList_Type"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_EquipmentRepair_HeaderList_Operation"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_EquipmentRepair_HeaderList_Responsible"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_EquipmentRepair_HeaderList_Cost"])); decimal totalCost = 0; int cont = 0; // Poner el tipo de registro diccionarizado foreach (var record in data) { record.RecordTypeText = dictionary[record.Item + "-" + (record.RecordType == 0 ? "Int" : "Ext")]; } switch (listOrder.ToUpperInvariant()) { default: case "TH0|ASC": data = data.OrderBy(d => d.Date).ToList(); break; case "TH0|DESC": data = data.OrderByDescending(d => d.Date).ToList(); break; case "TH1|ASC": data = data.OrderBy(d => d.RecordTypeText).ToList(); break; case "TH1|DESC": data = data.OrderByDescending(d => d.RecordTypeText).ToList(); break; case "TH2|ASC": data = data.OrderBy(d => d.Operation).ToList(); break; case "TH2|DESC": data = data.OrderByDescending(d => d.Operation).ToList(); break; case "TH3|ASC": data = data.OrderBy(d => d.Responsible.FullName).ToList(); break; case "TH3|DESC": data = data.OrderByDescending(d => d.Responsible.FullName).ToList(); break; case "TH4|ASC": data = data.OrderBy(d => d.Cost).ToList(); break; case "TH4|DESC": data = data.OrderByDescending(d => d.Cost).ToList(); break; } foreach (var equipmentRecord in data) { table.AddCell(ToolsPdf.DataCellCenter(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", equipmentRecord.Date), ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCell(equipmentRecord.RecordTypeText, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCell(equipmentRecord.Operation, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCell(equipmentRecord.Responsible.FullName, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCellMoney(equipmentRecord.Cost, ToolsPdf.LayoutFonts.Times)); if (equipmentRecord.Cost.HasValue) { totalCost += equipmentRecord.Cost.Value; } cont++; } string totalRegistros = string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", dictionary["Common_RegisterCount"], cont); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 2 }); table.AddCell(new PdfPCell(new iTS.Phrase(dictionary["Common_Total"], ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, HorizontalAlignment = iTS.Element.ALIGN_RIGHT, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Colspan = 2 }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#,##0.00}", totalCost), ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, HorizontalAlignment = iTS.Element.ALIGN_RIGHT }); pdfDoc.Add(table); pdfDoc.CloseDocument(); res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName)); return(res); }
public static ActionResult PDF(int companyId, string yearFrom, string yearTo, string mode, string listOrder, string textFilter) { var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var company = new Company(companyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(company.Name); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_LearningList"], formatedDescription, DateTime.Now); // FONTS string pathFonts = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts); } var headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream( string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName), FileMode.Create)); // evento para poner titulo y pie de página cada vez que salta de página writer.PageEvent = new TwoColumnHeaderFooter { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = user.UserName, CompanyId = company.Id, CompanyName = company.Name, Title = dictionary["Item_LearningList"].ToUpperInvariant() }; pdfDoc.Open(); var backgroundColor = new iTS.BaseColor(225, 225, 225); var rowEven = new iTS.BaseColor(240, 240, 240); var titleTable = new iTSpdf.PdfPTable(1); titleTable.SetWidths(new float[] { 50f }); titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont)) { HorizontalAlignment = iTS.Element.ALIGN_CENTER, Border = iTS.Rectangle.NO_BORDER }); //------ CRITERIA var criteriatable = new iTSpdf.PdfPTable(4) { WidthPercentage = 100 }; criteriatable.SetWidths(new float[] { 3f, 12f, 3f, 22f }); string periode = string.Empty; if (!string.IsNullOrEmpty(yearFrom) && yearFrom != "0" && !string.IsNullOrEmpty(yearTo) && yearTo != "0") { periode = yearFrom + " - " + yearTo; } else if (!string.IsNullOrEmpty(yearFrom) && yearFrom != "0") { periode = dictionary["Common_From"] + " " + yearFrom; } else if (!string.IsNullOrEmpty(yearTo) && yearTo != "0") { periode = dictionary["Item_Incident_List_Filter_To"] + " " + yearTo; } if (string.IsNullOrEmpty(periode)) { periode = dictionary["Item_Learning_Filter_AllPeriode"]; } ; string modeText = dictionary["Common_All_Female_Plural"]; if (!string.IsNullOrEmpty(mode)) { modeText = string.Empty; bool first = true; if (mode.IndexOf("0") != -1) { modeText += dictionary["Item_Learning_Status_InProgress"]; first = false; } if (mode.IndexOf("1") != -1) { if (!first) { modeText += ", "; } modeText += dictionary["Item_Learning_Status_Started"]; first = false; } if (mode.IndexOf("2") != -1) { if (!first) { modeText += ", "; } modeText += dictionary["Item_Learning_Status_Finished"]; first = false; } if (mode.IndexOf("3") != -1) { if (!first) { modeText += ", "; } modeText += dictionary["Item_Learning_Status_Evaluated"]; } } criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Period"] + " :", ToolsPdf.LayoutFonts.TimesBold)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(periode, ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Status"] + " :", ToolsPdf.LayoutFonts.TimesBold)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(modeText, ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }); if (!string.IsNullOrEmpty(textFilter)) { criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_PDF_Filter_Contains"] + " :", ToolsPdf.LayoutFonts.TimesBold)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(textFilter, ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f, Colspan = 5 }); } pdfDoc.Add(criteriatable); var table = new iTSpdf.PdfPTable(5) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f, SpacingAfter = 30f }; table.SetWidths(new float[] { 15f, 5f, 5f, 5f, 5f }); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Learning_FieldLabel_Course"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Learning_FieldLabel_EstimatedDate"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Learning_ListHeader_DateComplete"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Learning_FieldLabel_Status"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Learning_FieldLabel_Cost"])); int cont = 0; DateTime?yFrom = null; DateTime?yTo = null; if (!string.IsNullOrEmpty(yearFrom) && yearFrom != "0") { // yFrom = Tools.TextToDate(yearFrom); var parts = yearFrom.Split('/'); yFrom = new DateTime(Convert.ToInt32(parts[2]), Convert.ToInt32(parts[1]), Convert.ToInt32(parts[0])); } if (!string.IsNullOrEmpty(yearTo) && yearTo != "0") { // yTo = Tools.TextToDate(yearTo); var parts = yearTo.Split('/'); yTo = new DateTime(Convert.ToInt32(parts[2]), Convert.ToInt32(parts[1]), Convert.ToInt32(parts[0])); } var learningFilter = new LearningFilter(companyId) { Pendent = mode.IndexOf("0") != -1, Started = mode.IndexOf("1") != -1, Finished = mode.IndexOf("2") != -1, Evaluated = mode.IndexOf("3") != -1, YearFrom = yFrom, YearTo = yTo }; decimal totalCost = 0; int count = 0; var data = learningFilter.Filter().ToList(); if (!string.IsNullOrEmpty(listOrder)) { switch (listOrder.ToUpperInvariant()) { default: case "TH0|ASC": data = data.OrderBy(d => d.Description).ToList(); break; case "TH0|DESC": data = data.OrderByDescending(d => d.Description).ToList(); break; case "TH1|ASC": data = data.OrderBy(d => d.RealStart).ToList(); break; case "TH1|DESC": data = data.OrderByDescending(d => d.RealStart).ToList(); break; case "TH2|ASC": data = data.OrderBy(d => d.RealFinish).ToList(); break; case "TH2|DESC": data = data.OrderByDescending(d => d.RealFinish).ToList(); break; case "TH3|ASC": data = data.OrderBy(d => d.Status).ToList(); break; case "TH3|DESC": data = data.OrderByDescending(d => d.Status).ToList(); break; case "TH4|ASC": data = data.OrderBy(d => d.Amount).ToList(); break; case "TH4|DESC": data = data.OrderByDescending(d => d.Amount).ToList(); break; } } // aplicar filtro de texto if (!string.IsNullOrEmpty(textFilter)) { data = data.Where(d => d.Description.IndexOf(textFilter, StringComparison.OrdinalIgnoreCase) != -1).ToList(); } foreach (var learning in data) { count++; learning.ObtainAssistance(); string assist = string.Empty; bool first = true; foreach (var alumno in learning.Assistance) { if (first) { first = false; } else { assist += ", "; } assist += alumno.Employee.FullName; } if (string.IsNullOrEmpty(assist)) { assist = "(" + dictionary["Item_LearningList_NoAssistants"] + ")"; } int border = 0; table.AddCell(ToolsPdf.DataCell(learning.Description)); table.AddCell(ToolsPdf.DataCellCenter(learning.DateEstimated)); /* * string fecha = Tools.TranslatedMonth(learning.DateEstimated.Month, dictionary) + " " + learning.DateEstimated.Year; * table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(fecha, ToolsPdf.LayoutFonts.Times)) * { * Border = border, * Padding = 6f, * PaddingTop = 4f, * HorizontalAlignment = Rectangle.ALIGN_CENTER * }); */ if (learning.RealFinish != null) { if (learning.RealFinish.Value.Year == 1970) { table.AddCell(ToolsPdf.DataCell(string.Empty)); } else { table.AddCell(ToolsPdf.DataCellCenter(learning.RealFinish)); } } else { table.AddCell(ToolsPdf.DataCell(string.Empty)); } string statusText = string.Empty; switch (learning.Status) { default: case 0: statusText = dictionary["Item_Learning_Status_InProgress"]; break; case 1: statusText = dictionary["Item_Learning_Status_Started"]; break; case 2: statusText = dictionary["Item_Learning_Status_Finished"]; break; case 3: statusText = dictionary["Item_Learning_Status_Evaluated"]; break; } table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(statusText, ToolsPdf.LayoutFonts.Times)) { Border = border, Padding = ToolsPdf.PaddingTableCell, PaddingTop = ToolsPdf.PaddingTopTableCell, HorizontalAlignment = Rectangle.ALIGN_CENTER }); table.AddCell(ToolsPdf.DataCellMoney(learning.Amount)); totalCost += learning.Amount; cont++; } string totalRegistros = string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", dictionary["Common_RegisterCount"], count); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Padding = 6f, PaddingTop = 4f, Colspan = 3 }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant(), ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Padding = 6f, PaddingTop = 4f, HorizontalAlignment = 2 }); string totalText = string.Format("{0:#,##0.00}", totalCost); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalText, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Padding = 6f, PaddingTop = 4f, HorizontalAlignment = 2 }); pdfDoc.Add(table); pdfDoc.CloseDocument(); res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName)); return(res); }
public static ActionResult PDF( int companyId, bool externa, string from, bool interna, bool provider, bool status0, bool status1, bool status2, bool status3, bool status4, bool status5, string to, string filterText, string listOrder) { var source = "AuditoryExportList"; var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; Dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var company = new Company(companyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(company.Name); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf", Dictionary["Item_Auditories"], formatedDescription, DateTime.Now); var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream( string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName), FileMode.Create)); writer.PageEvent = new TwoColumnHeaderFooter { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = user.UserName, CompanyId = company.Id, CompanyName = company.Name, Title = Dictionary["Item_Auditories"].ToUpperInvariant() }; pdfDoc.Open(); var titleTable = new iTSpdf.PdfPTable(1); titleTable.SetWidths(new float[] { 50f }); titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", Dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont)) { HorizontalAlignment = iTS.Element.ALIGN_CENTER, Border = iTS.Rectangle.NO_BORDER }); //------ CRITERIA var criteriatable = new iTSpdf.PdfPTable(4) { WidthPercentage = 100 }; criteriatable.SetWidths(new float[] { 10f, 50f, 10f, 80f }); #region texts string criteriaProccess = Dictionary["Common_All_Male_Plural"]; string periode = string.Empty; if (!string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to)) { periode = Dictionary["Item_Incident_List_Filter_From"] + " " + from; } else if (string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to)) { periode = Dictionary["Item_Incident_List_Filter_To"] + " " + to; } else if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to)) { periode = from + " - " + to; } else { periode = Dictionary["Common_All_Male"]; } string typetext = string.Empty; bool firtsType = false; if (interna) { typetext += Dictionary["Item_Adutory_Type_Label_0"]; firtsType = false; } if (externa) { typetext += firtsType ? string.Empty : ", "; typetext += Dictionary["Item_Adutory_Type_Label_1"]; firtsType = false; } if (provider) { typetext += firtsType ? string.Empty : ", "; typetext += Dictionary["Item_Adutory_Type_Label_2"]; } if (firtsType) { typetext = Dictionary["Common_All_Female_Plural"]; } string statustext = string.Empty; bool firstStatus = false; if (status0) { statustext += Dictionary["Item_Adutory_Status_Label_0"]; firstStatus = false; } if (status1) { statustext += firstStatus ? string.Empty : ", "; statustext += Dictionary["Item_Adutory_Status_Label_1"]; firstStatus = false; } if (status2) { statustext += firstStatus ? string.Empty : ", "; statustext += Dictionary["Item_Adutory_Status_Label_2"]; firstStatus = false; } if (status3) { statustext += firstStatus ? string.Empty : ", "; statustext += Dictionary["Item_Adutory_Status_Label_3"]; firstStatus = false; } if (status4) { statustext += firstStatus ? string.Empty : ", "; statustext += Dictionary["Item_Adutory_Status_Label_4"]; firstStatus = false; } if (status5) { statustext += firstStatus ? string.Empty : ", "; statustext += Dictionary["Item_Adutory_Status_Label_5"]; } if (firstStatus) { statustext = Dictionary["Common_All_Male_Plural"]; } #endregion criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(Dictionary["Common_Period"])); criteriatable.AddCell(ToolsPdf.CriteriaCellData(periode)); criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(Dictionary["Item_Auditory_Filter_Type"])); criteriatable.AddCell(ToolsPdf.CriteriaCellData(typetext)); criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(Dictionary["Item_Auditory_Filter_Status"])); criteriatable.AddCell(ToolsPdf.CriteriaCellData(statustext)); if (!string.IsNullOrEmpty(filterText)) { criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(Dictionary["Common_PDF_Filter_Contains"])); criteriatable.AddCell(ToolsPdf.CriteriaCellData(filterText)); } else { criteriatable.AddCell(ToolsPdf.CriteriaCellData(string.Empty)); criteriatable.AddCell(ToolsPdf.CriteriaCellData(string.Empty)); } pdfDoc.Add(criteriatable); //--------------------------- var tableWidths = new float[] { 40f, 10f, 10f, 10f, 10f, 10f }; var table = new iTSpdf.PdfPTable(tableWidths.Length) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f, SpacingAfter = 30f }; table.SetWidths(tableWidths); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_ListHeader_Name"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_Filter_Type"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_ListHeader_Status"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_ListHeader_Planned"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_ListHeader_Closed"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_ListHeader_Ammount"])); int cont = 0; var data = new List <Auditory>(); using (var cmd = new SqlCommand("Auditory_Filter")) { using (var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cns"].ConnectionString)) { cmd.Connection = cnn; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(DataParameter.Input("@CompanyId", companyId)); cmd.Parameters.Add(DataParameter.Input("@From", from)); cmd.Parameters.Add(DataParameter.Input("@To", to)); cmd.Parameters.Add(DataParameter.Input("@TypeInterna", interna)); cmd.Parameters.Add(DataParameter.Input("@TypeExterna", externa)); cmd.Parameters.Add(DataParameter.Input("@TypeProveedor", provider)); cmd.Parameters.Add(DataParameter.Input("@Status0", status0)); cmd.Parameters.Add(DataParameter.Input("@Status1", status1)); cmd.Parameters.Add(DataParameter.Input("@Status2", status2)); cmd.Parameters.Add(DataParameter.Input("@Status3", status3)); cmd.Parameters.Add(DataParameter.Input("@Status4", status4)); cmd.Parameters.Add(DataParameter.Input("@Status5", status5)); try { cmd.Connection.Open(); using (var rdr = cmd.ExecuteReader()) { while (rdr.Read()) { var newAuditory = new Auditory { Id = rdr.GetInt64(ColumnsAuditoryFilter.Id), Description = rdr.GetString(ColumnsAuditoryFilter.Nombre), Amount = rdr.GetDecimal(ColumnsAuditoryFilter.Amount), Status = rdr.GetInt32(ColumnsAuditoryFilter.Status), Type = rdr.GetInt32(ColumnsAuditoryFilter.Type) }; if (!rdr.IsDBNull(ColumnsAuditoryFilter.PlannedOn)) { newAuditory.PlannedOn = rdr.GetDateTime(ColumnsAuditoryFilter.PlannedOn); } if (!rdr.IsDBNull(ColumnsAuditoryFilter.ValidatedOn)) { newAuditory.ValidatedOn = rdr.GetDateTime(ColumnsAuditoryFilter.ValidatedOn); } data.Add(newAuditory); } } } catch (SqlException ex) { ExceptionManager.Trace(ex, source); } catch (FormatException ex) { ExceptionManager.Trace(ex, source); } catch (NullReferenceException ex) { ExceptionManager.Trace(ex, source); } finally { if (cmd.Connection.State != ConnectionState.Closed) { cmd.Connection.Close(); } } } } switch (listOrder.ToUpperInvariant()) { default: case "TH1|ASC": data = data.OrderBy(d => d.Status).ToList(); break; case "TH1|DESC": data = data.OrderByDescending(d => d.Status).ToList(); break; case "TH2|ASC": data = data.OrderBy(d => d.Description).ToList(); break; case "TH2|DESC": data = data.OrderByDescending(d => d.Description).ToList(); break; case "TH3|ASC": data = data.OrderBy(d => d.PlannedOn).ToList(); break; case "TH3|DESC": data = data.OrderByDescending(d => d.PlannedOn).ToList(); break; case "TH4|ASC": data = data.OrderBy(d => d.ValidatedOn).ToList(); break; case "TH4|DESC": data = data.OrderByDescending(d => d.ValidatedOn).ToList(); break; case "TH5|ASC": data = data.OrderBy(d => d.Amount).ToList(); break; case "TH5|DESC": data = data.OrderByDescending(d => d.Amount).ToList(); break; } foreach (var auditory in data) { if (!string.IsNullOrEmpty(filterText)) { var match = auditory.Description; if (match.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) == -1) { continue; } } cont++; string statustextCell = string.Empty; switch (auditory.Status) { case 0: statustextCell = Dictionary["Item_Adutory_Status_Label_0"]; break; case 1: statustextCell = Dictionary["Item_Adutory_Status_Label_1"]; break; case 2: statustextCell = Dictionary["Item_Adutory_Status_Label_2"]; break; case 3: statustextCell = Dictionary["Item_Adutory_Status_Label_3"]; break; case 4: statustextCell = Dictionary["Item_Adutory_Status_Label_4"]; break; case 5: statustextCell = Dictionary["Item_Adutory_Status_Label_5"]; break; } string typetextCell = string.Empty; switch (auditory.Type) { case 0: typetextCell = Dictionary["Item_Adutory_Type_Label_0"]; break; case 1: typetextCell = Dictionary["Item_Adutory_Type_Label_1"]; break; case 2: typetextCell = Dictionary["Item_Adutory_Type_Label_2"]; break; } table.AddCell(ToolsPdf.DataCell(auditory.Description)); table.AddCell(ToolsPdf.DataCellCenter(typetextCell)); table.AddCell(ToolsPdf.DataCellCenter(statustextCell)); table.AddCell(ToolsPdf.DataCellCenter(auditory.PlannedOn)); table.AddCell(ToolsPdf.DataCellCenter(auditory.ValidatedOn)); table.AddCell(ToolsPdf.DataCellMoney(auditory.Amount)); } table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", Dictionary["Common_RegisterCount"], cont), ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, Padding = 6f, PaddingTop = 4f, Colspan = 4 }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, Colspan = 4 }); pdfDoc.Add(table); pdfDoc.CloseDocument(); res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName)); return(res); }
public static ActionResult PDF( int companyId, DateTime?from, DateTime?to, int status, string listOrder, string filterText) { var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var company = new Company(companyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(company.Name); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_Objetivo_List"], formatedDescription, DateTime.Now); // FONTS string pathFonts = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts); } var headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream( string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName), FileMode.Create)); writer.PageEvent = new TwoColumnHeaderFooter() { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = user.UserName, CompanyId = company.Id, CompanyName = company.Name, Title = dictionary["Item_Objetivo_List"].ToUpperInvariant() }; pdfDoc.Open(); var rowEven = new iTS.BaseColor(240, 240, 240); var titleTable = new iTSpdf.PdfPTable(1); titleTable.SetWidths(new float[] { 50f }); titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont)) { HorizontalAlignment = iTS.Element.ALIGN_CENTER, Border = iTS.Rectangle.NO_BORDER }); #region Criteria var criteriatable = new iTSpdf.PdfPTable(4) { WidthPercentage = 100 }; criteriatable.SetWidths(new float[] { 20f, 50f, 20f, 150f }); #region texts string periode = string.Empty; if (from.HasValue && to == null) { periode = string.Format(CultureInfo.InvariantCulture, @"{0} {1:dd/MM/yyyy}", dictionary["Item_IncidentAction_List_Filter_From"], from); } else if (from == null && to.HasValue) { periode = string.Format(CultureInfo.InvariantCulture, @"{0} {1:dd/MM/yyyy}", dictionary["Item_IncidentAction_List_Filter_To"], to); } else if (from.HasValue && to.HasValue) { periode = string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy} {1:dd/MM/yyyy}", from, to); } else { periode = dictionary["Common_All_Male"]; } string statusText = dictionary["Common_All"]; if (status == 1) { statusText = dictionary["Item_ObjetivoAction_List_Filter_ShowActive"]; } if (status == 2) { statusText = dictionary["Item_ObjetivoAction_List_Filter_ShowClosed"]; } #endregion ToolsPdf.AddCriteria(criteriatable, dictionary["Common_Period"], periode); ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Header_Status"], statusText); if (!string.IsNullOrEmpty(filterText)) { ToolsPdf.AddCriteria(criteriatable, dictionary["Common_PDF_Filter_Contains"], filterText); } pdfDoc.Add(criteriatable); #endregion var table = new iTSpdf.PdfPTable(5) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f, SpacingAfter = 30f }; table.SetWidths(new float[] { 7f, 50f, 30f, 12f, 12f }); table.AddCell(ToolsPdf.HeaderCell(dictionary["Common_Status"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_Name"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_Responsible"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_StartDate"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_PreviewEndDate"])); int cont = 0; var data = Objetivo.Filter(companyId, from, to, status).ToList(); foreach (var item in data) { if (!item.Objetivo.EndDate.HasValue) { item.Objetivo.EndDate = item.Objetivo.PreviewEndDate; } } switch (listOrder.ToUpperInvariant()) { default: case "TH0|ASC": data = data.OrderBy(d => d.Objetivo.Name).ToList(); break; case "TH0|DESC": data = data.OrderByDescending(d => d.Objetivo.Name).ToList(); break; case "TH1|ASC": data = data.OrderBy(d => d.Objetivo.Responsible.FullName).ToList(); break; case "TH1|DESC": data = data.OrderByDescending(d => d.Objetivo.Responsible.FullName).ToList(); break; case "TH2|ASC": data = data.OrderBy(d => d.Objetivo.StartDate).ToList(); break; case "TH2|DESC": data = data.OrderByDescending(d => d.Objetivo.StartDate).ToList(); break; case "TH3|ASC": data = data.OrderBy(d => d.Objetivo.EndDate).ToList(); break; case "TH3|DESC": data = data.OrderByDescending(d => d.Objetivo.EndDate).ToList(); break; } cont = 0; foreach (var item in data) { if (!string.IsNullOrEmpty(filterText)) { var show = false; if (item.Objetivo.Name.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) != -1) { show = true; } if (item.Objetivo.Responsible.FullName.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) != -1) { show = true; } if (!show) { continue; } } string endDateText = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", item.Objetivo.PreviewEndDate); if (item.Objetivo.EndDate.HasValue) { endDateText = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", item.Objetivo.EndDate); } table.AddCell(ToolsPdf.DataCell(item.Objetivo.Active ? dictionary["Common_Active"] : dictionary["Common_Inactve"], ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCell(item.Objetivo.Name, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCell(item.Objetivo.Responsible.FullName, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCellCenter(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", item.Objetivo.StartDate), ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCellCenter(endDateText, ToolsPdf.LayoutFonts.Times)); cont++; } string totalRegistros = string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", dictionary["Common_RegisterCount"], cont); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Padding = 6f, PaddingTop = 4f, Colspan = 2 }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Colspan = 3 }); pdfDoc.Add(table); pdfDoc.CloseDocument(); res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName)); return(res); }
protected void Page_Load(object sender, EventArgs e) { long auditoryId = Convert.ToInt64(Request.QueryString["id"]); int companyId = Convert.ToInt32(Request.QueryString["companyId"]); var company = new Company(companyId); var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var auditory = Auditory.ById(auditoryId, user.CompanyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } string formatedDescription = auditory.Description.Replace("?", string.Empty); formatedDescription = formatedDescription.Replace("#", string.Empty); formatedDescription = formatedDescription.Replace("/", string.Empty); formatedDescription = formatedDescription.Replace("\\", string.Empty); formatedDescription = formatedDescription.Replace(":", string.Empty); formatedDescription = formatedDescription.Replace(";", string.Empty); formatedDescription = formatedDescription.Replace(".", string.Empty); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_Auditory"], formatedDescription, DateTime.Now); // FONTS var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts); } this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); this.arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK); var document = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55); var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create)); var pageEventHandler = new TwoColumnHeaderFooter() { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName), CompanyId = auditory.CompanyId, CompanyName = company.Name, Title = dictionary["Item_Auditory"] }; writer.PageEvent = pageEventHandler; document.Open(); #region Dades bàsiques // Ficha pincipal var table = new PdfPTable(4) { WidthPercentage = 100, HorizontalAlignment = 0 }; table.SetWidths(new float[] { 30f, 50f, 30f, 50f }); table.AddCell(new PdfPCell(new Phrase(auditory.Description, descriptionFont)) { Colspan = 4, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Type"])); table.AddCell(TitleData(dictionary["Item_Adutory_Type_Label_" + auditory.Type.ToString()])); if (auditory.Provider.Id > 0) { table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Provider"])); table.AddCell(TitleData(auditory.Provider.Description)); } else if (auditory.Customer.Id > 0) { table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Customer"])); table.AddCell(TitleData(auditory.Customer.Description)); } else { table.AddCell(TitleData(string.Empty, 2)); } table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Rules"])); var rulesText = string.Empty; bool firstRule = true; foreach (var rule in auditory.Rules) { if (firstRule) { firstRule = false; } else { rulesText += ", "; } rulesText += rule.Description; } table.AddCell(TitleData(rulesText, 3)); table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_InternalResponsible"])); table.AddCell(TitleData(auditory.InternalResponsible.FullName, 3)); //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_PannedDate"])); //table.AddCell(TitleData(previewDateText)); table.AddCell(TitleLabel(dictionary["Item_Audiotry_PDF_Planned"])); if (auditory.PlannedBy.Id > 0) { var planningText = string.Format( CultureInfo.InvariantCulture, "{0} {1} {2}", auditory.PlannedBy.FullName, dictionary["Item_Auditory_PDF_Label_date"], string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.PlannedOn) ?? "-"); table.AddCell(TitleData(planningText, 3)); } else { table.AddCell(TitleData(string.Empty, 3)); } //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_PlanningDate"])); //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.PlannedOn) ?? "-")); table.AddCell(TitleLabel(dictionary["Item_Auditory_PDF_Closing"])); if (auditory.ClosedBy.Employee.Id > 0) { var closedText = string.Format( CultureInfo.InvariantCulture, "{0} {1} {2}", auditory.ClosedBy.Employee.FullName, dictionary["Item_Auditory_PDF_Label_date"], string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ClosedOn) ?? "-"); table.AddCell(TitleData(closedText, 3)); } else { table.AddCell(TitleData(string.Empty, 3)); } //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_ClosedOn"])); //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ClosedOn) ?? "-")); table.AddCell(TitleLabel(dictionary["Item_Auditory_PDF_Validation"])); if (auditory.ValidatedBy.Id > 0) { var validatedText = string.Format( CultureInfo.InvariantCulture, "{0} {1} {2}", auditory.ValidatedBy.FullName, dictionary["Item_Auditory_PDF_Label_date"], string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ValidatedOn) ?? "-"); table.AddCell(TitleData(validatedText, 3)); } else { table.AddCell(TitleData(string.Empty, 3)); } //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_ValidatedOn"])); //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ValidatedOn) ?? "-")); table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Address"])); table.AddCell(TitleData(auditory.EnterpriseAddress, 3)); table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_AuditorTeam"])); table.AddCell(TitleData(auditory.AuditorTeam, 3)); table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Notes"])); table.AddCell(TitleData(string.IsNullOrEmpty(auditory.Notes.Trim()) ? "-" : auditory.Notes, 3)); document.Add(table); #endregion if (auditory.Status > 3) { document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var widthsActions = new float[] { 5f, 30f, 5f }; var tableAccions = new PdfPTable(widthsActions.Length) { WidthPercentage = 100, HorizontalAlignment = 0 }; tableAccions.SetWidths(widthsActions); tableAccions.AddCell(new PdfPCell(new Phrase(dictionary["Item_IncidentActions"], descriptionFont)) { Colspan = 3, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); tableAccions.AddCell(ToolsPdf.HeaderCell(dictionary["Tipo"])); tableAccions.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction"])); tableAccions.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"])); var accions = IncidentAction.ByAuditoryId(auditory.Id, auditory.CompanyId); foreach (var accio in accions) { tableAccions.AddCell(ToolsPdf.DataCell(dictionary["Item_IncidentAction_Type" + accio.ActionType.ToString()])); tableAccions.AddCell(ToolsPdf.DataCell(accio.Description)); tableAccions.AddCell(ToolsPdf.DataCell(accio.WhatHappenedOn)); } document.Add(tableAccions); } document.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf"); Response.ContentType = "application/pdf"; Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName); Response.Flush(); Response.Clear(); }
public static ActionResult PDF( int companyId, int indicatorType, DateTime?from, DateTime?to, int?processId, int?processTypeId, int?targetId, int status, string listOrder) { var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var company = new Company(companyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(company.Name); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_Indicador_List"], formatedDescription, DateTime.Now); var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream( string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName), FileMode.Create)); writer.PageEvent = new TwoColumnHeaderFooter { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = user.UserName, CompanyId = company.Id, CompanyName = company.Name, Title = dictionary["Item_Indicador_List"].ToUpperInvariant() }; pdfDoc.Open(); var backgroundColor = new iTS.BaseColor(225, 225, 225); var titleTable = new iTSpdf.PdfPTable(1); titleTable.SetWidths(new float[] { 50f }); titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont)) { HorizontalAlignment = iTS.Element.ALIGN_CENTER, Border = iTS.Rectangle.NO_BORDER }); var table = new iTSpdf.PdfPTable(6) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f, SpacingAfter = 30f }; //------ CRITERIA var criteriatable = new iTSpdf.PdfPTable(6) { WidthPercentage = 100 }; criteriatable.SetWidths(new float[] { 20f, 50f, 25f, 50f, 20f, 150f }); var criteriaBlank = new iTSpdf.PdfPCell(new iTS.Phrase(".", ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = ToolsPdf.PaddingTopTableCell, PaddingTop = ToolsPdf.PaddingTopCriteriaCell }; string periode = string.Empty; if (from.HasValue && to == null) { periode = string.Format(CultureInfo.InvariantCulture, @"{0} {1:dd/MM/yyyy}", dictionary["Item_IncidentAction_List_Filter_From"], from); } else if (from == null && to.HasValue) { periode = string.Format(CultureInfo.InvariantCulture, @"{0} {1:dd/MM/yyyy}", dictionary["Item_IncidentAction_List_Filter_To"], to); } else if (from.HasValue && to.HasValue) { periode = string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy} {1:dd/MM/yyyy}", from, to); } else { periode = dictionary["Common_All_Male"]; } criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(dictionary["Common_Period"])); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(periode, ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = ToolsPdf.PaddingTopTableCell, PaddingTop = ToolsPdf.PaddingTopCriteriaCell }); criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(dictionary["Item_IncidentAction_Header_Status"])); string statusText = dictionary["Common_All"]; if (status == 1) { statusText = dictionary["Item_ObjetivoAction_List_Filter_ShowActive"]; } if (status == 2) { statusText = dictionary["Item_ObjetivoAction_List_Filter_ShowClosed"]; } criteriatable.AddCell(ToolsPdf.CriteriaCellData(statusText)); criteriatable.AddCell(criteriaBlank); criteriatable.AddCell(criteriaBlank); criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(dictionary["Item_Indicaddor_Filter_TypeLabel"])); string indicadorTypeText = string.Empty; switch (indicatorType) { case 0: indicadorTypeText = dictionary["Common_All_Male_Plural"]; break; case 1: indicadorTypeText = dictionary["Item_Indicaddor_Filter_TypeProcess"]; break; case 2: indicadorTypeText = dictionary["Item_Indicaddor_Filter_TypeObjetivo"]; break; default: indicadorTypeText = dictionary["Common_All_Male_Plural"]; break; } criteriatable.AddCell(ToolsPdf.CriteriaCellData(indicadorTypeText)); switch (indicatorType) { case 1: string processText = dictionary["Common_All_Male_Plural"]; if (processId.HasValue) { processText = new Process(processId.Value, companyId).Description; } string processTypeCriteriaText = dictionary["Common_All_Male_Plural"]; if (processTypeId.HasValue) { switch (processTypeId.Value) { case 1: processTypeCriteriaText = dictionary["Item_ProcessType_Name_Principal"]; break; case 2: processTypeCriteriaText = dictionary["Item_ProcessType_Name_Support"]; break; case 3: processTypeCriteriaText = dictionary["Item_ProcessType_Name_Estrategic"]; break; default: processTypeCriteriaText = string.Empty; foreach (var t in ProcessType.ObtainByCompany(companyId, dictionary)) { if (t.Id == processTypeId) { processTypeCriteriaText = t.Description; } } break; } } criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(dictionary["Item_Process"])); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(processText, ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = ToolsPdf.PaddingTopTableCell, PaddingTop = ToolsPdf.PaddingTopCriteriaCell }); criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(dictionary["Item_ProcessType"])); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(processTypeCriteriaText, ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = ToolsPdf.PaddingTopTableCell, PaddingTop = ToolsPdf.PaddingTopCriteriaCell }); break; case 2: string objetivoText = dictionary["Common_All_Male_Plural"]; if (targetId.HasValue) { objetivoText = Objetivo.ById(targetId.Value, companyId).Name; } criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(dictionary["Item_Objetivo"])); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(objetivoText, ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = ToolsPdf.PaddingTopTableCell, PaddingTop = ToolsPdf.PaddingTopCriteriaCell, Colspan = 3 }); break; default: criteriatable.AddCell(criteriaBlank); criteriatable.AddCell(criteriaBlank); criteriatable.AddCell(criteriaBlank); criteriatable.AddCell(criteriaBlank); break; } pdfDoc.Add(criteriatable); //--------------------------- table.SetWidths(new float[] { 7f, 30f, 10f, 30f, 10f, 10f });; table.AddCell(ToolsPdf.HeaderCell(dictionary["Common_Status"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_Header_Description"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_Header_StartDate"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_Header_Process"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_Header_ProcessType"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_Header_ObjetivoResponsible"])); var tipoProcesos = ProcessType.ObtainByCompany(company.Id, dictionary); int cont = 0; var data = Indicador.Filter(companyId, indicatorType, from, to, processId, processTypeId, targetId, status).ToList(); foreach (var item in data) { string processTypeText = string.Empty; switch (item.Proceso.ProcessType) { case 1: item.Proceso.Work = dictionary["Item_ProcessType_Name_Principal"]; break; case 2: item.Proceso.Work = dictionary["Item_ProcessType_Name_Support"]; break; case 3: item.Proceso.Work = dictionary["Item_ProcessType_Name_Estrategic"]; break; default: item.Proceso.Work = tipoProcesos.First(tp => tp.Id == item.Proceso.ProcessType).Description; break; } } switch (listOrder.ToUpperInvariant()) { default: case "TH0|ASC": data = data.OrderBy(d => d.Indicador.Description).ToList(); break; case "TH0|DESC": data = data.OrderByDescending(d => d.Indicador.Description).ToList(); break; case "TH1|ASC": data = data.OrderBy(d => d.StartDate).ToList(); break; case "TH1|DESC": data = data.OrderByDescending(d => d.StartDate).ToList(); break; case "TH2|ASC": data = data.OrderBy(d => d.Proceso.Description).ToList(); break; case "TH2|DESC": data = data.OrderByDescending(d => d.Proceso.Description).ToList(); break; case "TH3|ASC": data = data.OrderBy(d => d.Proceso.Work).ToList(); break; case "TH3|DESC": data = data.OrderByDescending(d => d.Proceso.Work).ToList(); break; case "TH4|ASC": data = data.OrderBy(d => d.ObjetivoResponsible).ToList(); break; case "TH4|DESC": data = data.OrderByDescending(d => d.ObjetivoResponsible).ToList(); break; } foreach (var item in data) { table.AddCell(ToolsPdf.DataCell(item.Status == 0 ? dictionary["Common_Active"] : dictionary["Common_Inactive"], ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCell(item.Indicador.Description, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCell(item.StartDate, ToolsPdf.LayoutFonts.Times, Rectangle.ALIGN_CENTER)); table.AddCell(ToolsPdf.DataCell(item.Proceso.Description, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCell(item.Proceso.Work, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCell(item.ObjetivoResponsible, ToolsPdf.LayoutFonts.Times)); cont++; } table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", dictionary["Common_RegisterCount"], cont), ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = backgroundColor, Padding = ToolsPdf.PaddingTopTableCell, PaddingTop = ToolsPdf.PaddingTopCriteriaCell, Colspan = 2 }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = backgroundColor, Colspan = 4 }); pdfDoc.Add(table); pdfDoc.CloseDocument(); res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName)); return(res); }
public static ActionResult PDF( int companyId, string from, string to, bool statusIdnetified, bool statusAnalyzed, bool statusInProgress, bool statusClose, int origin, int departmentId, int providerId, int customerId, string listOrder, string filterText) { var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var company = new Company(companyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(company.Name); var fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_IncidentList"], formatedDescription, DateTime.Now); // FONTS var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts); } var headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream( string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName), FileMode.Create)); writer.PageEvent = new TwoColumnHeaderFooter() { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = user.UserName, CompanyId = company.Id, CompanyName = company.Name, Title = dictionary["Item_IncidentList"].ToUpperInvariant() }; pdfDoc.Open(); var backgroundColor = new iTS.BaseColor(225, 225, 225); var rowPair = new iTS.BaseColor(255, 255, 255); var rowEven = new iTS.BaseColor(240, 240, 240); // ------------ FONTS var awesomeFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\fontawesome-webfont.ttf", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK); criteriaFont = new iTS.Font(arial, 10, iTS.Font.NORMAL, iTS.BaseColor.BLACK); var titleFont = new iTS.Font(arial, 18, iTS.Font.BOLD, iTS.BaseColor.BLACK); var symbolFont = new iTS.Font(awesomeFont, 8, iTS.Font.NORMAL, iTS.BaseColor.BLACK); var fontAwesomeIcon = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\fontawesome-webfont.ttf", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); fontAwe = new Font(fontAwesomeIcon, 10); // ------------------- var titleTable = new iTSpdf.PdfPTable(1); titleTable.SetWidths(new float[] { 50f }); titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), titleFont)) { HorizontalAlignment = iTS.Element.ALIGN_CENTER, Border = iTS.Rectangle.NO_BORDER }); var borderNone = iTS.Rectangle.NO_BORDER; #region Criteria var criteriatable = new iTSpdf.PdfPTable(2) { WidthPercentage = 100 }; criteriatable.SetWidths(new float[] { 8f, 50f }); #region texts var criteriaOrigin = dictionary["Item_Incident_Origin0"]; if (origin == 1) { if (departmentId > 0) { var department = Department.ById(departmentId, companyId); criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Incident_Origin1"], department.Description); } else { criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - ({1})", dictionary["Item_Incident_Origin1"], dictionary["Common_All_Male_Plural"]); } } if (origin == 2) { if (providerId > 0) { var provider = Provider.ById(providerId, companyId); criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Incident_Origin2"], provider.Description); } else { criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - ({1})", dictionary["Item_Incident_Origin2"], dictionary["Common_All_Male_Plural"]); } } if (origin == 3) { if (customerId > 0) { var customer = Customer.ById(customerId, companyId); criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Incident_Origin3"], customer.Description); } else { criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - ({1})", dictionary["Item_Incident_Origin3"], dictionary["Common_All_Male_Plural"]); } } var periode = string.Empty; if (!string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to)) { periode = dictionary["Item_Incident_List_Filter_From"] + " " + from; } else if (string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to)) { periode = dictionary["Item_Incident_List_Filter_To"] + " " + to; } else if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to)) { periode = from + " " + to; } else { periode = dictionary["Common_All_Male"]; } var typetext = string.Empty; var firstType = false; var statusText = string.Empty; var firstStatus = true; if (statusIdnetified) { firstStatus = false; statusText += dictionary["Item_IndicentAction_Status1"]; } if (statusAnalyzed) { if (!firstStatus) { statusText += " - "; } statusText += dictionary["Item_IndicentAction_Status2"]; firstStatus = false; } if (statusInProgress) { if (!firstStatus) { statusText += " - "; } statusText += dictionary["Item_IndicentAction_Status3"]; firstType = false; } if (statusClose) { if (!firstType) { statusText += " - "; } statusText += dictionary["Item_IndicentAction_Status4"]; firstType = false; } #endregion ToolsPdf.AddCriteria(criteriatable, dictionary["Common_Period"], periode); if (!string.IsNullOrEmpty(filterText)) //{ // ToolsPdf.AddCriteria(criteriatable, string.Empty, string.Empty); //} //else { ToolsPdf.AddCriteria(criteriatable, dictionary["Common_PDF_Filter_Contains"], filterText); } ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Header_Status"], statusText); ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Header_Origin"], criteriaOrigin); pdfDoc.Add(criteriatable); #endregion var table = new iTSpdf.PdfPTable(8) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f, SpacingAfter = 30f }; table.SetWidths(new float[] { 5f, 35f, 10f, 10f, 20f, 8f, 10f, 10f }); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Label_Number"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Description"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Open"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Status"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Origin"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_ActionNumber"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Cost"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Close"])); int cont = 0; decimal totalCost = 0; var data = HttpContext.Current.Session["IncidentFilterData"] as List <IncidentFilterItem>; bool pair = false; foreach (IncidentFilterItem item in data) { var originValue = string.Empty; if (!string.IsNullOrEmpty(item.Customer.Description)) { originValue = item.Customer.Description; } if (!string.IsNullOrEmpty(item.Provider.Description)) { originValue = item.Provider.Description; } if (!string.IsNullOrEmpty(item.Department.Description)) { originValue = item.Department.Description; } item.OriginText = originValue; } switch (listOrder.ToUpperInvariant()) { default: case "TH0|ASC": data = data.OrderBy(d => d.Description).ToList(); break; case "TH0|DESC": data = data.OrderByDescending(d => d.Description).ToList(); break; case "TH1|ASC": data = data.OrderBy(d => d.Open).ToList(); break; case "TH1|DESC": data = data.OrderByDescending(d => d.Open).ToList(); break; case "TH3|ASC": data = data.OrderBy(d => d.OriginText).ToList(); break; case "TH3|DESC": data = data.OrderByDescending(d => d.OriginText).ToList(); break; case "TH4|ASC": data = data.OrderBy(d => d.Action.Description).ToList(); break; case "TH4|DESC": data = data.OrderByDescending(d => d.Action.Description).ToList(); break; case "TH5|ASC": data = data.OrderBy(d => d.Amount).ToList(); break; case "TH5|DESC": data = data.OrderByDescending(d => d.Amount).ToList(); break; case "TH6|ASC": data = data.OrderBy(d => d.Close).ToList(); break; case "TH6|DESC": data = data.OrderByDescending(d => d.Close).ToList(); break; } foreach (var incidentFilter in data) { if (!string.IsNullOrEmpty(filterText)) { var match = incidentFilter.Description; match += "|" + incidentFilter.Code; match += "|" + incidentFilter.Customer.Description; match += "|" + incidentFilter.Provider.Description; match += "|" + incidentFilter.Department.Description; if (match.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) == -1) { continue; } } cont++; totalCost += incidentFilter.Amount; var incident = Incident.GetById(incidentFilter.Id, companyId); var action = IncidentAction.ByIncidentId(incident.Id, companyId); var lineBackground = pair ? rowEven : rowPair; // pair = !pair; var statustext = string.Empty; switch (incidentFilter.Status) { case 1: statustext = dictionary["Item_IndicentAction_Status1"]; break; case 2: statustext = dictionary["Item_IndicentAction_Status2"]; break; case 3: statustext = dictionary["Item_IndicentAction_Status3"]; break; case 4: statustext = dictionary["Item_IndicentAction_Status4"]; break; default: statusText = string.Empty; break; } var actionDescription = string.Empty; if (!string.IsNullOrEmpty(action.Description)) { actionDescription = dictionary["Common_Yes"]; } var originText = string.Empty; switch (incidentFilter.Origin) { case 1: originText = dictionary["Item_IncidentAction_Origin1"]; break; case 2: originText = dictionary["Item_IncidentAction_Origin2"]; break; case 3: originText = dictionary["Item_IncidentAction_Origin3"]; break; case 4: originText = dictionary["Item_IncidentAction_Origin4"]; break; default: originText = string.Empty; break; } table.AddCell(ToolsPdf.DataCellCenter(incidentFilter.Code, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCell(incidentFilter.Description, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCellCenter(incidentFilter.Open, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCellCenter(statustext, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCell(incidentFilter.OriginText, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCellCenter(actionDescription, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCellMoney(incidentFilter.Amount, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCellCenter(incidentFilter.Close, ToolsPdf.LayoutFonts.Times)); } table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", dictionary["Common_RegisterCount"], cont), ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Padding = 6f, PaddingTop = 4f, Colspan = 4 }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant(), ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Padding = 6f, PaddingTop = 4f, HorizontalAlignment = 2 }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(totalCost), ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Padding = 6f, PaddingTop = 4f, HorizontalAlignment = 2 }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Colspan = 2 }); pdfDoc.Add(table); pdfDoc.CloseDocument(); res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName)); return(res); }
protected void Page_Load(object sender, EventArgs e) { var incidentId = Convert.ToInt64(Request.QueryString["id"]); var companyId = Convert.ToInt32(Request.QueryString["companyId"]); var company = new Company(companyId); var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var incident = Incident.GetById(incidentId, user.CompanyId); var path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(incident.Description); var fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_Incident"], formatedDescription, DateTime.Now); // FONTS var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts); } this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); this.arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); string type = string.Empty; string origin = string.Empty; string originSufix = string.Empty; string reporterType = string.Empty; string reporter = string.Empty; if (incident.Origin == 1) { origin = dictionary["Item_Incident_Origin1"]; } if (incident.Origin == 2) { origin = dictionary["Item_Incident_Origin2"]; } if (incident.Origin == 3) { origin = dictionary["Item_Incident_Origin3"]; } if (incident.Department.Id > 0) { reporterType = dictionary["Item_Incident_Origin1"]; reporter = Department.ById(incident.Department.Id, incident.CompanyId).Description; } else if (incident.Provider.Id > 0) { reporterType = dictionary["Item_Incident_Origin2"]; reporter = Provider.ById(incident.Provider.Id, incident.CompanyId).Description; } else if (incident.Customer.Id > 0) { reporterType = dictionary["Item_Incident_Origin3"]; reporter = Customer.ById(incident.Customer.Id, incident.CompanyId).Description; } string status = string.Empty; var document = new iTextSharp.text.Document(PageSize.A4, 30, 30, 65, 55); var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create)); var pageEventHandler = new TwoColumnHeaderFooter { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = user.UserName, CompanyId = incident.CompanyId, CompanyName = company.Name, Title = dictionary["Item_Incident"] }; pageEventHandler.Titles = new List <string> { dictionary["Item_IncidentAction"] }; writer.PageEvent = pageEventHandler; document.Open(); var table = new PdfPTable(4) { WidthPercentage = 100, HorizontalAlignment = 0 }; table.SetWidths(new float[] { 15f, 30f, 15f, 30f }); var borderNone = Rectangle.NO_BORDER; var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER; var borderAll = Rectangle.RIGHT_BORDER + Rectangle.TOP_BORDER + Rectangle.LEFT_BORDER + Rectangle.BOTTOM_BORDER; var borderTBL = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER; var borderTBR = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER; var borderBL = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER; var borderBR = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER; var alignLeft = Element.ALIGN_LEFT; var alignRight = Element.ALIGN_RIGHT; var labelFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.DARK_GRAY); var valueFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.BLACK); // Descripción table.AddCell(LabelCell(dictionary["Item_Incident"], Rectangle.NO_BORDER)); table.AddCell(ValueCell(incident.Code.ToString() + " - " + incident.Description, borderNone, alignLeft, 3)); // Reportador if (incident.Origin != 4) { table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Reporter"], Rectangle.NO_BORDER)); table.AddCell(ValueCell(reporterType + " (" + reporter + ")", borderNone, alignLeft, 3)); } // WhatHappend table.AddCell(SeparationRow(4)); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"])); table.AddCell(TextAreaCell(Environment.NewLine + incident.WhatHappened, borderSides, alignLeft, 4)); table.AddCell(BlankRow(4)); table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + incident.WhatHappenedBy.FullName, borderBL, alignLeft, 2)); table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], incident.WhatHappenedOn), borderBR, alignRight, 2)); // Causes table.AddCell(SeparationRow(4)); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"])); table.AddCell(TextAreaCell(Environment.NewLine + incident.Causes, borderSides, alignLeft, 4)); table.AddCell(BlankRow(4)); table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + incident.CausesBy.FullName, borderBL, alignLeft, 2)); table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], incident.CausesOn), borderBR, alignRight, 2)); // Actions table.AddCell(SeparationRow(4)); table.AddCell(TitleCell(dictionary["Item_Incident_Label_Actions"])); table.AddCell(TextAreaCell(Environment.NewLine + incident.Actions, borderSides, alignLeft, 4)); table.AddCell(BlankRow(4)); table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + incident.ActionsBy.FullName, borderBL, alignLeft, 2)); table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_DateExecution"], incident.ActionsOn), borderBR, alignRight, 2)); // Close table.AddCell(SeparationRow(4)); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"])); table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], incident.ClosedBy.FullName), borderTBL, alignLeft, 2)); table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1:dd/MM/yyyy}", dictionary["Common_DateClose"], incident.ClosedOn), borderTBR, alignRight, 2)); // Notes table.AddCell(SeparationRow(4)); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"])); table.AddCell(TextAreaCell(Environment.NewLine + incident.Notes, borderAll, alignLeft, 4)); document.Add(table); if (user.HasGrantToRead(ApplicationGrant.IncidentActions)) { // Añadir posible acción var action = IncidentAction.ByIncidentId(incident.Id, companyId); if (action.Id > 0) { var tableAction = new PdfPTable(4) { WidthPercentage = 100, HorizontalAlignment = 0 }; tableAction.SetWidths(new float[] { 15f, 30f, 15f, 30f }); // Descripción var headerFont = new Font(this.arial, 15, Font.NORMAL, BaseColor.BLACK); tableAction.AddCell(new PdfPCell(new Phrase(dictionary["Item_Incident_PDF_ActionPageTitle"], headerFont)) { Colspan = 4, Border = ToolsPdf.BorderBottom, HorizontalAlignment = Rectangle.ALIGN_CENTER }); tableAction.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Description"], Rectangle.NO_BORDER)); tableAction.AddCell(ValueCell(action.Description, borderNone, alignLeft, 3)); // WhatHappend tableAction.AddCell(SeparationRow(4)); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"])); tableAction.AddCell(TextAreaCell(Environment.NewLine + action.WhatHappened, borderSides, alignLeft, 4)); tableAction.AddCell(BlankRow(4)); tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.WhatHappenedBy.FullName, borderBL, alignLeft, 2)); tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.WhatHappenedOn), borderBR, alignRight, 2)); // Causes var causesFullName = string.Empty; var causesDate = string.Empty; if (action.CausesBy != null) { causesFullName = action.CausesBy.FullName; causesDate = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.CausesOn); } tableAction.AddCell(SeparationRow(4)); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"])); tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Causes, borderSides, alignLeft, 4)); tableAction.AddCell(BlankRow(4)); tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + causesFullName, borderBL, alignLeft, 2)); tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_Date"], causesDate), borderBR, alignRight, 2)); // Actions var actionFullName = string.Empty; var actionDate = string.Empty; if (action.ActionsBy != null) { actionFullName = action.ActionsBy.FullName; actionDate = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ActionsOn); } tableAction.AddCell(SeparationRow(4)); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Actions"])); tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Actions, borderSides, alignLeft, 4)); tableAction.AddCell(BlankRow(4)); tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + actionFullName, borderBL, alignLeft, 2)); tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_DateExecution"], actionDate), borderBR, alignRight, 2)); // Monitoring tableAction.AddCell(SeparationRow(4)); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Monitoring"])); tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Monitoring, borderAll, alignLeft, 4)); // Close var closedFullName = string.Empty; var closedDate = string.Empty; if (action.ClosedBy != null) { closedFullName = action.ClosedBy.FullName; closedDate = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ClosedOn); } tableAction.AddCell(SeparationRow(4)); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"])); tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], closedFullName), borderTBL, alignLeft, 2)); tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Common_DateClose"], closedDate), borderTBR, alignRight, 2)); // Notes tableAction.AddCell(SeparationRow(4)); tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"])); tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Notes, borderAll, alignLeft, 4)); document.NewPage(); document.Add(tableAction); } } // Costes var costs = IncidentCost.AllCosts(incidentId, companyId); if (costs.Count > 0) { var times = new Font(arial, 8, Font.NORMAL, BaseColor.BLACK); var fontSummary = new Font(arial, 9, Font.BOLD, BaseColor.BLACK); var headerFontFinal = new Font(headerFont, 9, Font.NORMAL, BaseColor.BLACK); var tableCosts = new PdfPTable(5) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f, SpacingAfter = 30f }; tableCosts.SetWidths(new float[] { 35f, 10f, 10f, 10f, 20f }); tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Description"])); tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Amount"])); tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Quantity"])); tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Total"])); tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_ReportedBy"])); decimal total = 0; decimal totalIncidencia = 0; decimal totalAccion = 0; int cont = 0; int contIncidencia = 0; int contAccion = 0; foreach (var cost in costs.Where(c => c.Source == "I")) { tableCosts.AddCell(ToolsPdf.DataCell(cost.Description, times)); tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Amount, times)); tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, times)); tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity * cost.Amount, times)); tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Responsible.FullName, times)); total += cost.Amount * cost.Quantity; totalIncidencia += cost.Amount * cost.Quantity; cont++; contIncidencia++; } if (user.HasGrantToRead(ApplicationGrant.IncidentActions)) { tableCosts.AddCell(new PdfPCell(new Phrase(string.Format( CultureInfo.InvariantCulture, @"{0} {2}: {1}", dictionary["Common_RegisterCount"], contIncidencia, dictionary["Item_Incident"]), times)) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 2 }); tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], times)) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 1, HorizontalAlignment = Rectangle.ALIGN_RIGHT, }); tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(totalIncidencia), times)) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 1, HorizontalAlignment = Rectangle.ALIGN_RIGHT, }); tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, times))) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 1 }); } if (user.HasGrantToRead(ApplicationGrant.IncidentActions)) { // Acciones foreach (var cost in costs.Where(c => c.Source == "A")) { tableCosts.AddCell(ToolsPdf.DataCell(cost.Description, times)); tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Amount, times)); tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, times)); tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity * cost.Amount, times)); tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Responsible.FullName, times)); total += cost.Amount * cost.Quantity; totalAccion = cost.Amount * cost.Quantity; cont++; contAccion++; } tableCosts.AddCell(new PdfPCell(new Phrase(string.Format( CultureInfo.InvariantCulture, @"{0} {2}: {1}", dictionary["Common_RegisterCount"], contAccion, dictionary["Item_IncidentAction"]), times)) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 2 }); tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], times)) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 1, HorizontalAlignment = Rectangle.ALIGN_RIGHT }); tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(totalAccion), times)) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 1, HorizontalAlignment = Rectangle.ALIGN_RIGHT, }); tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, times))) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 1 }); } // resumen tableCosts.AddCell(new PdfPCell(new Phrase(string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", dictionary["Common_RegisterCount"], cont), fontSummary)) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 2 }); tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], fontSummary)) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 1, HorizontalAlignment = Rectangle.ALIGN_RIGHT }); tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(total), fontSummary)) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 1, HorizontalAlignment = Rectangle.ALIGN_RIGHT, }); tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, fontSummary))) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 1 }); document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); document.Add(tableCosts); } document.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=Incidencia.pdf"); Response.ContentType = "application/pdf"; Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName); Response.Flush(); Response.Clear(); }
public static ActionResult PDF(int companyId, DateTime?dateFrom, DateTime?dateTo, string indicadorName, int indicadorId, string listOrder) { var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var company = new Company(companyId); var registros = IndicadorRegistro.ByIndicadorId(indicadorId, companyId).ToList(); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(indicadorName); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_{2:yyyyMMddhhmmss}.xls", dictionary["Item_Indicador_RecordsReportTitle"], formatedDescription, DateTime.Now); fileName = fileName.Replace("%", ""); var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream( string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName), FileMode.Create)); writer.PageEvent = new TwoColumnHeaderFooter { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName), CompanyId = companyId, CompanyName = company.Name, Title = string.Format(CultureInfo.InvariantCulture, "{0} {1}", dictionary["Item_Indicador_RecordsReportTitle"].ToUpperInvariant(), indicadorName) }; pdfDoc.Open(); var backgroundColor = new iTS.BaseColor(220, 220, 220); string periode = string.Empty; if (dateFrom.HasValue && dateTo.HasValue) { periode = string.Format( CultureInfo.InvariantCulture, @"{2} {0:dd/MM/yyyy} {3} {1:dd/MM/yyyy}", dateFrom.Value, dateTo.Value, dictionary["Common_From"].ToLowerInvariant(), dictionary["Common_To"].ToLowerInvariant()); } else if (dateFrom.HasValue && dateTo == null) { periode = string.Format( CultureInfo.InvariantCulture, @"{1}: {0:dd/MM/yyyy}", dateFrom.Value, dictionary["Common_From"]); } else if (dateFrom == null && dateTo.HasValue) { periode = string.Format( CultureInfo.InvariantCulture, @"{1}: {0:dd/MM/yyyy}", dateTo.Value, dictionary["Common_To"]); } if (string.IsNullOrEmpty(periode)) { periode = dictionary["Common_PeriodAll"]; } var criteriatable = new iTSpdf.PdfPTable(2) { WidthPercentage = 100 }; string typeText = string.Empty; criteriatable.SetWidths(new float[] { 25f, 250f }); criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(dictionary["Common_Period"])); criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(periode)); criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(typeText)); pdfDoc.Add(criteriatable); var table = new iTSpdf.PdfPTable(7) { WidthPercentage = 100, HorizontalAlignment = 0, SpacingBefore = 20f, SpacingAfter = 30f }; table.SetWidths(new float[] { 15f, 10f, 15f, 15f, 20f, 20f, 30f }); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Status"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Value"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Date"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Comments"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Meta"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Alarm"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Responsible"])); // Aplicar filtro if (dateFrom.HasValue) { registros = registros.Where(r => r.Date >= dateFrom).ToList(); } if (dateTo.HasValue) { registros = registros.Where(r => r.Date <= dateTo).ToList(); } switch (listOrder.ToUpperInvariant()) { default: case "TH1|ASC": registros = registros.OrderBy(d => d.Value).ToList(); break; case "TH1|DESC": registros = registros.OrderByDescending(d => d.Value).ToList(); break; case "TH2|ASC": registros = registros.OrderBy(d => d.Date).ToList(); break; case "TH2|DESC": registros = registros.OrderByDescending(d => d.Date).ToList(); break; case "TH4|ASC": registros = registros.OrderBy(d => d.Meta).ToList(); break; case "TH4|DESC": registros = registros.OrderByDescending(d => d.Meta).ToList(); break; case "TH5|ASC": registros = registros.OrderBy(d => d.Alarma).ToList(); break; case "TH5|DESC": registros = registros.OrderByDescending(d => d.Alarma).ToList(); break; case "TH6|ASC": registros = registros.OrderBy(d => d.Responsible.FullName).ToList(); break; case "TH6|DESC": registros = registros.OrderByDescending(d => d.Responsible.FullName).ToList(); break; } int cont = 0; var dataPoints = new List <PointData>(); foreach (var registro in registros.OrderByDescending(r => r.Date)) { cont++; string metaText = IndicadorRegistro.ComparerLabelSign(registro.MetaComparer, dictionary); string alarmText = IndicadorRegistro.ComparerLabelSign(registro.AlarmaComparer, dictionary); int color = 0; string statusLabel = dictionary["Item_Objetivo_StatusLabelWithoutMeta"]; if (metaText == "=" && registro.Value == registro.Meta) { color = 1; statusLabel = dictionary["Item_Objetivo_StatusLabelMeta"]; } else if (metaText == ">" && registro.Value > registro.Meta) { color = 1; statusLabel = dictionary["Item_Objetivo_StatusLabelMeta"]; } else if (metaText == ">=" && registro.Value >= registro.Meta) { color = 1; statusLabel = dictionary["Item_Objetivo_StatusLabelMeta"]; } else if (metaText == "<" && registro.Value < registro.Meta) { color = 1; statusLabel = dictionary["Item_Objetivo_StatusLabelMeta"]; } else if (metaText == "<=" && registro.Value <= registro.Meta) { color = 1; statusLabel = dictionary["Item_Objetivo_StatusLabelMeta"]; } else if (!string.IsNullOrEmpty(alarmText)) { if (alarmText == "=" && registro.Value == registro.Alarma) { color = 2; statusLabel = dictionary["Item_Objetivo_StatusLabelWarning"]; } else if (alarmText == ">" && registro.Value > registro.Alarma) { color = 2; statusLabel = dictionary["Item_Objetivo_StatusLabelWarning"]; } else if (alarmText == ">=" && registro.Value >= registro.Alarma) { color = 2; statusLabel = dictionary["Item_Objetivo_StatusLabelWarning"]; } else if (alarmText == "<" && registro.Value < registro.Alarma) { color = 2; statusLabel = dictionary["Item_Objetivo_StatusLabelWarning"]; } else if (alarmText == "<=" && registro.Value <= registro.Alarma) { color = 2; statusLabel = dictionary["Item_Objetivo_StatusLabelWarning"]; } else { statusLabel = dictionary["Item_Objetivo_StatusLabelNoMeta"]; color = 3; } } else { statusLabel = dictionary["Item_Objetivo_StatusLabelNoMeta"]; color = 3; } table.AddCell(ToolsPdf.DataCell(statusLabel, ToolsPdf.LayoutFonts.Times)); metaText = string.Format(CultureInfo.InvariantCulture, "{0} {1:#,##0.00}", metaText, registro.Meta); alarmText = string.Format(CultureInfo.InvariantCulture, "{0} {1:#,##0.00}", alarmText, registro.Alarma); table.AddCell(ToolsPdf.DataCellRight(string.Format(CultureInfo.InvariantCulture, "{0:#,##0.00}", registro.Value))); table.AddCell(ToolsPdf.DataCell(registro.Date)); table.AddCell(ToolsPdf.DataCell(registro.Comments)); table.AddCell(ToolsPdf.DataCell(metaText)); table.AddCell(ToolsPdf.DataCell(alarmText)); table.AddCell(ToolsPdf.DataCell(registro.Responsible.FullName)); dataPoints.Add(new PointData { Value = registro.Value, Meta = registro.Meta, Alarma = registro.Alarma, Date = registro.Date, Status = color }); } table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", dictionary["Common_RegisterCount"], cont), ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = backgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 2 }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = backgroundColor, Colspan = 5 }); string graphName = string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, "graph.jpg"); dataPoints = dataPoints.OrderBy(dp => dp.Date).ToList(); using (var chart = new Chart()) { chart.ChartAreas.Add(new ChartArea("Valor")); var series = new Series(); chart.Width = 800; chart.Height = 350; chart.Series.Add("Values"); chart.Series["Values"].ChartType = SeriesChartType.Column; chart.Series["Values"].YValueType = ChartValueType.Double; chart.Series.Add("Meta"); chart.Series["Meta"].ChartType = SeriesChartType.Line; chart.Series["Meta"].BorderWidth = 3; chart.Series["Meta"].BorderColor = DR.Color.Green; chart.Series["Meta"].YValueType = ChartValueType.Double; chart.Series.Add("Alarma"); chart.Series["Alarma"].ChartType = SeriesChartType.Line; chart.Series["Alarma"].BorderWidth = 3; chart.Series["Alarma"].BorderColor = DR.Color.Pink; chart.Series["Alarma"].YValueType = ChartValueType.Double; foreach (var dataPoint in dataPoints) { chart.Series["Values"].Points.AddXY(string.Format("{0:dd/MM/yyyy}", dataPoint.Date), dataPoint.Value); chart.Series["Meta"].Points.AddY(dataPoint.Meta); chart.Series["Alarma"].Points.AddY(dataPoint.Alarma ?? 0); } chart.Series["Values"].IsValueShownAsLabel = true; chart.Series["Values"].Font = new DR.Font("Arial", 8, DR.FontStyle.Bold); chart.Series["Values"].ChartArea = "Valor"; chart.Series["Meta"].ChartArea = "Valor"; chart.Series["Alarma"].ChartArea = "Valor"; chart.ChartAreas["Valor"].AxisX.LabelStyle.Font = new DR.Font("Arial", 8); chart.ChartAreas["Valor"].AxisX.MajorGrid.Enabled = false; chart.ChartAreas["Valor"].AxisX.LabelStyle.Angle = 75; chart.ChartAreas["Valor"].AxisY.LabelStyle.Font = new DR.Font("Arial", 10); chart.ChartAreas["Valor"].RecalculateAxesScale(); int cp = 0; foreach (var Point in chart.Series["Values"].Points) { switch (dataPoints[cp].Status) { default: case 0: Point.Color = DR.Color.DarkGray; break; case 1: Point.Color = DR.Color.Green; break; case 2: Point.Color = DR.Color.Red; break; case 3: Point.Color = DR.Color.Orange; break; } cp++; } chart.Series.Add(series); chart.SaveImage(graphName, ChartImageFormat.Jpeg); } var tif = Image.GetInstance(graphName); tif.ScalePercent(100); pdfDoc.Add(table); pdfDoc.NewPage(); pdfDoc.Add(new iTS.Phrase("Grafico", ToolsPdf.LayoutFonts.Times)); pdfDoc.Add(tif); var logoIssus = Image.GetInstance(string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path)); logoIssus.ScalePercent(20f); logoIssus.SetAbsolutePosition(40f, 24f); pdfDoc.Add(logoIssus); pdfDoc.CloseDocument(); res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName)); return(res); }
protected void Page_Load(object sender, EventArgs e) { long actionId = Convert.ToInt64(Request.QueryString["id"]); int companyId = Convert.ToInt32(Request.QueryString["companyId"]); var company = new Company(companyId); var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var action = IncidentAction.ById(actionId, user.CompanyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(action.Description); formatedDescription = formatedDescription.Replace(@"\", "/"); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_IncidentAction"], formatedDescription, DateTime.Now); string type = string.Empty; string origin = string.Empty; string originSufix = string.Empty; string reporterType = string.Empty; string reporter = string.Empty; if (action.ActionType == 1) { type = dictionary["Item_IncidentAction_Type1"]; } if (action.ActionType == 2) { type = dictionary["Item_IncidentAction_Type2"]; } if (action.ActionType == 3) { type = dictionary["Item_IncidentAction_Type3"]; } if (action.Origin == 1) { origin = dictionary["Item_IncidentAction_Origin1"]; } if (action.Origin == 2) { origin = dictionary["Item_IncidentAction_Origin2"]; } if (action.Origin == 3) { if (action.IncidentId.HasValue) { var incident = Incident.GetById(action.IncidentId.Value, action.CompanyId); origin = string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", dictionary["Item_Incident"], incident.Description); } } if (action.Origin == 4) { if (action.BusinessRiskId.HasValue) { if (action.BusinessRiskId > Constant.DefaultId) { var businessRisk = BusinessRisk.ById(action.CompanyId, action.BusinessRiskId.Value); origin = businessRisk.Description; originSufix = " (" + dictionary["Item_BusinessRisk"] + ")"; } } } if (action.Origin == 5) { if (action.ObjetivoId.HasValue) { if (action.ObjetivoId > Constant.DefaultId) { var objetivo = Objetivo.ById(Convert.ToInt32(action.ObjetivoId.Value), action.CompanyId); origin = objetivo.Name; originSufix = " (" + dictionary["Item_Objetivo"] + ")"; } } } if (action.Origin == 6) { if (action.Oportunity.Id > Constant.DefaultId) { var oportunidad = Oportunity.ById(Convert.ToInt32(action.Oportunity.Id), action.CompanyId); origin = oportunidad.Description; originSufix = " (" + dictionary["Item_Oportunity"] + ")"; } } else { switch (action.ReporterType) { case 1: reporterType = dictionary["Item_IncidentAction_ReporterType1"]; if (action.Department != null && action.Department.Id > 0) { var department = Department.ById(action.Department.Id, action.CompanyId); reporter = department.Description; } break; case 2: reporterType = dictionary["Item_IncidentAction_ReporterType2"]; if (action.Provider != null && action.Provider.Id > 0) { var provider = Provider.ById(action.Provider.Id, action.CompanyId); reporter = provider.Description; } break; case 3: reporterType = dictionary["Item_IncidentAction_ReporterType3"]; if (action.Customer != null && action.Customer.Id > 0) { var customer = Customer.ById(action.Customer.Id, action.CompanyId); reporter = customer.Description; } break; default: break; } } string status = string.Empty; var document = new iTextSharp.text.Document(PageSize.A4, 30, 30, 65, 55); var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create)); writer.PageEvent = new TwoColumnHeaderFooter { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = user.UserName, CompanyId = action.CompanyId, CompanyName = company.Name, Title = dictionary["Item_IncidentAction"].ToUpperInvariant() }; document.Open(); var styles = new iTextSharp.text.html.simpleparser.StyleSheet(); var hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document); var widths = new float[] { 15f, 30f, 15f, 30f }; var table = new PdfPTable(4) { WidthPercentage = 100, HorizontalAlignment = 0 }; table.SetWidths(widths); var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER; var borderTBL = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER; var borderTBR = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER; var borderBL = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER; var borderBR = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER; var alignLeft = Element.ALIGN_LEFT; var alignRight = Element.ALIGN_RIGHT; var labelFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.DARK_GRAY); var valueFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.BLACK); // Descripción table.AddCell(LabelCell(dictionary["Item_IncidentAction"], Rectangle.NO_BORDER)); table.AddCell(ValueCell(action.Number.ToString() + " - " + action.Description, ToolsPdf.BorderNone, alignLeft, 3)); // Tipo table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Type"], Rectangle.NO_BORDER)); table.AddCell(ValueCell(type, ToolsPdf.BorderNone, alignLeft, 1)); // Origen table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Origin"], Rectangle.NO_BORDER)); table.AddCell(ValueCell(origin + originSufix, ToolsPdf.BorderNone, alignLeft, 3)); // Reportador if (action.Origin != 4 && action.Origin != 5 && !string.IsNullOrEmpty(reporter)) { table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Reporter"], Rectangle.NO_BORDER)); table.AddCell(ValueCell(reporterType + " (" + reporter + ")", ToolsPdf.BorderNone, alignLeft, 3)); } // WhatHappend table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"])); table.AddCell(TextAreaCell(Environment.NewLine + action.WhatHappened, borderSides, alignLeft, 4)); table.AddCell(BlankRow()); table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.WhatHappenedBy.FullName, borderBL, alignLeft, 2)); table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.WhatHappenedOn), borderBR, alignRight, 2)); // Causes table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"])); table.AddCell(TextAreaCell(Environment.NewLine + action.Causes, borderSides, alignLeft, 4)); table.AddCell(BlankRow()); table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.CausesBy.FullName, borderBL, alignLeft, 2)); table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.CausesOn), borderBR, alignRight, 2)); // Actions table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Actions"])); table.AddCell(TextAreaCell(Environment.NewLine + action.Actions, borderSides, alignLeft, 4)); table.AddCell(BlankRow()); table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.ActionsBy.FullName, borderBL, alignLeft, 2)); table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_DateExecution"], action.ActionsOn), borderBR, alignRight, 2)); // Monitoring table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Monitoring"])); table.AddCell(TextAreaCell(Environment.NewLine + action.Monitoring, ToolsPdf.BorderAll, alignLeft, 4)); // Close table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"])); table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], action.ClosedBy.FullName), borderTBL, alignLeft, 2)); table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1:dd/MM/yyyy}", dictionary["Common_DateClose"], action.ClosedOn), borderTBR, alignRight, 2)); // Notes table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"])); table.AddCell(TextAreaCell(Environment.NewLine + action.Notes, ToolsPdf.BorderAll, alignLeft, 4)); document.Add(table); // Costes var costs = IncidentActionCost.GetByIncidentActionId(actionId, companyId); if (costs.Count > 0) { var times = new Font(arial, 8, Font.NORMAL, BaseColor.BLACK); var fontSummary = new Font(arial, 9, Font.BOLD, BaseColor.BLACK); var headerFontFinal = new Font(headerFont, 9, Font.NORMAL, BaseColor.BLACK); // @alex: hay que crear la tabla con 6 columnas en lugar de 5 //var tableCosts = new PdfPTable(5) var tableCosts = new PdfPTable(6) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f, SpacingAfter = 30f }; // @alex: se añade una nueva columna de 10f para la fecha //tableCosts.SetWidths(new float[] { 35f, 10f, 10f, 10f, 20f }); tableCosts.SetWidths(new float[] { 35f, 10f, 10f, 10f, 10f, 20f }); tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Description"])); // @alex: se añade una nueva cabecera tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Common_Date"])); tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Amount"])); tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Quantity"])); tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Total"])); tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_ReportedBy"])); decimal total = 0; decimal totalAccion = 0; int cont = 0; int contAccion = 0; // Acciones foreach (var cost in costs.Where(c => c.Active == true)) { tableCosts.AddCell(ToolsPdf.DataCell(cost.Description, times)); // @alex: se añade la columna en la misma posición que en el listado de la ficha tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Date, times)); tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Amount, times)); tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, times)); tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity * cost.Amount, times)); tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Responsible.FullName, times)); total += cost.Amount * cost.Quantity; totalAccion = cost.Amount * cost.Quantity; cont++; contAccion++; } tableCosts.AddCell(new PdfPCell(new Phrase(string.Format( CultureInfo.InvariantCulture, @"{0} {2}: {1}", dictionary["Common_RegisterCount"], contAccion, dictionary["Item_IncidentAction"]), times)) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 3//@ alex: al haber una columna más el colspan crece de 2 a 3 }); tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], times)) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 1, HorizontalAlignment = Rectangle.ALIGN_RIGHT }); tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(total), times)) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 1, HorizontalAlignment = Rectangle.ALIGN_RIGHT, }); tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, times))) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 1 }); document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); document.Add(tableCosts); } document.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=Accion.pdf"); Response.ContentType = "application/pdf"; Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName); Response.Flush(); Response.Clear(); }
protected void Page_Load(object sender, EventArgs e) { int objetivoId = Convert.ToInt32(Request.QueryString["id"]); int companyId = Convert.ToInt32(Request.QueryString["companyId"]); var company = new Company(companyId); var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var objetivo = Objetivo.ById(objetivoId, user.CompanyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(objetivo.Name); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_Objetivo"], formatedDescription, DateTime.Now); string type = string.Empty; string origin = string.Empty; string originSufix = string.Empty; string reporterType = string.Empty; string reporter = string.Empty; string status = string.Empty; var document = new iTextSharp.text.Document(PageSize.A4, 30, 30, 65, 55); var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create)); writer.PageEvent = new TwoColumnHeaderFooter { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = user.UserName, CompanyId = objetivo.CompanyId, CompanyName = company.Name, Title = dictionary["Item_Objetivo"].ToUpperInvariant() }; document.Open(); var table = new PdfPTable(4) { WidthPercentage = 100, HorizontalAlignment = 0 }; table.SetWidths(new float[] { 15f, 30f, 15f, 30f }); ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Name"], objetivo.Name, 3); ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Responsible"], objetivo.Responsible.FullName, 3); ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_DateStart"], objetivo.StartDate); ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_ClosePreviewDate"], objetivo.PreviewEndDate); if (objetivo.VinculatedToIndicator) { var indicador = Indicador.ById(objetivo.IndicatorId.Value, companyId); ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Indicator"], indicador.Description); ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Periodicity"], indicador.Periodicity); } AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Description"], objetivo.Description, 4); AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Methodology"], objetivo.Methodology, 4); AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Resources"], objetivo.Resources, 4); AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Notes"], objetivo.Notes, 4); document.Add(table); if (user.HasGrantToRead(ApplicationGrant.IncidentActions)) { #region Acciones if (user.HasGrantToRead(ApplicationGrant.IncidentActions)) { var acciones = IncidentAction.ByObjetivoId(objetivoId, companyId); if (acciones.Count > 0) { document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var tableAcciones = new PdfPTable(5) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f }; tableAcciones.SetWidths(new float[] { 20f, 120f, 20f, 20f, 20f }); ToolsPdf.AddTableTitle(tableAcciones, dictionary["Item_Objetivo_ActionsReportTitle"]); tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Status"])); tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"])); tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"])); tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_ImplementDate"])); tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Cost"])); int cont = 0; decimal totalAcciones = 0; foreach (var accion in acciones) { tableAcciones.AddCell(ToolsPdf.DataCell(accion.Status)); tableAcciones.AddCell(ToolsPdf.DataCell(accion.Description)); tableAcciones.AddCell(ToolsPdf.DataCell(accion.WhatHappenedOn)); tableAcciones.AddCell(ToolsPdf.DataCell(accion.ActionsOn)); tableAcciones.AddCell(ToolsPdf.DataCell(0)); cont++; var costs = IncidentActionCost.GetByIncidentActionId(accion.Id, company.Id); foreach (var cost in costs) { totalAcciones = cost.Amount; } } // TotalRow tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_RegisterCount"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Padding = 8f }); tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, Padding = 8f }); tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Padding = 8f, Colspan = 2 }); tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", totalAcciones), ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, Padding = 8f }); tableAcciones.AddCell(new PdfPCell(new Phrase(string.Empty)) { Colspan = 3, Border = Rectangle.TOP_BORDER }); document.Add(tableAcciones); } } #endregion } #region Registros if (objetivo.VinculatedToIndicator) { var registros = IndicadorRegistro.ByIndicadorId(objetivo.IndicatorId.Value, companyId).ToList(); if (registros.Count > 0) { document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var tableRegistros = new PdfPTable(5) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f }; tableRegistros.SetWidths(new float[] { 20f, 20f, 120f, 40f, 50f }); ToolsPdf.AddTableTitle(tableRegistros, dictionary["Item_Objetivo_RecordsReportTitle"]); tableRegistros.AddCell(ToolsPdf.HeaderCell("*" + dictionary["Item_Indicador_TableRecords_Header_Value"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Date"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Comments"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Meta"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Responsible"])); int cont = 0; foreach (var registro in registros) { string meta = dictionary["Common_Comparer_" + registro.MetaComparer] + " " + registro.Meta.ToString(); // WEKE ALEX: con datacellmoney el dato debe ser decimal y lo poen con dos decimales tableRegistros.AddCell(ToolsPdf.DataCellMoney(registro.Value)); tableRegistros.AddCell(ToolsPdf.DataCell(registro.Date)); tableRegistros.AddCell(ToolsPdf.DataCell(registro.Comments)); tableRegistros.AddCell(ToolsPdf.DataCell(meta)); tableRegistros.AddCell(ToolsPdf.DataCell(registro.Responsible.FullName)); cont++; } // TotalRow tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_RegisterCount"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Padding = 8f }); tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, Padding = 8f }); tableRegistros.AddCell(new PdfPCell(new Phrase(string.Empty)) { Colspan = 3, Border = Rectangle.TOP_BORDER }); document.Add(tableRegistros); } } else { var registros = ObjetivoRegistro.GetByObjetivo(objetivoId, companyId).ToList(); if (registros.Count > 0) { document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var tableRegistros = new PdfPTable(5) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f }; tableRegistros.SetWidths(new float[] { 20f, 120f, 20f, 40f, 50f }); tableRegistros.AddCell(new PdfPCell(new Phrase(dictionary["Item_Objetivo_RecordsReportTitle"])) { Colspan = 5, Border = Rectangle.NO_BORDER, PaddingTop = 20f, PaddingBottom = 20f, HorizontalAlignment = Element.ALIGN_CENTER }); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Value"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Date"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Comments"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Meta"])); tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Responsible"])); int cont = 0; foreach (var registro in registros) { string meta = dictionary["Common_Comparer_" + registro.MetaComparer] + " " + registro.Meta.ToString(); tableRegistros.AddCell(ToolsPdf.DataCell(registro.Value)); tableRegistros.AddCell(ToolsPdf.DataCellCenter(registro.Date)); tableRegistros.AddCell(ToolsPdf.DataCell(registro.Comments)); tableRegistros.AddCell(ToolsPdf.DataCell(meta)); tableRegistros.AddCell(ToolsPdf.DataCell(registro.Responsible.FullName)); cont++; } // TotalRow tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Padding = 8f }); tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, Padding = 8f }); tableRegistros.AddCell(new PdfPCell(new Phrase(string.Empty)) { Colspan = 3, Border = Rectangle.TOP_BORDER }); document.Add(tableRegistros); } } #endregion if (user.HasGrantToRead(ApplicationGrant.IncidentActions)) { #region Historico var historico = ObjetivoHistorico.ByObjetivoId(objetivoId); if (historico.Count > 0) { document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); var tableHistorico = new PdfPTable(4) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f }; tableHistorico.SetWidths(new float[] { 20f, 20f, 120f, 50f }); ToolsPdf.AddTableTitle(tableHistorico, dictionary["Item_Objetivo_TabHistoric"]); tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_FieldLabel_Action"])); tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IndicatorRecord_FieldLabel_Date"])); tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_ObjetivoRecord_FieldLabel_Reason"])); tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_FieldLabel_CloseResponsible"])); int cont = 0; foreach (var objetivoHistorico in historico) { var actionText = string.Empty; var description = string.Empty; if (objetivoHistorico.Reason == "Restore") { actionText = dictionary["Item_ObjetivoHistorico_StatusRestore"]; } else { actionText = dictionary["Item_ObjetivoHistorico_StatusAnulate"]; description = objetivoHistorico.Reason; } tableHistorico.AddCell(ToolsPdf.DataCell(actionText)); tableHistorico.AddCell(ToolsPdf.DataCell(objetivoHistorico.Date)); tableHistorico.AddCell(ToolsPdf.DataCell(description)); tableHistorico.AddCell(ToolsPdf.DataCell(objetivoHistorico.Employee.FullName)); cont++; } // TotalRow tableHistorico.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Padding = 8f }); tableHistorico.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold)) { Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, Padding = 8f }); tableHistorico.AddCell(new PdfPCell(new Phrase(string.Empty)) { Colspan = 2, Border = Rectangle.TOP_BORDER }); document.Add(tableHistorico); } #endregion } document.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=Accion.pdf"); Response.ContentType = "application/pdf"; Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName); Response.Flush(); Response.Clear(); }
public static ActionResult PDF( int companyId, string from, string to, long rulesId, long processId, string listOrder) { var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; Dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var company = new Company(companyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(company.Name); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf", Dictionary["Item_Oportunities"], formatedDescription, DateTime.Now); var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream( string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName), FileMode.Create)); writer.PageEvent = new TwoColumnHeaderFooter() { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = user.UserName, CompanyId = company.Id, CompanyName = company.Name, Title = Dictionary["Item_Oportunities"].ToUpperInvariant() }; pdfDoc.Open(); var titleTable = new iTSpdf.PdfPTable(1); titleTable.SetWidths(new float[] { 50f }); titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", Dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont)) { HorizontalAlignment = iTS.Element.ALIGN_CENTER, Border = iTS.Rectangle.NO_BORDER }); #region Criteria var criteriatable = new iTSpdf.PdfPTable(6) { WidthPercentage = 100 }; criteriatable.SetWidths(new float[] { 15f, 50f, 15f, 50f, 15f, 50f }); #region texts string criteriaProccess = Dictionary["Common_All_Male_Plural"]; if (processId > 0) { var process = new Process(processId, companyId); if (!string.IsNullOrEmpty(process.Description)) { criteriaProccess = process.Description; } } string periode = string.Empty; if (!string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to)) { periode = Dictionary["Item_Incident_List_Filter_From"] + " " + from; } else if (string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to)) { periode = Dictionary["Item_Incident_List_Filter_To"] + " " + to; } else if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to)) { periode = from + " - " + to; } else { periode = Dictionary["Common_All_Male"]; } string typetext = Dictionary["Common_All_Male_Plural"]; string ruleDescription = Dictionary["Common_All_Female_Plural"]; if (rulesId > 0) { var rule = Rules.GetById(companyId, rulesId); if (!string.IsNullOrEmpty(rule.Description)) { ruleDescription = rule.Description; } } #endregion ToolsPdf.AddCriteria(criteriatable, Dictionary["Common_Period"], periode); ToolsPdf.AddCriteria(criteriatable, Dictionary["Item_BusinesRisk_ListHeader_Process"], typetext); ToolsPdf.AddCriteria(criteriatable, Dictionary["Item_BusinesRisk_ListHeader_Rule"], ruleDescription); pdfDoc.Add(criteriatable); #endregion var table = new iTSpdf.PdfPTable(7) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f, SpacingAfter = 30f }; table.SetWidths(new float[] { 10f, 10f, 30f, 20f, 20f, 10f, 10f }); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_IncidentAction_Header_Type"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_Date"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Oportunity"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_Process"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_Rule"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_StartValue"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_IPR"])); int cont = 0; var data = HttpContext.Current.Session["OportunityFilterData"] as List <OportunityFilterItem>; switch (listOrder.ToUpperInvariant()) { default: case "TH1|ASC": data = data.OrderBy(d => d.OpenDate).ToList(); break; case "TH1|DESC": data = data.OrderByDescending(d => d.OpenDate).ToList(); break; case "TH2|ASC": data = data.OrderBy(d => d.Description).ToList(); break; case "TH2|DESC": data = data.OrderByDescending(d => d.Description).ToList(); break; case "TH3|ASC": data = data.OrderBy(d => d.Process.Description).ToList(); break; case "TH3|DESC": data = data.OrderByDescending(d => d.Process.Description).ToList(); break; case "TH4|ASC": data = data.OrderBy(d => d.Rule.Description).ToList(); break; case "TH4|DESC": data = data.OrderByDescending(d => d.Rule.Description).ToList(); break; case "TH5|ASC": data = data.OrderBy(d => d.Rule.Limit).ToList(); break; case "TH5|DESC": data = data.OrderByDescending(d => d.Rule.Limit).ToList(); break; } foreach (OportunityFilterItem risk in data) { cont++; string typeText = string.Empty; if (risk.Result == 0) { typeText = Dictionary["Item_BusinessRisk_Status_Unevaluated"]; } else if (risk.Result < risk.Rule.Limit) { typeText = Dictionary["Item_BusinessRisk_Status_NotSignificant"]; } else { typeText = Dictionary["Item_BusinessRisk_Status_Significant"]; } string initialResultText = risk.Result == 0 ? string.Empty : risk.Result.ToString(); table.AddCell(ToolsPdf.DataCellCenter(typeText)); table.AddCell(ToolsPdf.DataCellCenter(risk.OpenDate)); table.AddCell(ToolsPdf.DataCell(risk.Description)); table.AddCell(ToolsPdf.DataCell(risk.Process.Description)); table.AddCell(ToolsPdf.DataCellCenter(risk.Rule.Description)); table.AddCell(ToolsPdf.DataCellCenter(initialResultText)); table.AddCell(ToolsPdf.DataCellRight(risk.Rule.Limit)); } table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", Dictionary["Common_RegisterCount"], cont), ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, Padding = 6f, PaddingTop = 4f, Colspan = 4 }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, Colspan = 4 }); pdfDoc.Add(table); pdfDoc.CloseDocument(); res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName)); return(res); }
public static ActionResult PDF(int companyId, string filter, string listOrder) { var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; Dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var company = new Company(companyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(company.Name); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf", Dictionary["Item_DocumentList"], formatedDescription, DateTime.Now); var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream( string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName), FileMode.Create)); writer.PageEvent = new TwoColumnHeaderFooter { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = user.UserName, CompanyId = company.Id, CompanyName = company.Name, Title = Dictionary["Item_DocumentList"].ToUpperInvariant() }; pdfDoc.Open(); var titleTable = new iTSpdf.PdfPTable(1); titleTable.SetWidths(new float[] { 20f }); titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", Dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont)) { HorizontalAlignment = iTS.Element.ALIGN_CENTER, Border = iTS.Rectangle.NO_BORDER }); var criteriatable = new iTSpdf.PdfPTable(6) { WidthPercentage = 100 }; criteriatable.SetWidths(new float[] { 10f, 20f, 12f, 30f, 10f, 80f }); var criteria1Label = new iTSpdf.PdfPCell(new iTS.Phrase(Dictionary["Common_Status"] + " :", ToolsPdf.LayoutFonts.TimesBold)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }; var criteria2Label = new iTSpdf.PdfPCell(new iTS.Phrase(Dictionary["Item_Document_FieldLabel_Category"] + " :", ToolsPdf.LayoutFonts.TimesBold)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }; var criteria3Label = new iTSpdf.PdfPCell(new iTS.Phrase(Dictionary["Item_Document_FieldLabel_Origin"] + " :", ToolsPdf.LayoutFonts.TimesBold)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }; string statusText = Dictionary["Common_All_Male_Plural"]; string category = Dictionary["Common_All_Female_Plural"]; string origin = Dictionary["Common_All_Male_Plural"]; if (filter.IndexOf("A|") != -1) { statusText = Dictionary["Common_Active_Plural"]; } if (filter.StartsWith("I", StringComparison.OrdinalIgnoreCase)) { statusText = Dictionary["Common_Inactive_Plural"]; } if (filter.StartsWith("|", StringComparison.OrdinalIgnoreCase)) { statusText = Dictionary["Common_None"]; } var documents = GisoFramework.Item.Document.ByCompany(companyId); var data = new List <GisoFramework.Item.Document>(); // @alex: "A" indica que en el filtro se ha marcado "activos" if (filter.IndexOf("A") != -1) { data = documents.Where(d => d.EndDate.HasValue == false).ToList(); } // @alex: "I" indica que en el filtro se ha marcado "inactivos" if (filter.IndexOf("I") != -1) { data.AddRange(documents.Where(d => d.EndDate.HasValue).ToList()); } var parts = filter.Split('|'); if (parts[1] != "-1") { data = data.Where(d => d.Category.Id == Convert.ToInt32(parts[1])).ToList(); var cats = DocumentCategory.ByCompany(companyId); var cat = cats.First(c => c.Id == Convert.ToInt32(parts[1])); category = cat.Description; } if (parts[2] == "0") { data = data.Where(d => d.Origin.Id == 0).ToList(); origin = Dictionary["Common_Internal"]; } if (parts[2] == "1") { data = data.Where(d => d.Origin.Id > 0).ToList(); origin = Dictionary["Common_External"]; } criteriatable.AddCell(criteria1Label); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(statusText, ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }); criteriatable.AddCell(criteria2Label); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(category, ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }); criteriatable.AddCell(criteria3Label); criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(origin, ToolsPdf.LayoutFonts.Times)) { Border = ToolsPdf.BorderNone, HorizontalAlignment = iTS.Element.ALIGN_LEFT, Padding = 6f, PaddingTop = 4f }); // @alex-20200605: hay que indicr que son 7 columnas en lugar de 6 var table = new iTSpdf.PdfPTable(7) //var table = new iTSpdf.PdfPTable(6) { WidthPercentage = 100, HorizontalAlignment = 1 }; // @alex-20200605: supongo que te petaba aquí porque le enviarías 7 anchos cuando sólo había 6 columnas (mensaje anterior) table.SetWidths(new float[] { 20f, 5f, 12f, 9f, 9f, 5f, 5f }); //table.SetWidths(new float[] { 20f, 5f, 15f, 15f, 10f, 5f }); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Name"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Code"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Category"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Origin"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Location"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Revision"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinessRisk_LabelField_DateStart"])); switch (listOrder.ToUpperInvariant()) { default: case "TH0|ASC": data = data.OrderBy(d => d.Description).ToList(); break; case "TH0|DESC": data = data.OrderByDescending(d => d.Description).ToList(); break; case "TH1|ASC": data = data.OrderBy(d => d.Code).ToList(); break; case "TH1|DESC": data = data.OrderByDescending(d => d.Code).ToList(); break; case "TH2|ASC": data = data.OrderBy(d => d.LastNumber).ToList(); break; case "TH2|DESC": data = data.OrderByDescending(d => d.LastNumber).ToList(); break; case "TH3|ASC": data = data.OrderBy(d => d.Origin).ToList(); break; case "TH3|DESC": data = data.OrderByDescending(d => d.Origin).ToList(); break; // @alex-20200605: toda columna ordenable en pantalla debe aparece aquí para replicar el orden en el pdf case "TH4|ASC": data = data.OrderBy(d => d.Location).ToList(); break; case "TH4|DESC": data = data.OrderByDescending(d => d.Location).ToList(); break; case "TH5|ASC": data = data.OrderBy(d => d.LastNumber).ToList(); break; case "TH5|DESC": data = data.OrderByDescending(d => d.LastNumber).ToList(); break; case "TH6|ASC": data = data.OrderBy(d => d.StartDate).ToList(); break; case "TH6|DESC": data = data.OrderByDescending(d => d.StartDate).ToList(); break; } int count = 0; foreach (var document in data) { count++; table.AddCell(ToolsPdf.DataCell(document.Description)); table.AddCell(ToolsPdf.DataCell(document.Code)); table.AddCell(ToolsPdf.DataCell(document.Category.Description)); table.AddCell(ToolsPdf.DataCell(document.Origin.Id == 0 ? Dictionary["Common_Internal"] : Dictionary["Common_External"])); table.AddCell(ToolsPdf.DataCell(document.Location)); table.AddCell(ToolsPdf.DataCell(document.LastNumber)); table.AddCell(ToolsPdf.DataCell(document.StartDate)); } string totalRegistros = string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", Dictionary["Common_RegisterCount"], count); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Colspan = 5 }); pdfDoc.Add(criteriatable); pdfDoc.Add(table); pdfDoc.CloseDocument(); res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName)); return(res); }
protected void Page_Load(object sender, EventArgs e) { var presupuestoId = Request.QueryString["presupuestoId"]; var centro = HttpContext.Current.Session["user"] as ApplicationUser; var polizaId = Request.QueryString["polizaId"]; var poliza = Poliza.ById(polizaId); var dictionary = ApplicationDictionary.Load("es"); var path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}.pdf", dictionary["Item_Prespuesto"], Guid.NewGuid()); // FONTS var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts); } string type = string.Empty; string origin = string.Empty; string originSufix = string.Empty; string reporterType = string.Empty; string reporter = string.Empty; string status = string.Empty; var document = new iTextSharp.text.Document(PageSize.A4, 30, 30, 65, 55); var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create)); document.Open(); var borderNone = Rectangle.NO_BORDER; var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER; var borderAll = Rectangle.RIGHT_BORDER + Rectangle.TOP_BORDER + Rectangle.LEFT_BORDER + Rectangle.BOTTOM_BORDER; var borderTBL = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER; var borderTBR = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER; var borderBL = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER; var borderBR = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER; document.Add(new Paragraph(centro.Nombre, FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD))); document.Add(new Paragraph("N.I.F: " + centro.NIF, FontFactory.GetFont(FontFactory.HELVETICA, 8))); document.Add(new Paragraph(centro.Nombre, FontFactory.GetFont(FontFactory.HELVETICA, 8))); document.Add(new Paragraph(centro.CP + ", " + centro.Poblacion, FontFactory.GetFont(FontFactory.HELVETICA, 8))); document.Add(new Paragraph("Telf.: " + centro.Telefono1, FontFactory.GetFont(FontFactory.HELVETICA, 8))); var alignLeft = Element.ALIGN_LEFT; var alignRight = Element.ALIGN_RIGHT; var table = new PdfPTable(2) { WidthPercentage = 100, HorizontalAlignment = 0 }; table.SetWidths(new float[] { 30f, 30f }); var labelFont = FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL); var totalFont = FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.NORMAL); var dataFont = FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD); var presupuestoCodigo = string.Empty; var presupuestoFecha = string.Empty; var aseguradoNombre = poliza.AseguradoNombre; var aseguradoDireccion = string.Empty; var aseguradoCP = string.Empty; var aseguradoPoblacion = string.Empty; var aseguradoProvincia = string.Empty; var aseguradoNIF = poliza.AseguradoNIF; var observaciones = string.Empty; // Linea Total string impuestoText = dictionary["PDF_IVA"] + " " + ConfigurationManager.AppSettings["IVA"].ToString() + "%"; decimal impuesto = Convert.ToDecimal(ConfigurationManager.AppSettings["IVA"].ToString()); if (centro.Provincia.IndexOf("tenerife", StringComparison.OrdinalIgnoreCase) != -1 || centro.Provincia.IndexOf("canaria", StringComparison.OrdinalIgnoreCase) != -1 || centro.Provincia.IndexOf("las palmas", StringComparison.OrdinalIgnoreCase) != -1) { impuestoText = dictionary["PDF_IGIC"] + " " + ConfigurationManager.AppSettings["IGIC"].ToString() + "%"; impuesto = Convert.ToDecimal(ConfigurationManager.AppSettings["IGIC"].ToString()); } if (centro.Provincia.IndexOf("melilla", StringComparison.OrdinalIgnoreCase) != -1) { impuestoText = dictionary["PDF_Melilla"] + " " + ConfigurationManager.AppSettings["Melilla"].ToString() + "%"; impuesto = Convert.ToDecimal(ConfigurationManager.AppSettings["Melilla"].ToString()); } if (centro.Provincia.IndexOf("ceuta", StringComparison.OrdinalIgnoreCase) != -1) { impuestoText = dictionary["PDF_Ceuta"] + " " + ConfigurationManager.AppSettings["Ceuta"].ToString() + "%"; impuesto = Convert.ToDecimal(ConfigurationManager.AppSettings["Ceuta"].ToString()); } var tableObservaciones = new PdfPTable(2) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f, SpacingAfter = 30f }; var tableCostsAspad = new PdfPTable(6) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f, SpacingAfter = 10f }; var tableCostsPropios = new PdfPTable(6) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 10f, SpacingAfter = 20f }; tableObservaciones.SetWidths(new float[] { 1f, 3f }); tableCostsAspad.SetWidths(new float[] { 25f, 23f, 10f, 10f, 10f, 15f }); tableCostsPropios.SetWidths(new float[] { 25f, 23f, 10f, 10f, 10f, 15f }); tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Especialidad"])); tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Concepto"])); tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Cantidad"])); tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Base"])); tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Dto"])); tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Importe"])); /* CREATE PROCEDURE ASPADLAND_GetPresupuestoPendienteByPresupuestoId * @PresupuestoId uniqueidentifier, * @CentroId nvarchar(50) */ bool propios = false; bool hasObservaciones = false; decimal totalBaseCost = 0; decimal totalBaseCostASPAD = 0; using (var cmd = new SqlCommand("ASPADLAND_Salesforce_GetPresupuestoPendienteByPresupuestoId")) { cmd.CommandType = CommandType.StoredProcedure; using (var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cns"].ConnectionString)) { cmd.Connection = cnn; cmd.Parameters.Add(DataParameter.Input("@PresupuestoId", presupuestoId)); cmd.Parameters.Add(DataParameter.Input("@CentroId", centro.Id)); try { cmd.Connection.Open(); using (var rdr = cmd.ExecuteReader()) { while (rdr.Read()) { observaciones = rdr.GetString(9); presupuestoCodigo = rdr.GetString(1); presupuestoFecha = string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy}", rdr.GetDateTime(7)); string amountText = string.Empty; string totalRowText = string.Empty; string actoObservaciones = rdr.GetString(10); var especialidad = rdr.GetString(4); decimal finalAmount = 0M; if (!rdr.IsDBNull(5)) { finalAmount = rdr.GetDecimal(5); if (especialidad.Equals("propio", StringComparison.OrdinalIgnoreCase)) { finalAmount = finalAmount / (1 + impuesto / 100); } amountText = string.Format( CultureInfo.InvariantCulture, @"{0:#0.00} €", finalAmount).Replace(",", "."); totalRowText = string.Format( CultureInfo.InvariantCulture, @"{0:#0.00} €", finalAmount).Replace(",", "."); } var dto = string.Empty; if (!rdr.IsDBNull(6)) { decimal dtoAmount = rdr.GetDecimal(6); finalAmount = finalAmount / (1 + impuesto / 100); amountText = string.Format( CultureInfo.InvariantCulture, @"{0:#0.00} €", finalAmount).Replace(",", "."); finalAmount = finalAmount * (100 - dtoAmount) / 100; dto = string.Format( CultureInfo.InvariantCulture, @"{0:#0.00} %", dtoAmount).Replace(",", "."); totalRowText = string.Format( CultureInfo.InvariantCulture, @"{0:#0.00} €", finalAmount).Replace(",", "."); } if (especialidad.Equals("propio", StringComparison.OrdinalIgnoreCase)) { totalBaseCost += finalAmount; } else { totalBaseCostASPAD += finalAmount; } if (especialidad.Equals("propio", StringComparison.OrdinalIgnoreCase)) { if (!propios) { tableCostsPropios.AddCell(new PdfPCell(new Phrase(dictionary["PDF_Actospropios"], ToolsPdf.TimesBold)) { Border = ToolsPdf.BorderBottom, Padding = 6f, PaddingTop = 6f, HorizontalAlignment = 0, Colspan = 6 }); } tableCostsPropios.AddCell(ToolsPdf.DataCell(especialidad, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCell(rdr.GetString(3), labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCellRight(1, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCellRight(amountText, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCellRight(dto, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCellRight(totalRowText, labelFont)); propios = true; if (!string.IsNullOrEmpty(actoObservaciones)) { hasObservaciones = true; tableObservaciones.AddCell(new PdfPCell(new Phrase(rdr.GetString(3), labelFont)) { Border = ToolsPdf.BorderNone, Padding = 6f, PaddingTop = 6f, HorizontalAlignment = 0 }); tableObservaciones.AddCell(new PdfPCell(new Phrase(actoObservaciones, labelFont)) { Border = ToolsPdf.BorderNone, Padding = 6f, PaddingTop = 6f, HorizontalAlignment = 0 }); } } else { tableCostsAspad.AddCell(ToolsPdf.DataCell(especialidad, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCell(rdr.GetString(3), labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCellRight(1, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCellRight(amountText, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCellRight(dto, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCellRight(totalRowText, labelFont)); if (!string.IsNullOrEmpty(actoObservaciones)) { hasObservaciones = true; tableObservaciones.AddCell(new PdfPCell(new Phrase(rdr.GetString(3), labelFont)) { Border = ToolsPdf.BorderNone, Padding = 6f, PaddingTop = 6f, HorizontalAlignment = 0 }); tableObservaciones.AddCell(new PdfPCell(new Phrase(actoObservaciones, labelFont)) { Border = ToolsPdf.BorderNone, Padding = 6f, PaddingTop = 6f, HorizontalAlignment = 0 }); } } } } } finally { if (cmd.Connection.State != ConnectionState.Closed) { cmd.Connection.Close(); } } } } var la1 = new Chunk(dictionary["PDF_Albaran"] + ": ", labelFont); var la2 = new Chunk(presupuestoCodigo + Environment.NewLine, FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)); var la3 = new Chunk(dictionary["PDF_Fecha"] + ": ", labelFont); var la4 = new Chunk(presupuestoFecha, dataFont); var p1 = new Paragraph { la1, la2, la3, la4 }; document.Add(new Paragraph(Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine)); var lb1 = new Chunk(aseguradoNombre + Environment.NewLine, dataFont); var lb2 = new Chunk(dictionary["PDF_Poliza"] + ": ", labelFont); var lb3 = new Chunk(poliza.Numero + Environment.NewLine, dataFont); var p2 = new Paragraph { lb1, lb2, lb3 }; var cell1 = new PdfPCell { Border = ToolsPdf.BorderNone }; var cell2 = new PdfPCell { Border = ToolsPdf.BorderNone }; cell1.AddElement(p1); cell2.AddElement(p2); table.AddCell(cell1); table.AddCell(cell2); document.Add(table); decimal baseIvaASPAD = totalBaseCostASPAD * impuesto / 100; string baseIvaTextASPAD = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", baseIvaASPAD).Replace(",", "."); string totalASPAD = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCostASPAD + baseIvaASPAD).Replace(",", "."); tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(dictionary["PDF_Base"] + ":", labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCostASPAD).Replace(",", "."), totalFont)); tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCellRight(impuestoText + ":", labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCellRight(baseIvaTextASPAD, totalFont)); tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCellRight(dictionary["PDF_Total"] + ":", labelFont)); tableCostsAspad.AddCell(ToolsPdf.DataCellRight(totalASPAD, totalFont)); document.Add(tableCostsAspad); if (propios) { decimal baseIva = totalBaseCost * impuesto / 100; string baseIvaText = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", baseIva).Replace(",", "."); string total = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCost + baseIva).Replace(",", "."); tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(dictionary["PDF_Base"], labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCost).Replace(",", "."), totalFont)); tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCellRight(impuestoText + ":", labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCellRight(baseIvaText, totalFont)); tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCellRight(dictionary["PDF_Total"] + ":", labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCellRight(total, totalFont)); tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont)); tableCostsPropios.AddCell(TotalCell(string.Empty)); tableCostsPropios.AddCell(TotalCell(string.Empty)); tableCostsPropios.AddCell(TotalCell(string.Empty)); tableCostsPropios.AddCell(TotalCell(string.Empty)); tableCostsPropios.AddCell(TotalCell(dictionary["PDF_Total"] + ":")); string superTotal = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCost + baseIva + totalBaseCostASPAD + baseIvaASPAD).Replace(",", "."); tableCostsPropios.AddCell(TotalCell(superTotal)); document.Add(tableCostsPropios); } if (!string.IsNullOrEmpty(observaciones)) { document.Add(new Paragraph("Observaciones", ToolsPdf.TimesBold)); document.Add(new Paragraph(observaciones, labelFont)); } if (hasObservaciones) { document.Add(tableObservaciones); } document.Add(new Phrase(dictionary["Item_Presupuesto_Print_Caducity"], ToolsPdf.TimesLittle)); document.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=Incidencia.pdf"); Response.ContentType = "application/pdf"; Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName); Response.Flush(); Response.Clear(); }