Ejemplo n.º 1
0
        public static void SearchAndReplace(string template, string path, string currentUser, string period, List <ViewModels.UserTableViewModel> stats)
        {
            WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(template, false);
            var newDoc = wordprocessingDocument.Clone();

            File.Copy(template, path);
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(path, true))
            {
                string docText = null;

                using (StreamReader sr = new StreamReader(wordDocument.MainDocumentPart.GetStream()))
                {
                    docText = sr.ReadToEnd();
                }

                docText = ReplaceByWord(docText, "currentDateTempl", DateTime.Now.ToString("dd.MM.yyyy"));
                docText = ReplaceByWord(docText, "currentUser", currentUser);
                docText = ReplaceByWord(docText, "period", period);

                using (StreamWriter sw = new StreamWriter(wordDocument.MainDocumentPart.GetStream(FileMode.OpenOrCreate)))
                {
                    sw.Write(docText);
                }
                EditTable(wordDocument, stats);
                wordDocument.Save();
            }
        }
Ejemplo n.º 2
0
        public virtual byte[] GenerateDocumentFromTemplate(Stream templateStream, string xmlData)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                templateStream.CopyTo(memoryStream);

                using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memoryStream, true))
                {
                    var mainPart = wordDoc.MainDocumentPart;
                    mainPart.DeleteParts(mainPart.CustomXmlParts);
                    var myXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml);

                    var byteArray = Encoding.UTF8.GetBytes(xmlData);

                    using (MemoryStream stream = new MemoryStream(byteArray))
                    {
                        myXmlPart.FeedData(stream);
                    }

                    wordDoc.Save();
                    byteArray = memoryStream.ToArray();

                    return(byteArray);
                }
            }
        }
Ejemplo n.º 3
0
        public void Merge()
        {
            using (WordprocessingDocument doc = OpenCopyWord(GetPath("week.docx"), GetPath("WordMergerTestResult.docx")))
            {
                //находим место для вставки
                var placeToPasteSchedule = doc.MainDocumentPart.Document.Body
                                           .FindElementsByText(weekVar)
                                           .FirstOrDefault();

                if (placeToPasteSchedule != null)
                {
                    //ищем нужный шаблон дня

                    using (var dayDoc = OpenWord(GetPath("0.docx"), false))
                    {
                        var body = dayDoc.MainDocumentPart.Document.Body.Elements();
                        foreach (var ins in body)
                        {
                            var clone = ins.CloneNode(true);
                            placeToPasteSchedule.InsertBeforeSelf(clone);
                        }

                        placeToPasteSchedule.Parent.RemoveChild(placeToPasteSchedule);

                        doc.Save();
                        //doc.SaveAs(GetPath("WordMergerTestResult.docx"));
                    }
                }
            }

            Assert.Pass("Success");
        }
        public static string CreateReceipt(Order order, string templateFileName, string receiptFileName)
        {
            File.Copy(templateFileName, receiptFileName);
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(receiptFileName, true))
            {
                string docText = null;

                using (StreamReader sr = new StreamReader(wordDocument.MainDocumentPart.GetStream()))
                {
                    docText = sr.ReadToEnd();
                }
                EditTable(wordDocument, order);
                docText = ReplaceByWord(docText, "ClientName", order.Client.Name);
                docText = ReplaceByWord(docText, "ClientEmail", order.Client.Email);
                docText = ReplaceByWord(docText, "OrderID", order.ID.ToString());
                docText = ReplaceByWord(docText, "Total", (from game in order.Game
                                                           select game.Price).Sum().ToString());

                using (StreamWriter sw = new StreamWriter(wordDocument.MainDocumentPart.GetStream(FileMode.OpenOrCreate)))
                {
                    sw.Write(docText);
                }
                wordDocument.Save();
                return(receiptFileName);
            }
        }
