Example #1
0
 public bool GantiMergeField(string docPath, string savePath, Dictionary <string, string> raportDict)
 {
     try
     {
         byte[] byteArray = File.ReadAllBytes(docPath);
         using (var stream = new MemoryStream())
         {
             stream.Write(byteArray, 0, byteArray.Length);
             using (WordprocessingDocument document = WordprocessingDocument.Open(stream, true))
             {
                 document.ChangeDocumentType(WordprocessingDocumentType.Document);
                 foreach (var item in raportDict)
                 {
                     document.GetMergeFields(item.Key).ReplaceWithText(item.Value);
                 }
                 document.MainDocumentPart.Document.Save();
             }
             stream.Position = 0;
             File.WriteAllBytes(savePath, stream.ToArray());
         }
         return(true);
     }
     catch (Exception)
     {
         throw;
     }
 }
Example #2
0
    public static void SearchAndReplace(string document, Dictionary <string, string> replaceDictionary)
    {
        using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
        {
            //string docText = null;
            //using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
            //{
            //    docText = sr.ReadToEnd();
            //}

            // Regex regexText;

            foreach (string key in replaceDictionary.Keys)
            {
                //regexText = new Regex(key);
                //docText = regexText.Replace(docText, replaceDictionary[key]);


                wordDoc.GetMergeFields(key).ReplaceWithText(replaceDictionary[key]);

                //document.MainDocumentPart.Document.Save();
            }


            //using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
            //{
            //    sw.Write(docText);
            //}



            //repeatElement(wordDoc);
        }
    }
Example #3
0
 public void ChangeMergeFields(string docName, Dictionary <string, string> raportDict, string targetfile)
 {
     using (WordprocessingDocument document = WordprocessingDocument.Open(docName, true))
     {
         foreach (var item in raportDict)
         {
             document.GetMergeFields(item.Key).ReplaceWithText(item.Value);
         }
     }
 }
Example #4
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
        {
            log.LogInformation("Generating document");

            try
            {
                var data = await Helpers.GetModelFromBodyAsync <GenerateDocumentModel>(req.Body);

                if (data == null)
                {
                    return(new BadRequestObjectResult("Posted data are not correct"));
                }

                var container = await Helpers.GetContainerAsync(Environment.GetEnvironmentVariable(Constants.TemplatesContainerName));

                var blob = container.GetBlockBlobReference(data.BlobName);

                byte[] bytes = null;
                using (var stream = new MemoryStream())
                {
                    await blob.DownloadToStreamAsync(stream);

                    await blob.FetchAttributesAsync();

                    log.LogInformation("Blob downloaded");

                    using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))
                    {
                        foreach (var field in data.Fields)
                        {
                            if (!string.IsNullOrEmpty(field.Value))
                            {
                                string name = field.Name;
                                if (name.Contains(" "))
                                {
                                    name = "\"" + name + "\"";
                                }

                                doc.GetMergeFields(name).ReplaceWithText(field.Value);
                            }
                        }

                        var todayField = doc.GetMergeFields("dnes");
                        if (todayField.Count() > 0)
                        {
                            todayField.ReplaceWithText(DateTime.Now.ToString("d. MMMM yyyy", new CultureInfo("cs")));
                        }

                        doc.MainDocumentPart.Document.Save();
                        doc.Close();

                        bytes = new byte[stream.Length];
                        bytes = stream.ToArray();
                    }
                }

                log.LogInformation($"Document generated with length {bytes.Length}");
                return(new FileContentResult(bytes, blob.Properties.ContentType));
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                throw ex;
            }
        }
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
        {
            log.LogInformation("Procesing template");

            try
            {
                var data = await Helpers.GetModelFromBodyAsync <TemplateModel>(req.Body);

                if (data == null)
                {
                    log.LogWarning("Posted data are not correct");
                    return(new BadRequestObjectResult("Posted data are not correct"));
                }

                var container = await Helpers.GetContainerAsync(Environment.GetEnvironmentVariable(Constants.TemplatesContainerName));

                var blob = container.GetBlockBlobReference(data.BlobName);

                var fields = new List <string>();
                using (var sourceStream = new MemoryStream())
                {
                    await blob.DownloadToStreamAsync(sourceStream);

                    using (WordprocessingDocument doc = WordprocessingDocument.Open(sourceStream, false))
                    {
                        foreach (var field in doc.GetMergeFields())
                        {
                            string fieldName = OpenXmlWordHelpers.GetFieldNameFromMergeField(field.InnerText).Trim('\"');
                            if (!fields.Contains(fieldName) && fieldName.Trim() != "PAGE")
                            {
                                fields.Add(fieldName);
                            }
                        }
                    }
                }

                blob.Metadata.Add("name", Uri.EscapeDataString(data.Name));

                if (!string.IsNullOrEmpty(data.Description))
                {
                    blob.Metadata.Add("description", Uri.EscapeDataString(data.Description));
                }

                string fieldsString = string.Join(";", fields);
                if (fields.Count > 0)
                {
                    blob.Metadata.Add("fields", Uri.EscapeDataString(fieldsString));
                }
                else
                {
                    log.LogWarning("No fields were found");
                }

                await blob.SetMetadataAsync();

                log.LogInformation("Template processed");

                return(new OkObjectResult(new TemplateModel()
                {
                    Name = data.Name,
                    BlobName = data.BlobName,
                    Description = data.Description,
                    Fields = Helpers.GetFieldsWithoutHiddenArray(fieldsString)
                }));
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                throw ex;
            }
        }