Example #1
0
        /// <inheritdoc/>
        public async Task GenerateAndStoreReceiptPDF(Instance instance)
        {
            string      app             = instance.AppId.Split("/")[1];
            string      org             = instance.Org;
            int         instanceOwnerId = int.Parse(instance.InstanceOwner.PartyId);
            Application application     = _appResourcesService.GetApplication();
            Guid        instanceGuid    = Guid.Parse(instance.Id.Split("/")[1]);

            DataType dataModelDataElement     = application.DataTypes.Find(element => element.AppLogic != null);
            Guid     dataModelDataElementGuid = Guid.Parse(instance.Data.Find(element => element.DataType.Equals(dataModelDataElement.Id))?.Id);

            Stream dataStream = await _dataService.GetBinaryData(org, app, instanceOwnerId, instanceGuid, dataModelDataElementGuid);

            byte[] dataAsBytes = new byte[dataStream.Length];
            await dataStream.ReadAsync(dataAsBytes);

            string encodedXml = System.Convert.ToBase64String(dataAsBytes);

            byte[] formLayout    = _appResourcesService.GetAppResource(org, app, _appSettings.FormLayoutJSONFileName);
            byte[] textResources = _appResourcesService.GetText(org, app, "resource.nb.json");

            string formLayoutString    = GetUTF8String(formLayout);
            string textResourcesString = GetUTF8String(textResources);

            PDFContext pdfContext = new PDFContext
            {
                Data          = encodedXml,
                FormLayout    = JsonConvert.DeserializeObject(formLayoutString),
                TextResources = JsonConvert.DeserializeObject(textResourcesString),
                Party         = await _registerService.GetParty(instanceOwnerId),
                Instance      = instance
            };

            Stream pdfContent;

            try
            {
                pdfContent = await GeneratePDF(pdfContext);
            }
            catch (Exception exception)
            {
                _logger.LogError($"Could not generate pdf for {instance.Id}, failed with message {exception.Message}");
                return;
            }

            try
            {
                await StorePDF(pdfContent, instance);
            }
            catch (Exception exception)
            {
                _logger.LogError($"Could not store pdf for {instance.Id}, failed with message {exception.Message}");
                return;
            }
            finally
            {
                pdfContent.Dispose();
            }
        }
Example #2
0
        private async Task <Stream> GeneratePDF(PDFContext pdfContext)
        {
            using HttpContent data = new StringContent(JObject.FromObject(pdfContext, _camelCaseSerializer).ToString(), Encoding.UTF8, "application/json");
            HttpResponseMessage response = await _pdfClient.PostAsync("generate", data);

            response.EnsureSuccessStatusCode();
            Stream pdfContent = await response.Content.ReadAsStreamAsync();

            return(pdfContent);
        }
Example #3
0
        public Task <Stream> GeneratePDF(PDFContext pdfContext)
        {
            string unitTestFolder = Path.GetDirectoryName(new Uri(typeof(PDFMockSI).Assembly.CodeBase).LocalPath);
            string dataPath       = Path.Combine(unitTestFolder, @"..\..\..\Data\Files\print.pdf");

            Stream ms = new MemoryStream();

            using (FileStream file = new FileStream(dataPath, FileMode.Open, FileAccess.Read))
            {
                file.CopyTo(ms);
            }

            return(Task.FromResult(ms));
        }