Ejemplo n.º 5
0
        public void Main(List <MetrologyObjectDTO> items, string filename)
        {
            string filePath     = filename + ".docx";
            string templatePath = HttpContext.Current.Request.PhysicalApplicationPath + @"WordTemplates\" + "LableTemplate.docx";

            File.Copy(templatePath, filePath, true);
            WordprocessingDocument wordprocessingDocument =
                WordprocessingDocument.Open(filePath, true);
            Body body     = wordprocessingDocument.MainDocumentPart.Document.Body;
            var  template = body.FirstChild.LastChild.LastChild.CloneNode(true);

            body.FirstChild.LastChild.Remove();
            for (var i = 0; i <= (items.Count - items.Count % 4) / 4; i++)
            {
                var row = new TableRow();
                for (var j = 0; j < 4 && j < items.Count - i * 4; j++)
                {
                    var cell = template.CloneNode(true);
                    cell.InnerXml = cell.InnerXml.Replace("BRANCH", items[i * 4 + j].OwnerBranchTitle.ToString());
                    cell.InnerXml = cell.InnerXml.Replace("DEPARTMENT", items[i * 4 + j].OwnerDepartmentTitle.ToString());
                    cell.InnerXml = cell.InnerXml.Replace("TYPE", items[i * 4 + j].TypeAOTitle.ToString());
                    cell.InnerXml = cell.InnerXml.Replace("FACTNUM", items[i * 4 + j].FactoryNumber.ToString());
                    cell.InnerXml = cell.InnerXml.Replace("ACCOUTNUM", items[i * 4 + j].AccountingNumber.ToString());
                    cell.InnerXml = cell.InnerXml.Replace("DATE", items[i * 4 + j].MetrologicalWorkDatePlanStr.ToString());
                    row.Append(cell);
                }
                if (row.InnerXml.Length > 0)
                {
                    body.FirstChild.Append(row);
                }
            }
            wordprocessingDocument.Save();
            wordprocessingDocument.Close();
        }
Ejemplo n.º 6
0
        public static void InsertImages(string fullPathToDocument, List <KeyValuePair <string, List <string> > > pictures)
        {
            WordprocessingDocument wordDoc = WordprocessingDocument.Open(fullPathToDocument, true);
            string currentHeader           = "";

            foreach (var keyValuePair in pictures)
            {
                if (currentHeader != keyValuePair.Key)
                {
                    if (currentHeader != "")
                    {
                        SectionProperties sectPr = (SectionProperties)wordDoc.MainDocumentPart.Document.Body.ChildElements.Last();

                        wordDoc.MainDocumentPart.Document.Body.InsertBefore(
                            new Paragraph(
                                new Run(
                                    new Break()
                        {
                            Type = BreakValues.Page
                        }
                                    )),
                            sectPr
                            );
                    }
                    InsertHeader(keyValuePair.Key, wordDoc, currentHeader);
                }

                currentHeader = keyValuePair.Key;
                InsertPicture(keyValuePair.Value, wordDoc);
            }

            wordDoc.Save();
            wordDoc.Close();
            wordDoc.Dispose();
        }
        private void run(string vorname, string nachname)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Create(@"C:\\TestDoc\test.docx", DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = doc.AddMainDocumentPart();
                var body = new Body();
                mainPart.Document = new Document(body);

                //insert content control, find and replace text in content control.
                this.InsertContentControl(body, "=fullname", "Beispiel Text");
                this.ReplaceTextInContentControlByTag(body, "=fullname", vorname + " " + nachname);
                this.InsertCheckbox(body);

                //create paragraph, apply custom style
                Paragraph paragraph = new Paragraph(new Run(new Text("Paragraph Style")));
                paragraph.ParagraphId = "paragraph1";

                this.CreateStyle(doc, "1", "myCustomStyle");
                this.ApplyStyleById(doc, paragraph, "1");

                //find paragraph example
                Paragraph firstParagraph =
                    body.Elements <Paragraph>().Where(w => w.ParagraphId == "paragraph1").FirstOrDefault();

                doc.Save();
            }
        }
