Tue Sep 29, 2026 8:31 am
It works correctly for you because you import the generated document and call the method again. We generate the document from scratch; I can’t update it in the same way because the document doesn’t exist at that point.
I’ll copy over all the code we use to generate the file… although it’s huge and calls various methods, but perhaps this will give you a better context.
Thanks again for your help.
public async Task<byte[]> GenerateFile(Guid missionId, string language, IDictionary<string, object> parameters)
{
Func<string, string> t = key => _translationService.Translate(key, null, language);
var context = _dbContextFactory.GetContext();
var mission = context.Set<Mission>().Include(x => x.Regime).FirstOrDefault(t => t.Id == missionId);
decimal IVAPercentage = await _percentageService.GetIvaPercent(missionId) / 100;
var companyId = mission.CompanyId;
var company = context.Set<Company>().FirstOrDefault(t => t.Id == companyId);
bool includeAnnotation = (bool)parameters["IncludeAnnotation"];
bool? includeIndividualCostStaff = (bool?)parameters["IncludeIndividualCostStaff"];
bool isGlobalTechnicalMemory = parameters.ContainsKey("IsGlobalTechnicalMemory");
//Identificación de proyectos
List<Project> projects = await context.Set<Project>().Include("Qualification").Where(t => t.MissionId == mission.Id && t.QualificationId != null && !t.IsDeleted).OrderBy(p => p.Acronym).ToListAsync();
//Projectos AUTO
var projectsAUTO = projects.Where(p => p.Strategy == Strategy.Expertise).ToList();
bool isProjectsAUTO = projectsAUTO.Count > 0;
var stream = GetTemplateStream(isGlobalTechnicalMemory, includeAnnotation, isProjectsAUTO);
Document document = new Document(stream);
document.addStylesDocument();
//Portada
var frontPage = new Frontpage(_fileStorageService, _logger);
await frontPage.GenerateFrontPage(document, company, mission);
//Datos generales
var generalData = new GeneralData();
generalData.GenerateGeneralData(document, mission);
var technicalMemories = await context.Set<TechnicalMemory>().Include("Project").Where(t => t.Project.MissionId == missionId && t.Project.Strategy == Strategy.Expertise).ToListAsync();
if (isGlobalTechnicalMemory && isProjectsAUTO)
{
generalData.GenerateTechnicalSpecialist(document, mission, projectsAUTO, technicalMemories, t);
}
var projectsID = projects.Where(p => p.Qualification.Title == "I+D" && p.Qualification.Title != "I+D+I").OrderBy(p => p.Acronym).ToList();
var projectsIT = projects.Where(p => p.Qualification.Title == "IT" && p.Qualification.Title != "I+D+I").OrderBy(p => p.Acronym).ToList();
var projectsITID = projects.Where(p => p.Qualification.Title == "I+D+I" && p.Qualification.Title != "IT" && p.Qualification.Title != "I+D").OrderBy(p => p.Acronym).ToList();
var projectList = new ProjectList();
projectList.GenerateProjectList(document, projectsID, projectsIT, projectsITID);
//Memoria Económica
string projectsText = projects.Count() > 1 ? "de los proyectos" : "del proyecto";
var economicMemorySection = new EconomicMemorySection();
economicMemorySection.GenerateEconomicMemorySection(document, mission, projectsText);
#region Calculo deduccion
// New Method
var deductionCalculation = new DeductionReport("");
//Staff
var staffSection = new StaffSection();
await staffSection.GenerateStaffSection(document, mission.Id, projects, deductionCalculation, includeIndividualCostStaff, context);
//Collaborations
var collaborationsSection = new CollaborationsSection(_expensesService);
await collaborationsSection.GenerateCollaborationsSection(document, mission, projects, deductionCalculation, context);
////Consumables
var consumblessSection = new ConsumablesSection();
await consumblessSection.GenerateConsumablesSection(document, mission, projects, deductionCalculation, context);
//Assets
var assetsSection = new AssetsSection(_assetDataService, _percentageService);
await assetsSection.GenerateAssetsSection(document, mission, projects, deductionCalculation, context);
//Otros gastos
var otherExpensesSection = new OtherExpensesSection();
await otherExpensesSection.GenerateOtherExpensesSection(document, mission, projects, deductionCalculation, context);
//Ayudas
var grantsSection = new GrantsSection(_grantsDataService);
await grantsSection.GenerateGrantsSection(mission, projects, deductionCalculation, context);
//Gasto por proyecto
var expensePerProjectSection = new ExpensePerProjectSection(_expensesPerProjectService);
ExpensesSectionResult expensesSectionResult = await expensePerProjectSection.GeneratExpensePerProjectSection(document, mission, projects, deductionCalculation);
//Deducciones
var deductionsSection = new DeductionSection(_deductionService);
DeductionSectionResult deductionSectionResult = await deductionsSection.GenerateDeductionSection(document, mission, projects, expensesSectionResult.ExpensesSummary, deductionCalculation);
deductionCalculation.CloseSections();
if (deductionCalculation.SectionCount > 0)
{
var file = await deductionCalculation.GenerateFile();
var replace = new Document(file);
document.Replace("{deductionCalculation}", replace, true, true);
}
else
document.Replace("{deductionCalculation}", "", true, true);
#endregion Calculo deduccion
bool? includeAnnexeIII = (bool?)parameters["IncludeAnnexeIII"];
// Annexe III
var annexeIII = new AnnexeIIISection(_recapDataService);
if (includeAnnexeIII.GetValueOrDefault())
{
await annexeIII.GenerateAnnexeIII(document, mission);
}
else
{
RemoveAnnexeIIIBlock(document);
}
//Recap
var recap = new RecapSection(_recapDataService);
await recap.GenerateRecap(document, mission);
var versions = context.Set<Version>().Include(x => x.Mission)
.Where(x => x.OriginalMissionId == missionId &&
(x.VersionType == VersionType.Precertificada || x.VersionType == VersionType.Certificada || x.VersionType == VersionType.Motivada))
.OrderBy(x => x.VersionType).ToList();
//Desviations
if (isGlobalTechnicalMemory)
{
var desviations = new DesviationsSection(_expensesPerProjectService, _deductionService);
await desviations.GenerateDesviations(document, projects, includeAnnotation, isGlobalTechnicalMemory, mission, versions);
}
#region Annotations
//if (includeAnnotation)
//{
// // se pidio el 247672024 que salieran los valores de los gastos en vez de las deducciones
//
// var annotations = new AnnotationsSection();
// var deductionAnnotationsStrem = await annotations.GenerateAnnotations(missionId, expensesSectionResult, company.Title, context);
//
// Document deductionAnnotationsStreamDocument = new Document(deductionAnnotationsStrem);
// document.Replace("{DeductionAnnotationSummary}", deductionAnnotationsStreamDocument, false, false);
// document.Replace("{IncludeAnnotation}", "", false, false);
//}
#endregion Annotations
#region globalSheets
#region regimenDesc
string regimen = mission.Regime.Title;
string regimenDescription = string.Empty;
string regimenDesc1 = string.Empty;
string regimenDesc2 = string.Empty;
switch (regimen)
{
case "Estatal":
regimenDescription = "Real Decreto 1432 / 2003, de 21 de Noviembre, por el que se regula la emisión por el Ministerio de Ciencia y Tecnología de informes motivados relativos al cumplimiento de requisitos científicos y tecnológicos a efectos de la aplicación e interpretación de deducciones fiscales por actividades de investigación y desarrollo e innovación tecnológica.";
regimenDesc1 = "Ley 27/2014, de 27 de noviembre, del Impuesto sobre Sociedades. Artículo 35.";
regimenDesc2 = string.Empty;
break;
case "Navarra":
regimenDescription = "Ley Foral 26/2016, de 28 de diciembre, del Impuesto sobre Sociedades.";
regimenDesc1 = "Real Decreto 1432 / 2003, de 21 de Noviembre, por el que se regula la emisión por el Ministerio de Ciencia y Tecnología de informes motivados relativos al cumplimiento de requisitos científicos y tecnológicos a efectos de la aplicación e interpretación de deducciones fiscales por actividades de investigación y desarrollo e innovación tecnológica.";
regimenDesc2 = "Ley 27/2014, de 27 de noviembre, del Impuesto sobre Sociedades. Artículo 35.";
break;
case "Canarias":
regimenDescription = "Ley 20/1991, Art. 94 que regula el régimen económica fiscal Canario.";
regimenDesc1 = "Real Decreto 1432 / 2003, de 21 de Noviembre, por el que se regula la emisión por el Ministerio de Ciencia y Tecnología de informes motivados relativos al cumplimiento de requisitos científicos y tecnológicos a efectos de la aplicación e interpretación de deducciones fiscales por actividades de investigación y desarrollo e innovación tecnológica.";
regimenDesc2 = "Ley 27/2014, de 27 de noviembre, del Impuesto sobre Sociedades. Artículo 35.";
break;
case "Alava":
regimenDescription = "Norma Foral 37/2013 de 13 de diciembre, de las Juntas Generales de Araba del Impuesto sobre Sociedades";
regimenDesc1 = string.Empty;
regimenDesc2 = string.Empty;
break;
case "Vizcaya":
regimenDescription = "Norma Foral 11/2013 de 5 de diciembre, de las Juntas Generales de Bizkaia del Impuesto sobre Sociedades";
regimenDesc1 = string.Empty;
regimenDesc2 = string.Empty;
break;
case "Guipuzcoa":
regimenDescription = "Norma Foral 2/2014 de 17 de enero, de las Juntas Generales de Gipuzkoa del Impuesto sobre Sociedades";
regimenDesc1 = string.Empty;
regimenDesc2 = string.Empty;
break;
default:
regimenDescription = string.Empty;
regimenDesc1 = string.Empty;
regimenDesc2 = string.Empty;
break;
}
if (!string.IsNullOrEmpty(regimenDescription))
{
document.Replace("{regimenDesc}", regimenDescription, false, false);
}
else
{
document.RemoveParagraphWithMarker("{regimenDesc}");
}
if (!string.IsNullOrEmpty(regimenDesc1))
{
document.Replace("{regimenDesc-2}", regimenDesc1, false, false);
}
else
{
document.RemoveParagraphWithMarker("{regimenDesc-2}");
}
if (!string.IsNullOrEmpty(regimenDesc2))
{
document.Replace("{regimenDesc-3}", regimenDesc2, false, false);
}
else
{
document.RemoveParagraphWithMarker("{regimenDesc-3}");
}
#endregion regimenDesc
if (isGlobalTechnicalMemory)
{
if (!string.IsNullOrEmpty(regimenDescription))
{
document.Replace("{regimenDesc}", regimenDescription, false, false);
}
else
{
document.RemoveParagraphWithMarker("{regimenDesc}");
}
if (!string.IsNullOrEmpty(regimenDesc1))
{
document.Replace("{regimenDesc-2}", regimenDesc1, false, false);
}
else
{
document.RemoveParagraphWithMarker("{regimenDesc-2}");
}
if (!string.IsNullOrEmpty(regimenDesc2))
{
document.Replace("{regimenDesc-3}", regimenDesc2, false, false);
}
else
{
document.RemoveParagraphWithMarker("{regimenDesc-3}");
}
bool certificateShow = projects.Any(x => x.Strategy == Strategy.IMV || x.Strategy == Strategy.NoIVMCertificate);
bool imvShow = projects.Any(x => x.Strategy == Strategy.IMV);
var projectsId = projects.Select(x => x.Id).ToList();
bool hasTechMem = context.Set<TechnicalMemory>().Any(x => projectsId.Contains(x.ProjectId) && x.IsFinalVersion);
if (hasTechMem)
{
document.Replace("{certificadoMemTec}", "", false, true);
}
else
{
document.RemoveParagraphWithMarker("{certificadoMemTec}");
}
if (certificateShow)
{
document.Replace("{certificadoDesc}", "", false, true);
}
else
{
document.RemoveParagraphWithMarker("{certificadoDesc}");
}
if (imvShow)
{
document.Replace("{IMVDesc}", "", false, true);
}
else
{
document.RemoveParagraphWithMarker("{IMVDesc}");
}
}
#endregion globalSheets
// Copy Header and Footer
//CopyHeaderFooter(document);
//Actualizar Summary
try
{
document.UpdateTableOfContents();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error updating table of contents in EconomicMemoryIndex");
}
var TempStream = new MemoryStream();
//Create File
document.SaveToStream(TempStream, FileFormat.Docx2013);
var bufferresult = TempStream.GetBytes();
//kill stream
TempStream.Close();
//Return Buffer
return await Task.FromResult(bufferresult);
}