Example #4
0
        private async Task GenerateAndStoreReceiptPDF(Instance instance, string taskId, DataElement dataElement, Type dataElementModelType)
        {
            string app             = instance.AppId.Split("/")[1];
            string org             = instance.Org;
            int    instanceOwnerId = int.Parse(instance.InstanceOwner.PartyId);
            Guid   instanceGuid    = Guid.Parse(instance.Id.Split("/")[1]);

            string     layoutSetsString = _resourceService.GetLayoutSets();
            LayoutSets layoutSets       = null;
            LayoutSet  layoutSet        = null;

            if (!string.IsNullOrEmpty(layoutSetsString))
            {
                layoutSets = JsonConvert.DeserializeObject <LayoutSets>(layoutSetsString);
                layoutSet  = layoutSets.Sets.FirstOrDefault(t => t.DataType.Equals(dataElement.DataType) && t.Tasks.Contains(taskId));
            }

            string layoutSettingsFileContent = layoutSet == null?_resourceService.GetLayoutSettingsString() : _resourceService.GetLayoutSettingsStringForSet(layoutSet.Id);

            LayoutSettings layoutSettings = null;

            if (!string.IsNullOrEmpty(layoutSettingsFileContent))
            {
                layoutSettings = JsonConvert.DeserializeObject <LayoutSettings>(layoutSettingsFileContent);
            }

            object data = await _dataService.GetFormData(instanceGuid, dataElementModelType, org, app, instanceOwnerId, new Guid(dataElement.Id));

            layoutSettings = await FormatPdf(layoutSettings, data);

            XmlSerializer serializer = new XmlSerializer(dataElementModelType);

            using MemoryStream stream = new MemoryStream();

            serializer.Serialize(stream, data);
            stream.Position = 0;

            byte[] dataAsBytes = new byte[stream.Length];
            await stream.ReadAsync(dataAsBytes);

            string encodedXml = Convert.ToBase64String(dataAsBytes);

            string          language    = "nb";
            Party           actingParty = null;
            ClaimsPrincipal user        = _httpContextAccessor.HttpContext.User;

            int?userId = user.GetUserIdAsInt();

            if (userId != null)
            {
                UserProfile userProfile = await _profileService.GetUserProfile((int)userId);

                actingParty = userProfile.Party;

                if (!string.IsNullOrEmpty(userProfile.ProfileSettingPreference?.Language))
                {
                    language = userProfile.ProfileSettingPreference.Language;
                }
            }
            else
            {
                string orgNumber = user.GetOrgNumber().ToString();
                actingParty = await _registerService.LookupParty(new PartyLookup { OrgNo = orgNumber });
            }

            // If layoutset exists pick correct layotFiles
            string formLayoutsFileContent = layoutSet == null?_resourceService.GetLayouts() : _resourceService.GetLayoutsForSet(layoutSet.Id);

            TextResource textResource = await _textService.GetText(org, app, language);

            if (textResource == null && language != "nb")
            {
                // fallback to norwegian if texts does not exist
                textResource = await _textService.GetText(org, app, "nb");
            }

            string textResourcesString = JsonConvert.SerializeObject(textResource);
            Dictionary <string, Dictionary <string, string> > optionsDictionary = await GetOptionsDictionary(formLayoutsFileContent);

            PDFContext pdfContext = new PDFContext
            {
                Data              = encodedXml,
                FormLayouts       = JsonConvert.DeserializeObject <Dictionary <string, object> >(formLayoutsFileContent),
                LayoutSettings    = layoutSettings,
                TextResources     = JsonConvert.DeserializeObject(textResourcesString),
                OptionsDictionary = optionsDictionary,
                Party             = await _registerService.GetParty(instanceOwnerId),
                Instance          = instance,
                UserParty         = actingParty,
                Language          = language
            };

            Stream pdfContent = await _pdfService.GeneratePDF(pdfContext);

            await StorePDF(pdfContent, instance, textResource);

            pdfContent.Dispose();
        }
Example #5
0
        /// <inheritdoc/>
        public async Task GenerateAndStoreReceiptPDF(Instance instance, DataElement dataElement)
        {
            string      app             = instance.AppId.Split("/")[1];
            string      org             = instance.Org;
            int         instanceOwnerId = int.Parse(instance.InstanceOwner.PartyId);
            Application application     = _appResourcesService.GetApplication();
            Guid        instanceGuid    = Guid.Parse(instance.Id.Split("/")[1]);

            Stream dataStream = await _dataService.GetBinaryData(org, app, instanceOwnerId, instanceGuid, new Guid(dataElement.Id));

            byte[] dataAsBytes = new byte[dataStream.Length];
            await dataStream.ReadAsync(dataAsBytes);

            string encodedXml = Convert.ToBase64String(dataAsBytes);

            UserContext userContext = await _userHelper.GetUserContext(_httpContextAccessor.HttpContext);

            UserProfile userProfile = await _profileService.GetUserProfile(userContext.UserId);

            byte[]       formLayout   = _appResourcesService.GetAppResource(org, app, _appSettings.FormLayoutJSONFileName);
            TextResource textResource = await _textService.GetText(org, app, userProfile.ProfileSettingPreference.Language);

            string formLayoutString    = GetUTF8String(formLayout);
            string textResourcesString = JsonConvert.SerializeObject(textResource);

            PDFContext pdfContext = new PDFContext
            {
                Data          = encodedXml,
                FormLayout    = JsonConvert.DeserializeObject(formLayoutString),
                TextResources = JsonConvert.DeserializeObject(textResourcesString),
                Party         = await _registerService.GetParty(instanceOwnerId),
                Instance      = instance,
                UserProfile   = userProfile,
                UserParty     = userProfile.Party
            };

            Stream pdfContent;

            try
            {
                pdfContent = await GeneratePDF(pdfContext);
            }
            catch (Exception exception)
            {
                _logger.LogError($"Could not generate pdf for {instance.Id}, failed with message {exception.Message}");
                return;
            }

            try
            {
                await StorePDF(pdfContent, instance, textResource);
            }
            catch (Exception exception)
            {
                _logger.LogError($"Could not store pdf for {instance.Id}, failed with message {exception.Message}");
                return;
            }
            finally
            {
                pdfContent.Dispose();
            }
        }
 public PDFRepositoryController(PDFContext context)
 {
     _context = context;
 }