Ejemplo n.º 8
0
        public void RemoveHeaderIfParagraphs(string filePath, string mergefieldName = "DEBTOR__Middle_name")
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
            {
                string completeMergeFieldName = $"MERGEFIELD {mergefieldName} ";

                var fieldsWithMergefieldName = doc.MainDocumentPart.RootElement.Descendants <FieldCode>().Where(x => x.Text.Contains(mergefieldName));

                Console.WriteLine($"There are {fieldsWithMergefieldName.Count()} fields in the document.");
                int incrementer = 0;

                foreach (FieldCode field in fieldsWithMergefieldName)
                {
                    incrementer++;
                    Console.WriteLine($"We have checked the fields {incrementer} times.");
                    var paragraph         = field.Ancestors <Paragraph>().FirstOrDefault();
                    var previousParagraph = paragraph?.PreviousSibling();
                    if (previousParagraph == null)
                    {
                        continue;
                    }
                    if (previousParagraph.Descendants <FieldCode>().Any(x => x.Text.Contains(mergefieldName)))
                    {
                        paragraph.PreviousSibling().Remove();
                    }
                }
                //int seconds = DateTime.Now.Second;
                //doc.SaveAs(filePath.Remove(filePath.Length - 5, 5) + seconds + ".docx");
                doc.Save();
            }
        }
        public async Task GenerateContract(Dictionary <string, string> valuePairs, IEnumerable <Equipment> equipments, string filePath)
        {
            await Task.Factory.StartNew(() =>
            {
                string docText = "";
                using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(templateFile, true))
                {
                    using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                    {
                        docText = sr.ReadToEnd();
                    }

                    docText = ReplaceMarkersByValues(valuePairs, docText);

                    var savedDoc = wordDoc.SaveAs(filePath);
                    savedDoc.Close();
                }
                using (WordprocessingDocument generatedDocument = WordprocessingDocument.Open(filePath, true))
                {
                    using (StreamWriter sw = new StreamWriter(generatedDocument.MainDocumentPart.GetStream(FileMode.Create)))
                    {
                        sw.Write(docText);
                    }
                    FillTable(equipments, generatedDocument);
                    generatedDocument.Save();
                }
            });
        }
Ejemplo n.º 10
0
        public void HtmlToWordPartial(string html, string destinationFileName)
        {
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(destinationFileName, WordprocessingDocumentType.Document))
            {
                string altChunkId = "myId";

                MainDocumentPart mainPart = wordDocument.MainDocumentPart;
                if (mainPart == null)
                {
                    mainPart = wordDocument.AddMainDocumentPart();
                    new DocumentFormat.OpenXml.Wordprocessing.Document(new Body()).Save(mainPart);
                }
                MemoryStream ms = new MemoryStream(new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(html)).ToArray());

                // Uncomment the following line to create an invalid word document.
                // MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<h1>HELLO</h1>"));

                // Create alternative format import part.
                AlternativeFormatImportPart formatImportPart = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId);
                //ms.Seek(0, SeekOrigin.Begin);

                // Feed HTML data into format import part (chunk).
                formatImportPart.FeedData(ms);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                mainPart.Document.Body.Append(altChunk);
                wordDocument.Save();
                wordDocument.Close();
            }
        }
        public void CreateMaintenanceRequestReport(MaintRequestInitiation maintReqSingle)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Open(@"C:\Users\cabuk\Desktop\maintreqdetails.docx", true))
            {
                var document = doc.MainDocumentPart.Document;

                //loop through the preoprties of the maintenance request initation object
                foreach (PropertyInfo prop in maintReqSingle.GetType().GetProperties())
                {
                    //loop through the text in the word document
                    foreach (var text in document.Descendants <Text>())
                    {
                        //if the text found is equal to the proeprtyname then put text there
                        //the placeholder in the word document is {propertyname}
                        if (text.Text == "{" + prop.Name + "}")
                        {
                            var type = prop.Name;

                            if (prop.Name == "Factory")
                            {
                                text.Text = text.Text.Replace("{Factory}", maintReqSingle.Factory.FactoryName);
                            }
                            else
                            {
                                text.Text = text.Text.Replace(prop.Name, prop.GetValue(maintReqSingle, null).ToString());
                            }
                        }
                    }
                }

                doc.Save();
            }
        }
Ejemplo n.º 12
0
        public static void FillTemplate(string wordTemplateFile, IDictionary <string, string> data, string idKey)
        {
            var wordTemplate   = Path.Combine(InPath, wordTemplateFile);
            var targetFileName = $"{Path.GetFileNameWithoutExtension(wordTemplate)} - {data[idKey]}{Path.GetExtension(wordTemplate)}";
            var targetFilePath = Path.Combine(OutPath, targetFileName);

            File.Copy(wordTemplate, targetFilePath, true);

            using (WordprocessingDocument myDoc = WordprocessingDocument.Open(targetFilePath, true))
            {
                MainDocumentPart mainPart = myDoc.MainDocumentPart;

                Document doc = mainPart.Document;

                var xml = new StringBuilder(doc.InnerXml);

                foreach (var entry in data)
                {
                    xml.Replace(entry.Key, entry.Value);
                }

                doc.InnerXml = xml.ToString();

                myDoc.Save();
            }
        }
Ejemplo n.º 13
0
        public static void InsrtRows(string fileName)
        {
            // Use the file name and path passed in as an argument
            // to open an existing Word 2007 document.

            using (WordprocessingDocument doc
                       = WordprocessingDocument.Open(fileName, true))
            {
                // Find the first table in the document.
                Table table =
                    doc.MainDocumentPart.Document.Body.Elements <Table>().First();
                var row = table.Elements <TableRow>().ElementAt(0);

                var rowClone = (TableRow)row.Clone();

                var cell = rowClone.Elements <TableCell>().ElementAt(0);
                SetCellValue(cell, "10000");
                // rowClone.Append(cell);

                cell = rowClone.Elements <TableCell>().ElementAt(1);
                SetCellValue(cell, "123.45");
                //rowClone.Append(cell);

                table.Append(rowClone);

                doc.Save();
            }
        }
Ejemplo n.º 14
0
        string pathFolder = "";           // путь к файлу

        /// <summary>
        /// Начать работу с документом шаблоном
        /// </summary>
        /// <param name="type">тип документа</param>
        /// <param name="name">имя документа</param>
        public void Run(string type, string name)
        {
            _bookMarks = new List <string>();
            switch (type)
            {
            case TypeDocs._act:
                pathFile   = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._act + "\\" + name;
                pathFolder = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._act + "\\" + DateTime.Now.ToString("dd-MM-yy-hh-mm-ss");
                break;

            case TypeDocs._agreement:
                pathFile   = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._agreement + "\\" + name;
                pathFolder = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._agreement + "\\" + DateTime.Now.ToString("dd-MM-yy-hh-mm-ss");
                break;

            case TypeDocs._blank:
                pathFile   = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._blank + "\\" + name;
                pathFolder = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._blank + "\\" + DateTime.Now.ToString("dd-MM-yy-hh-mm-ss");
                break;

            case TypeDocs._reference:
                pathFile   = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._reference + "\\" + name;
                pathFolder = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._reference + "\\" + DateTime.Now.ToString("dd-MM-yy-hh-mm-ss");
                break;
            }
            Directory.CreateDirectory(pathFolder);
            File.Copy(pathFile, Path.Combine(pathFolder, name));
            pathFolder += "\\" + name;
            _document   = WordprocessingDocument.Open(pathFolder, true);
            _body       = _document.MainDocumentPart.Document.Body;
            FindMarks(_body);
            WorkWithText(_body);
            _document.Save();
            _document.Dispose();
        }
Ejemplo n.º 15
0
 public static string CreateReport(
     DateTime dateFrom,
     DateTime dateTo,
     List <GamesToReportViewModel> list,
     string templateFileName,
     string receiptFileName)
 {
     File.Copy(templateFileName, receiptFileName);
     using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(receiptFileName, true))
     {
         string docText = null;
         using (StreamReader sr = new StreamReader(wordDocument.MainDocumentPart.GetStream()))
         {
             docText = sr.ReadToEnd();
         }
         docText = ReplaceByWord(docText, "dateFrom", dateFrom.ToString("dd-MM-yyyy"));
         docText = ReplaceByWord(docText, "dateTo", dateTo.ToString("dd-MM-yyyy"));
         docText = ReplaceByWord(docText, "Total", (from game in list select game.Total).Sum().ToString() + " ₽");
         using (StreamWriter sw = new StreamWriter(wordDocument.MainDocumentPart.GetStream(FileMode.OpenOrCreate)))
         {
             sw.Write(docText);
         }
         wordDocument.Save();
         EditTable(wordDocument, list);
         return(receiptFileName);
     }
 }
Ejemplo n.º 16
0
        private static void FillByTemplate(WordprocessingDocument doc, TemplateData template)
        {
            try
            {
                if (template != null)
                {
                    Body body = doc.MainDocumentPart.Document.Body;

                    FillTable(body.Descendants <Table>(), template.Tables);
                    FillShape(body.Descendants <WordprocessingShape>(), template.TextShapes);
                    foreach (HeaderPart headerPart in doc.MainDocumentPart.HeaderParts)
                    {
                        FillShape(headerPart.Header.Descendants <WordprocessingShape>(), template.HeaderTextShape);
                    }
                    foreach (FooterPart footerPart in doc.MainDocumentPart.FooterParts)
                    {
                        FillShape(footerPart.Footer.Descendants <WordprocessingShape>(), template.FooterTextShapes);
                    }

                    doc.Save();
                }
                doc.Close();
            }
            catch (Exception e)
            {
                doc.Close();
                throw e;
            }
        }
Ejemplo n.º 17
0
 public void Dispose()
 {
     if (_wordDocx != null)
     {
         _wordDocx.Save();
         _wordDocx.Dispose();
     }
 }
Ejemplo n.º 18
0
        private static void DealWithWord(string path)
        {
            //using (WordprocessingDocument doc = WordprocessingDocument.Open(path, true))
            //{
            //    MainDocumentPart mainPart = doc.MainDocumentPart;
            //    Hyperlink hLink = mainPart.Document.Body.Descendants<Hyperlink>().FirstOrDefault();
            //    if (hLink != null)
            //    {
            //        // get hyperlink's relation Id (where path stores)
            //        string relationId = hLink.Id;
            //        if (relationId != string.Empty)
            //        {
            //            // get current relation
            //            HyperlinkRelationship hr = mainPart.HyperlinkRelationships.Where(a => a.Id == relationId).FirstOrDefault();
            //            if (hr != null)
            //            // remove current relation
            //            { mainPart.DeleteReferenceRelationship(hr); }
            //            //add new relation with same Id , but new path
            //            mainPart.AddHyperlinkRelationship(new System.Uri(@"D:\work\DOCS\new\My.docx", System.UriKind.Absolute), true, relationId);
            //        }
            //    }
            //    // apply changes
            //    doc.Close();
            //}

            //02  code demo
            using (WordprocessingDocument doc = WordprocessingDocument.Open(path, true))
            {
                var body = doc.MainDocumentPart.Document.Body;
                foreach (OpenXmlElement paragraph in body.Elements())
                {
                    foreach (OpenXmlElement item in paragraph.Elements <OpenXmlElement>())
                    {
                        if (item.InnerText.Contains("HYPERLINK") || item.InnerText.Contains("hyperlink"))
                        {
                            Regex regexText = new Regex("[\u4e00-\u9fa5]+");
                            if (regexText.IsMatch(item.InnerText))
                            {
                                string thisInnerText = item.InnerText.Trim();

                                //02  remove link
                                Regex regexLink = new Regex("^HYPERLINK \\\"((https|http)?:\\/\\/)[^\\s]+");
                                foreach (Match match in regexLink.Matches(thisInnerText.Trim()))
                                {
                                    item.InnerXml = thisInnerText.Replace(match.Value, "").Trim();
                                }
                            }
                            else
                            {
                                item.Remove();
                            }
                        }
                    }
                }
                doc.Save();
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Создать пустой документ
        /// </summary>
        /// <param name="path"></param>
        public static void CreateDoc(string path)
        {
            WordprocessingDocument doc = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document);

            doc.AddMainDocumentPart();
            doc.MainDocumentPart.Document = new Document(new Body());
            doc.Save();
            doc.Close();
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            Console.WriteLine("Processing document");

            //Find File
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string filepath    = Path.Combine(desktopPath + @"\WordFile\test_xml.docx");

            //Save Original File
            string originalFilename = Path.GetFileNameWithoutExtension(filepath);
            var    originalFile     = Path.Combine(desktopPath, @"WordFile\" + originalFilename + "-v1.docx");

            System.IO.File.Copy(filepath, originalFile);

            //Load File
            WordprocessingDocument doc = WordprocessingDocument.Open(filepath, true);
            Body body = doc.MainDocumentPart.Document.Body;

            //Find Title Paragraph
            IEnumerable <Paragraph> paragraphs = body.Elements <Paragraph>();
            string    title          = "A method to work with Mri devices";
            Paragraph titleParagraph = null;

            foreach (Paragraph p in paragraphs)
            {
                string text = p.InnerText;
                if (text.Equals(title))
                {
                    titleParagraph = p;
                }
            }

            //Replace Title Text
            string correctedTitle = "A Method to Work with MRI Devices";

            foreach (Run r in titleParagraph.Elements <Run>())
            {
                foreach (Text t in r.Elements <Text>())
                {
                    t.Text = "";
                }
            }
            Run run = titleParagraph.AppendChild(new Run());

            run.AppendChild(new Text(correctedTitle));

            //Apply Paragraph Style
            ApplyStyleToParagraph(doc, "H1", "Heading1", titleParagraph);

            //Close and Save File
            doc.Save();
            doc.Close();

            Console.WriteLine("Done");
            Console.ReadLine();
        }
Ejemplo n.º 21
0
 public void FixTextValue(string filePath, string incorrectValue = "Harry", string correctValue = "Harold")
 {
     // Updates an incorrect value of a complex mergefield with a correct value
     using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
     {
         var runs = doc.MainDocumentPart.Document.Descendants <Run>();
         _service.FixIncorrectTextValue(runs, incorrectValue, correctValue);
         doc.Save();
     }
 }
Ejemplo n.º 22
0
        /// <summary>
        /// Remove the document protection elements from an DOCX (WordprocessingDocument) file
        /// </summary>
        /// <param name="filename">DOCX file to remove protection</param>
        public void UnprotectDocx(string filename)
        {
            using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filename, true))
            {
                wordprocessingDocument.MainDocumentPart.DocumentSettingsPart.Settings.RemoveAllChildren <DocumentProtection>();

                wordprocessingDocument.Save();

                wordprocessingDocument.Close();
            }
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Sets the document public properties
 /// </summary>
 /// <param name="document">WordprocessingDocument reference</param>
 /// <param name="title">Document title</param>
 /// <param name="description">Document description</param>
 /// <param name="creator">Creator</param>
 /// <param name="category">Category</param>
 /// <param name="lastModifiedBy">Person that last modified</param>
 public static void SetProperties(this WordprocessingDocument document, string title, string description = null, string creator = null, string category = null, string lastModifiedBy = null)
 {
     //Add Document properties
     document.PackageProperties.Title          = title ?? @"Reporte";
     document.PackageProperties.Creator        = creator ?? @"Israel Ch";
     document.PackageProperties.Category       = category ?? @"Reporte";
     document.PackageProperties.Description    = description ?? @"Reporte tipo listado";
     document.PackageProperties.LastModifiedBy = lastModifiedBy ?? @"Israel Ch";
     //Save all changes
     document.Save();
 }
Ejemplo n.º 24
0
        /// <summary>
        /// The field values in the word doc need to be update in the property settings object of the word doc. The questions
        /// have 'keys' which we are using with MappingsEnum to know how update with the value from the IntakeForms. Then we
        /// explicitly ask the user to verify the fields are to be updated when opening the word doc.
        /// </summary>
        /// <param name="intakeForms"></param>
        /// <param name="doc"></param>
        private void UpdateValuesInWordDocsCustomProperties(
            WordprocessingDocument doc,
            IntakeFormModel intakeForm,
            PatientModel patient,
            PhysicianModel physician,
            ICollection <SignatureModel> signatures)
        {
            // Get all question's with a key, then gather the value as all answers comma delimited
            var intakeFromKeys = intakeForm.Questions
                                 .Where(r => !string.IsNullOrEmpty(r.Key))
                                 .Select(y => new KeyValuePair <string, string>(y.Key.ToUpper(), y.Answers.Select(z => z.Text)
                                                                                .Aggregate((c, n) => $"{c},{n}"))).ToList();

            intakeFromKeys.AddRange(GetPatientKeys(patient));
            intakeFromKeys.AddRange(GetAllCodes(intakeForm));
            intakeFromKeys.AddRange(GetPhysicanKeys(physician));
            intakeFromKeys.AddRange(GetSignature(signatures.First())); // just use the first signature for now since IP/Creation should be identicalish
            intakeFromKeys.AddRange(GetDrNotes(intakeForm.PhysicianNotes ?? ""));

            //This will update all of the custom properties that are used in the word doc.
            //Again, the fields are update in the document settings, but the downloading user
            //will need to approve the update for any fields.

            //https://docs.microsoft.com/en-us/office/open-xml/how-to-set-a-custom-property-in-a-word-processing-document
            Properties properties = doc.CustomFilePropertiesPart.Properties;

            foreach (MappingEnums propertyEnum in Enum.GetValues(typeof(MappingEnums)))
            {
                var item = (CustomDocumentProperty)properties
                           .FirstOrDefault(x => ((CustomDocumentProperty)x).Name.Value.Equals(propertyEnum.ToString()));
                if (item != null)
                {
                    //If a key doesn't exist, you could see an empty value stuffed into the word doc
                    var val = intakeFromKeys.FirstOrDefault(x => x.Key == propertyEnum.ToString().ToUpper()).Value ?? "N/A";
                    item.VTLPWSTR = new VTLPWSTR(val);
                }
            }

            properties.Save();

            //The docx is using Custom Properties and above we are updating the custom property values,
            //however there is no way (that I have found) to programatically updated all of the fields
            //that are using the custom properties without requiring the downloader to
            DocumentSettingsPart settingsPart = doc.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();
            var updateFields = new UpdateFieldsOnOpen
            {
                Val = new OnOffValue(true)
            };

            settingsPart.Settings.PrependChild(updateFields);
            settingsPart.Settings.Save();
            doc.Save();
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Saves the document to the underlying stream. Does not write out the document to the file system until Close() is called.
        /// </summary>
        public void Save()
        {
            Settings.Save();
            Styles.Save();

            MainDocumentPart.Document.Save();

            SaveHeaders();
            SaveFooters();

            document.Save();
        }
Ejemplo n.º 26
0
 public void Save()
 {
     mainDocumentPart.Document.Save();
     wordProcessingDocument.Save();
     //rewriting whole file
     using (Stream stream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
     {
         using (OpenXmlPackage docfile = wordProcessingDocument.Clone(stream))
         {
             docfile.Save();
         }
     }//stream is not automaticaly closed when document closed (when using Clone)
 }
Ejemplo n.º 27
0
        public void ParseCore()
        {
            var list = new List <(string replacedString, string replacingString)>();

            using (WordprocessingDocument document = WordprocessingDocument.Open(this.ResultWordFileFullName, true))
            {
                this.SimpleLabelReplacement(this.Result, document);

                this.SetStatistcisTable(this.Result, document);

                this.SetTestingTools(this.Result, document);

                //再处理一下finnaly notes.

                var text = document.MainDocumentPart.Document.Body.Descendants <Text>().Where(t => t.Text == "{{finnallynotes}}").FirstOrDefault();
                if (text != null)
                {
                    var run       = (Run)text.Parent;
                    var paragraph = (Paragraph)run.Parent;

                    var paragraphParent = paragraph.Parent;

                    var addedparagraph = paragraph;

                    for (var i = 0; i < this.Result.FinallyNotes.Count; i++)
                    {
                        this.Result.FinallyNotes[i] = (i + 1).ToString() + "." + this.Result.FinallyNotes[i];
                    }
                    for (var i = 0; i < this.Result.FinallyNotes.Count; i++)
                    {
                        if (i > 0)
                        {
                            paragraph = (Paragraph)paragraph.Clone();
                        }
                        paragraph.Elements <Run>().ToList()[0].Elements <Text>().ToList()[0].Text = this.Result.FinallyNotes[i];
                        if (i > 0)
                        {
                            paragraphParent.InsertAfter(paragraph, addedparagraph);
                        }
                        addedparagraph = paragraph;
                    }
                }


                this.Result.FinallyNotes.ForEach(fullString =>
                {
                    document.SetNumberStyle(fullString);
                });
                document.Save();
            }
        }
Ejemplo n.º 28
0
        private void ParseCore()
        {
            var list = new List <(string replacedString, string replacingString)>();

            using (WordprocessingDocument document = WordprocessingDocument.Open(this.ResultWordFileFullName, true))
            {
                this.SimpleLabelReplacement(this.Result, document);

                this.SetStatistcisTable(this.Result, document);

                this.SetFinallyNotes(this.Result, document);
                document.Save();
            }
        }
Ejemplo n.º 29
0
        private void CleanAndSaveItem(ListViewItem lvi)
        {
            //listView1.EnsureVisible(lvi.Index);
            var file = lvi.Tag as FileInfo;

            if (lvi.ToolTipText == "Unsaved" && //prevent double saving
                IsValidTarget(file))
            {
                try
                {
                    using (WordprocessingDocument doc = WordprocessingDocument.Open(file.FullName, true))
                    {
                        SimplifyMarkupSettings settings = new SimplifyMarkupSettings
                        {
                            AcceptRevisions = true,
                            //setting this to false reduces translation quality, but if true some documents have XML format errors when opening
                            NormalizeXml                      = true, // Merges Run's in a paragraph with similar formatting
                            RemoveBookmarks                   = true,
                            RemoveComments                    = true,
                            RemoveContentControls             = true,
                            RemoveEndAndFootNotes             = true,
                            RemoveFieldCodes                  = false, //true,
                            RemoveGoBackBookmark              = true,
                            RemoveHyperlinks                  = false,
                            RemoveLastRenderedPageBreak       = true,
                            RemoveMarkupForDocumentComparison = true,
                            RemovePermissions                 = false,
                            RemoveProof           = true,
                            RemoveRsidInfo        = true,
                            RemoveSmartTags       = true,
                            RemoveSoftHyphens     = true,
                            RemoveWebHidden       = true,
                            ReplaceTabsWithSpaces = false
                        };
                        MarkupSimplifier.SimplifyMarkup(doc, settings);
                        // OpenXmlPowerTools.WmlComparer.Compare
                        doc.Save();
                        lvi.BackColor   = Color.Green;
                        lvi.ToolTipText = "Saved";
                    }
                }
                catch (Exception ex)
                {
                    lvi.BackColor   = Color.Red;
                    lvi.ToolTipText = ex.Message;
                    //Console.WriteLine("Error in File: " + file.FullName + ". " + ex.Message);
                }
            }
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Sets the extended document properties
 /// </summary>
 /// <param name="document">WordprocessingDocument reference</param>
 /// <param name="company">Company</param>
 /// <param name="application">Application</param>
 public static void SetExtendedProperties(this WordprocessingDocument document, Company company, Application application)
 {
     //Add extended Document properties
     if (document.ExtendedFilePropertiesPart == null)
     {
         document.AddExtendedFilePropertiesPart();
     }
     document.ExtendedFilePropertiesPart.Properties = new Properties
     {
         Company     = company ?? new Company(@"izrra.ch"),
         Application = application ?? new Application("Combine.Sdk.Word")
     };
     //Save all changes
     document.Save();
 }