Пример #1
0
        private static void ProcessWordDocument(
            string outputDocumentFullName,
            string sourceLanguage,
            string targetLanguage,
            bool ignoreHidden = false)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Open(outputDocumentFullName, true))
            {
                OpenXmlPowerTools.SimplifyMarkupSettings settings = new OpenXmlPowerTools.SimplifyMarkupSettings
                {
                    AcceptRevisions       = true,
                    NormalizeXml          = true, //setting this to false reduces translation quality, but if true some documents have XML format errors when opening
                    RemoveBookmarks       = true,
                    RemoveComments        = true,
                    RemoveContentControls = true,
                    RemoveEndAndFootNotes = true,
                    RemoveFieldCodes      = true,
                    RemoveGoBackBookmark  = true,
                    //RemoveHyperlinks = false,
                    RemoveLastRenderedPageBreak       = true,
                    RemoveMarkupForDocumentComparison = true,
                    RemovePermissions     = false,
                    RemoveProof           = true,
                    RemoveRsidInfo        = true,
                    RemoveSmartTags       = true,
                    RemoveSoftHyphens     = true,
                    RemoveWebHidden       = true,
                    ReplaceTabsWithSpaces = false
                };
                OpenXmlPowerTools.MarkupSimplifier.SimplifyMarkup(doc, settings);
            }

            List <DocumentFormat.OpenXml.Wordprocessing.Text> texts = new List <DocumentFormat.OpenXml.Wordprocessing.Text>();

            using (WordprocessingDocument doc = WordprocessingDocument.Open(outputDocumentFullName, true))
            {
                var body = doc.MainDocumentPart.Document.Body;
                texts.AddRange(body.Descendants <DocumentFormat.OpenXml.Wordprocessing.Text>()
                               .Where(text => !String.IsNullOrEmpty(text.Text) && text.Text.Length > 0));

                var headers = doc.MainDocumentPart.HeaderParts.Select(p => p.Header);
                foreach (var header in headers)
                {
                    texts.AddRange(header.Descendants <DocumentFormat.OpenXml.Wordprocessing.Text>().Where(text => !String.IsNullOrEmpty(text.Text) && text.Text.Length > 0));
                }

                var footers = doc.MainDocumentPart.FooterParts.Select(p => p.Footer);
                foreach (var footer in footers)
                {
                    texts.AddRange(footer.Descendants <DocumentFormat.OpenXml.Wordprocessing.Text>().Where(text => !String.IsNullOrEmpty(text.Text) && text.Text.Length > 0));
                }

                if (ignoreHidden)
                {
                    texts.RemoveAll(t => t.Parent.Descendants <Vanish>().Any());
                }

                var exceptions = new ConcurrentQueue <Exception>();

                // Extract Text for Translation
                var batch = texts.Select(text => text.Text);

                // Do Translation
                var batches = SplitList(batch, TranslationServiceFacade.maxelements, TranslationServiceFacade.maxrequestsize);
                Parallel.For(
                    0,
                    batches.Count(),
                    new ParallelOptions {
                    MaxDegreeOfParallelism = 1
                },
                    l =>
                {
                    try
                    {
                        var translationOutput = TranslationServiceFacade.TranslateArray(
                            batches[l].ToArray(),
                            sourceLanguage,
                            targetLanguage);
                        int batchStartIndexInDocument = 0;
                        for (int i = 0; i < l; i++)
                        {
                            batchStartIndexInDocument = batchStartIndexInDocument + batches[i].Count();
                        }

                        // Apply translated batch to document
                        for (int j = 0; j < translationOutput.Length; j++)
                        {
                            int indexInDocument = j + batchStartIndexInDocument + 1;
                            var newValue        = translationOutput[j];
                            texts.Take(indexInDocument).Last().Text = newValue;
                        }
                    }
                    catch (Exception ex)
                    {
                        exceptions.Enqueue(ex);
                    }
                });

                // Throw the exceptions here after the loop completes.
                if (exceptions.Count > 0)
                {
                    throw new AggregateException(exceptions);
                }

                //doc.MainDocumentPart.PutXDocument();
            }
        }
Пример #2
0
 public TemplateProcessor(string fileName)
     : this(WordprocessingDocument.Open(fileName, true))
 {
 }
        public void WC001_Consolidate(string originalName, string revisedDocumentsXml)
        {
            FileInfo originalDocx = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, originalName));

            var originalCopiedToDestDocx = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, originalDocx.Name));

            if (!originalCopiedToDestDocx.Exists)
            {
                File.Copy(originalDocx.FullName, originalCopiedToDestDocx.FullName);
            }

            var revisedDocumentsXElement = XElement.Parse(revisedDocumentsXml);
            var revisedDocumentsArray    = revisedDocumentsXElement
                                           .Elements()
                                           .Select(z =>
            {
                FileInfo revisedDocx        = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, z.Element("DocName").Value));
                var revisedCopiedToDestDocx = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, revisedDocx.Name));
                if (!revisedCopiedToDestDocx.Exists)
                {
                    File.Copy(revisedDocx.FullName, revisedCopiedToDestDocx.FullName);
                }
                return(new WmlRevisedDocumentInfo()
                {
                    RevisedDocument = new WmlDocument(revisedCopiedToDestDocx.FullName),
                    Color = Color.FromName(z.Element("Color").Value),
                    Revisor = z.Element("Revisor").Value,
                });
            })
                                           .ToList();

            var consolidatedDocxName   = originalCopiedToDestDocx.Name.Replace(".docx", "-Consolidated.docx");
            var consolidatedDocumentFi = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, consolidatedDocxName));

            WmlDocument         source1Wml      = new WmlDocument(originalCopiedToDestDocx.FullName);
            WmlComparerSettings settings        = new WmlComparerSettings();
            WmlDocument         consolidatedWml = WmlComparer.Consolidate(
                source1Wml,
                revisedDocumentsArray,
                settings);

            consolidatedWml.SaveAs(consolidatedDocumentFi.FullName);

            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(consolidatedWml.DocumentByteArray, 0, consolidatedWml.DocumentByteArray.Length);
                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true))
                {
                    OpenXmlValidator validator = new OpenXmlValidator();
                    var errors = validator.Validate(wDoc).Where(e => !ExpectedErrors.Contains(e.Description));
                    if (errors.Count() > 0)
                    {
                        var ind = "  ";
                        var sb  = new StringBuilder();
                        foreach (var err in errors)
                        {
#if true
                            sb.Append("Error" + Environment.NewLine);
                            sb.Append(ind + "ErrorType: " + err.ErrorType.ToString() + Environment.NewLine);
                            sb.Append(ind + "Description: " + err.Description + Environment.NewLine);
                            sb.Append(ind + "Part: " + err.Part.Uri.ToString() + Environment.NewLine);
                            sb.Append(ind + "XPath: " + err.Path.XPath + Environment.NewLine);
#else
                            sb.Append("            \"" + err.Description + "\"," + Environment.NewLine);
#endif
                        }
                        var sbs = sb.ToString();
                        Assert.Equal("", sbs);
                    }
                }
            }

            /************************************************************************************************************************/

            if (s_OpenWord)
            {
                FileInfo wordExe = new FileInfo(@"C:\Program Files (x86)\Microsoft Office\root\Office16\WINWORD.EXE");
                WordRunner.RunWord(wordExe, consolidatedDocumentFi);
            }

            /************************************************************************************************************************/
        }
Пример #4
0
        public DocxConversionData CreateCleanedCopy(string fullPath, bool ignoreHidden)
        {
            if (string.IsNullOrEmpty(fullPath))
            {
                throw new ArgumentNullException("path variable cannot be null or empty");
            }

            // ensure we have a valid path to a docx file
            if (!validator.IsValid(fullPath))
            {
                return(null);
            }

            var origFileData = new DocxConversionData(fullPath);

            var cleanedFileName = origFileData.FileName + "_cleaned" + origFileData.FileExtension;
            var cleanedFileData = new DocxConversionData(Path.Join(origFileData.FilePath, cleanedFileName));

            try
            {
                // ensure there is not an orphaned copy already on disk
                File.Delete(cleanedFileData.FullPath);

                // Make a copy of the original using the "cleaned" file name
                File.Copy(origFileData.FullPath, cleanedFileData.FullPath);

                //Clean Document of extra tags
                using (WordprocessingDocument doc = WordprocessingDocument.Open(cleanedFileData.FullPath, true))
                {
                    OpenXmlPowerTools.SimplifyMarkupSettings settings = new OpenXmlPowerTools.SimplifyMarkupSettings
                    {
                        AcceptRevisions       = true,
                        NormalizeXml          = false, //setting this to false reduces translation quality, but if true some documents have XML format errors when opening
                        RemoveBookmarks       = true,
                        RemoveComments        = true,
                        RemoveContentControls = true,
                        RemoveEndAndFootNotes = true,
                        RemoveFieldCodes      = false, //FieldCode remove pagination
                        RemoveGoBackBookmark  = true,
                        //RemoveHyperlinks = false,
                        RemoveLastRenderedPageBreak       = true,
                        RemoveMarkupForDocumentComparison = true,
                        RemovePermissions     = false,
                        RemoveProof           = true,
                        RemoveRsidInfo        = true,
                        RemoveSmartTags       = true,
                        RemoveSoftHyphens     = true,
                        RemoveWebHidden       = true,
                        ReplaceTabsWithSpaces = false
                    };

                    OpenXmlPowerTools.MarkupSimplifier.SimplifyMarkup(doc, settings);

                    //Extract Strings for translation
                    var textBlocks = textExtractor.ExtractText(doc, ignoreHidden);
                    //var textBlocks = textExtractor.ExtractParagraph(doc, ignoreHidden);
                    cleanedFileData.Strings2Translate = textBlocks.Select(para => para.InnerText);
                }

                //Total the number of strings for translation
                cleanedFileData.TotalStrings2Translate = cleanedFileData.Strings2Translate.Count();

                if (File.Exists(cleanedFileData.FullPath))
                {
                    cleanedFileData.Messages.Add("Success");
                }
                else
                {
                    cleanedFileData.Messages.Add("Docx data failed to build properly.");
                }
            }
            catch (Exception e)
            {
                cleanedFileData.Messages.Add(e.Message);
            }

            return(cleanedFileData);
        }
        public static FileInfo ConvertToHtml(string file, string outputDirectory)
        {
            var fi = new FileInfo(file);

            byte[]   byteArray = File.ReadAllBytes(fi.FullName);
            FileInfo destFileName;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                memoryStream.Write(byteArray, 0, byteArray.Length);
                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(memoryStream, true))
                {
                    destFileName = new FileInfo(fi.Name.Replace(".docx", ".html"));
                    if (outputDirectory != null && outputDirectory != string.Empty)
                    {
                        DirectoryInfo di = new DirectoryInfo(outputDirectory);
                        if (!di.Exists)
                        {
                            throw new OpenXmlPowerToolsException("Output directory does not exist");
                        }
                        destFileName = new FileInfo(Path.Combine(di.FullName, destFileName.Name));
                    }
                    var imageDirectoryName = destFileName.FullName.Substring(0, destFileName.FullName.Length - 5) + "_files";
                    int imageCounter       = 0;
                    var pageTitle          = (string)wDoc.CoreFilePropertiesPart.GetXDocument().Descendants(DC.title).FirstOrDefault();
                    if (pageTitle == null)
                    {
                        pageTitle = fi.FullName;
                    }

                    HtmlConverterSettings settings = new HtmlConverterSettings()
                    {
                        PageTitle                           = pageTitle,
                        FabricateCssClasses                 = true,
                        CssClassPrefix                      = "pt-",
                        RestrictToSupportedLanguages        = false,
                        RestrictToSupportedNumberingFormats = false,
                        ImageHandler                        = imageInfo =>
                        {
                            DirectoryInfo localDirInfo = new DirectoryInfo(imageDirectoryName);
                            if (!localDirInfo.Exists)
                            {
                                localDirInfo.Create();
                            }
                            ++imageCounter;
                            string      extension   = imageInfo.ContentType.Split('/')[1].ToLower();
                            ImageFormat imageFormat = null;
                            if (extension == "png")
                            {
                                // Convert png to jpeg.
                                extension   = "gif";
                                imageFormat = ImageFormat.Gif;
                            }
                            else if (extension == "gif")
                            {
                                imageFormat = ImageFormat.Gif;
                            }
                            else if (extension == "bmp")
                            {
                                imageFormat = ImageFormat.Bmp;
                            }
                            else if (extension == "jpeg")
                            {
                                imageFormat = ImageFormat.Jpeg;
                            }
                            else if (extension == "tiff")
                            {
                                // Convert tiff to gif.
                                extension   = "gif";
                                imageFormat = ImageFormat.Gif;
                            }
                            else if (extension == "x-wmf")
                            {
                                extension   = "wmf";
                                imageFormat = ImageFormat.Wmf;
                            }

                            // If the image format isn't one that we expect, ignore it,
                            // and don't return markup for the link.
                            if (imageFormat == null)
                            {
                                return(null);
                            }

                            string imageFileName = imageDirectoryName + "/image" +
                                                   imageCounter.ToString() + "." + extension;
                            try
                            {
                                imageInfo.Bitmap.Save(imageFileName, imageFormat);
                            }
                            catch (System.Runtime.InteropServices.ExternalException)
                            {
                                return(null);
                            }
                            XElement img = new XElement(Xhtml.img,
                                                        new XAttribute(NoNamespace.src, imageFileName),
                                                        imageInfo.ImgStyleAttribute,
                                                        imageInfo.AltText != null ?
                                                        new XAttribute(NoNamespace.alt, imageInfo.AltText) : null);
                            return(img);
                        }
                    };
                    XElement html = HtmlConverter.ConvertToHtml(wDoc, settings);

                    // Note: the xhtml returned by ConvertToHtmlTransform contains objects of type
                    // XEntity.  PtOpenXmlUtil.cs define the XEntity class.  See
                    // http://blogs.msdn.com/ericwhite/archive/2010/01/21/writing-entity-references-using-linq-to-xml.aspx
                    // for detailed explanation.
                    //
                    // If you further transform the XML tree returned by ConvertToHtmlTransform, you
                    // must do it correctly, or entities will not be serialized properly.

                    var htmlString = html.ToString(SaveOptions.DisableFormatting);
                    File.WriteAllText(destFileName.FullName, htmlString, Encoding.UTF8);
                }
            }
            return(destFileName);
        }
        /// <summary>
        /// Creates the document.
        /// </summary>
        /// <param name="mergeTemplate">The merge template.</param>
        /// <param name="mergeObjectList">The merge object list.</param>
        /// <param name="globalMergeFields">The global merge fields.</param>
        /// <returns></returns>
        public override BinaryFile CreateDocument(MergeTemplate mergeTemplate, List <object> mergeObjectList, Dictionary <string, object> globalMergeFields)
        {
            this.Exceptions = new List <Exception>();
            BinaryFile outputBinaryFile = null;

            var rockContext       = new RockContext();
            var binaryFileService = new BinaryFileService(rockContext);

            var templateBinaryFile = binaryFileService.Get(mergeTemplate.TemplateBinaryFileId);

            if (templateBinaryFile == null)
            {
                return(null);
            }

            // Start by creating a new document with the contents of the Template (so that Styles, etc get included)
            XDocument sourceTemplateDocX;

            // NOTE: On using multiple IDisposable, see https://stackoverflow.com/a/12603126/1755417 and https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement
            using (MemoryStream sourceTemplateStream = new MemoryStream(), outputDocStream = new MemoryStream())
            {
                templateBinaryFile.ContentStream.CopyTo(outputDocStream);
                outputDocStream.Seek(0, SeekOrigin.Begin);

                // now that we have the outputdoc started, simplify the sourceTemplate
                templateBinaryFile.ContentStream.CopyTo(sourceTemplateStream);
                sourceTemplateStream.Seek(0, SeekOrigin.Begin);
                var simplifiedDoc = WordprocessingDocument.Open(sourceTemplateStream, true);
                MarkupSimplifier.SimplifyMarkup(simplifiedDoc, this.simplifyMarkupSettingsAll);

                //// simplify any nodes that have Lava in it that might not have been caught by the MarkupSimplifier
                //// MarkupSimplifier only merges superfluous runs that are children of a paragraph
                sourceTemplateDocX = simplifiedDoc.MainDocumentPart.GetXDocument();
                OpenXmlRegex.Match(
                    sourceTemplateDocX.Elements(),
                    this.lavaRegEx,
                    (x, m) =>
                {
                    foreach (var nonParagraphRunsParent in x.DescendantNodes().OfType <XElement>().Where(a => a.Parent != null && a.Name != null)
                             .Where(a => (a.Name.LocalName == "r")).Select(a => a.Parent).Distinct().ToList())
                    {
                        if (lavaRegEx.IsMatch(nonParagraphRunsParent.Value))
                        {
                            var tempParent = XElement.Parse(new Paragraph().OuterXml);
                            tempParent.Add(nonParagraphRunsParent.Nodes());
                            tempParent = MarkupSimplifier.MergeAdjacentSuperfluousRuns(tempParent);
                            nonParagraphRunsParent.ReplaceNodes(tempParent.Nodes());
                        }
                    }
                });

                XElement lastLavaNode = sourceTemplateDocX.DescendantNodes().OfType <XElement>().LastOrDefault(a => lavaRegEx.IsMatch(a.Value));

                // ensure there is a { Next } indicator after the last lava node in the template
                if (lastLavaNode != null)
                {
                    var nextRecordMatch = nextRecordRegEx.Match(lastLavaNode.Value);
                    if (nextRecordMatch == null || !nextRecordMatch.Success)
                    {
                        // if the last lava node doesn't have a { next }, append to the end
                        lastLavaNode.Value += " {% next %} ";
                    }
                    else
                    {
                        if (!lastLavaNode.Value.EndsWith(nextRecordMatch.Value))
                        {
                            // if the last lava node does have a { next }, but there is stuff after it, add it (just in case)
                            lastLavaNode.Value += " {% next %} ";
                        }
                    }
                }

                bool?allSameParent = null;

                using (WordprocessingDocument outputDoc = WordprocessingDocument.Open(outputDocStream, true))
                {
                    var xdoc           = outputDoc.MainDocumentPart.GetXDocument();
                    var outputBodyNode = xdoc.DescendantNodes().OfType <XElement>().FirstOrDefault(a => a.Name.LocalName.Equals("body"));
                    outputBodyNode.RemoveNodes();

                    int recordIndex     = 0;
                    int?lastRecordIndex = null;
                    int recordCount     = mergeObjectList.Count();
                    while (recordIndex < recordCount)
                    {
                        if (lastRecordIndex.HasValue && lastRecordIndex == recordIndex)
                        {
                            // something went wrong, so throw to avoid spinning infinitely
                            throw new Exception("Unexpected unchanged recordIndex");
                        }

                        lastRecordIndex = recordIndex;
                        using (var tempMergeTemplateStream = new MemoryStream())
                        {
                            sourceTemplateStream.Position = 0;
                            sourceTemplateStream.CopyTo(tempMergeTemplateStream);
                            tempMergeTemplateStream.Position = 0;
                            var tempMergeTemplateX        = new XDocument(sourceTemplateDocX);
                            var tempMergeTemplateBodyNode = tempMergeTemplateX.DescendantNodes().OfType <XElement>().FirstOrDefault(a => a.Name.LocalName.Equals("body"));

                            // find all the Nodes that have a {% next %}.
                            List <XElement> nextIndicatorNodes = new List <XElement>();

                            OpenXmlRegex.Match(
                                tempMergeTemplateX.Elements(),
                                this.nextRecordRegEx,
                                (x, m) =>
                            {
                                nextIndicatorNodes.Add(x);
                            });

                            allSameParent = allSameParent ?? nextIndicatorNodes.Count > 1 && nextIndicatorNodes.Select(a => a.Parent).Distinct().Count() == 1;

                            List <XContainer> recordContainerNodes = new List <XContainer>();

                            foreach (var nextIndicatorNodeParent in nextIndicatorNodes.Select(a => a.Parent).Where(a => a != null))
                            {
                                XContainer recordContainerNode = nextIndicatorNodeParent;
                                if (!allSameParent.Value)
                                {
                                    // go up the parent nodes until we have more than one "Next" descendent so that we know what to consider our record container
                                    while (recordContainerNode.Parent != null)
                                    {
                                        if (this.nextRecordRegEx.Matches(recordContainerNode.Parent.Value).Count == 1)
                                        {
                                            // still just the one "next" indicator, so go out another parent
                                            recordContainerNode = recordContainerNode.Parent;
                                        }
                                        else
                                        {
                                            // we went too far up the parents and found multiple "next" children, so use this node as the recordContainerNode
                                            break;
                                        }
                                    }
                                }

                                if (!recordContainerNodes.Contains(recordContainerNode))
                                {
                                    recordContainerNodes.Add(recordContainerNode);
                                }
                            }

                            foreach (var recordContainerNode in recordContainerNodes)
                            {
                                //// loop thru each of the recordContainerNodes
                                //// If we have more records than nodes, we'll jump out to the outer "while" and append another template and keep going

                                XContainer mergedXRecord;

                                var recordContainerNodeXml = recordContainerNode.ToString(SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces).ReplaceWordChars();

                                if (recordIndex >= recordCount)
                                {
                                    // out of records, so clear out any remaining template nodes that haven't been merged
                                    string xml = recordContainerNodeXml;
                                    mergedXRecord = XElement.Parse(xml) as XContainer;
                                    OpenXmlRegex.Replace(mergedXRecord.Nodes().OfType <XElement>(), this.regExDot, string.Empty, (a, b) => { return(true); });

                                    recordIndex++;
                                }
                                else
                                {
                                    //// just in case they have shared parent node, or if there is trailing {{ next }} after the last lava
                                    //// on the page, split the XML for each record and reassemble it when done
                                    List <string> xmlChunks = this.nextRecordRegEx.Split(recordContainerNodeXml).ToList();

                                    string mergedXml = string.Empty;

                                    foreach (var xml in xmlChunks)
                                    {
                                        bool incRecordIndex = true;
                                        if (lavaRegEx.IsMatch(xml))
                                        {
                                            if (recordIndex < recordCount)
                                            {
                                                try
                                                {
                                                    DotLiquid.Hash wordMergeObjects = new DotLiquid.Hash();
                                                    wordMergeObjects.Add("Row", mergeObjectList[recordIndex]);

                                                    foreach (var field in globalMergeFields)
                                                    {
                                                        wordMergeObjects.Add(field.Key, field.Value);
                                                    }

                                                    var resolvedXml = xml.ResolveMergeFields(wordMergeObjects, true, true);
                                                    mergedXml += resolvedXml;
                                                    if (resolvedXml == xml)
                                                    {
                                                        // there weren't any MergeFields after all, so don't move to the next record
                                                        incRecordIndex = false;
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    // if ResolveMergeFields failed, log the exception, then just return the orig xml
                                                    this.Exceptions.Add(ex);
                                                    mergedXml += xml;
                                                }

                                                if (incRecordIndex)
                                                {
                                                    recordIndex++;
                                                }
                                            }
                                            else
                                            {
                                                // out of records, so put a special '{% next_empty %}' that we can use to clear up unmerged parts of the template
                                                mergedXml += " {% next_empty %} " + xml;
                                            }
                                        }
                                        else
                                        {
                                            mergedXml += xml;
                                        }
                                    }

                                    mergedXRecord = XElement.Parse(mergedXml) as XContainer;
                                }

                                // remove the orig nodes and replace with merged nodes
                                recordContainerNode.RemoveNodes();
                                recordContainerNode.Add(mergedXRecord.Nodes().OfType <XElement>());

                                var mergedRecordContainer = XElement.Parse(recordContainerNode.ToString(SaveOptions.DisableFormatting));
                                if (recordContainerNode.Parent != null)
                                {
                                    // the recordContainerNode is some child/descendent of <body>
                                    recordContainerNode.ReplaceWith(mergedRecordContainer);
                                }
                                else
                                {
                                    // the recordContainerNode is the <body>
                                    recordContainerNode.RemoveNodes();
                                    recordContainerNode.Add(mergedRecordContainer.Nodes());

                                    if (recordIndex < recordCount)
                                    {
                                        // add page break
                                        var pageBreakXml = new Paragraph(new Run(new Break()
                                        {
                                            Type = BreakValues.Page
                                        })).OuterXml;
                                        var pageBreak     = XElement.Parse(pageBreakXml, LoadOptions.None);
                                        var lastParagraph = recordContainerNode.Nodes().OfType <XElement>().Where(a => a.Name.LocalName == "p").LastOrDefault();
                                        if (lastParagraph != null)
                                        {
                                            lastParagraph.AddAfterSelf(pageBreak);

                                            // Add page formatting for the page before the page break.
                                            var lastSectPr = recordContainerNode.Nodes().OfType <XElement>().Where(a => a.Name.LocalName == "sectPr").LastOrDefault();
                                            if (lastSectPr != null)
                                            {
                                                var paragraphPropertiesXml = new Paragraph(new ParagraphProperties(new SectionProperties(lastSectPr.ToString()))).OuterXml;
                                                var paragraphProperties    = XElement.Parse(paragraphPropertiesXml, LoadOptions.None);
                                                pageBreak.AddAfterSelf(paragraphProperties);
                                            }
                                        }
                                    }
                                }
                            }

                            outputBodyNode.Add(tempMergeTemplateBodyNode.Nodes());
                        }
                    }

                    // remove all the 'next' delimiters
                    OpenXmlRegex.Replace(outputBodyNode.Nodes().OfType <XElement>(), this.nextRecordRegEx, string.Empty, (xx, mm) => { return(true); });

                    // find all the 'next_empty' delimiters that we might have added and clear out the content in the paragraph nodes that follow
                    OpenXmlRegex.Match(
                        outputBodyNode.Nodes().OfType <XElement>(),
                        this.nextEmptyRecordRegEx,
                        (xx, mm) =>
                    {
                        var afterSiblings = xx.ElementsAfterSelf().ToList();

                        // get all the paragraph elements after the 'next_empty' node and clear out the content
                        var nodesToClean = afterSiblings.Where(a => a.Name.LocalName == "p").ToList();

                        // if the next_empty node has lava, clean that up too
                        var xxContent = xx.ToString();
                        if (lavaRegEx.IsMatch(xxContent))
                        {
                            nodesToClean.Add(xx);
                        }

                        foreach (var node in nodesToClean)
                        {
                            // remove all child nodes from each paragraph node
                            if (node.HasElements)
                            {
                                node.RemoveNodes();
                            }
                        }
                    });

                    // remove all the 'next_empty' delimiters
                    OpenXmlRegex.Replace(outputBodyNode.Nodes().OfType <XElement>(), this.nextEmptyRecordRegEx, string.Empty, (xx, mm) => { return(true); });

                    // remove all but the last SectionProperties element (there should only be one per section (body))
                    var sectPrItems = outputBodyNode.Nodes().OfType <XElement>().Where(a => a.Name.LocalName == "sectPr");
                    foreach (var extra in sectPrItems.Where(a => a != sectPrItems.Last()).ToList())
                    {
                        extra.Remove();
                    }

                    // renumber all the ids to make sure they are unique
                    var idAttrs = xdoc.DescendantNodes().OfType <XElement>().Where(a => a.HasAttributes).Select(a => a.Attribute("id")).Where(s => s != null);
                    int lastId  = 1;
                    foreach (var attr in idAttrs)
                    {
                        attr.Value = lastId.ToString();
                        lastId++;
                    }

                    DotLiquid.Hash globalMergeHash = new DotLiquid.Hash();
                    foreach (var field in globalMergeFields)
                    {
                        globalMergeHash.Add(field.Key, field.Value);
                    }

                    HeaderFooterGlobalMerge(outputDoc, globalMergeHash);

                    // sweep thru any remaining un-merged body parts for any Lava having to do with Global merge fields
                    foreach (var bodyTextPart in outputDoc.MainDocumentPart.Document.Body.Descendants <Text>())
                    {
                        string nodeText = bodyTextPart.Text.ReplaceWordChars();
                        if (lavaRegEx.IsMatch(nodeText))
                        {
                            bodyTextPart.Text = nodeText.ResolveMergeFields(globalMergeHash, true, true);
                        }
                    }

                    // remove the last pagebreak
                    MarkupSimplifier.SimplifyMarkup(outputDoc, new SimplifyMarkupSettings {
                        RemoveLastRenderedPageBreak = true
                    });

                    // If you want to see validation errors

                    /*
                     * var validator = new OpenXmlValidator();
                     * var errors = validator.Validate( outputDoc ).ToList();
                     */
                }

                outputBinaryFile                  = new BinaryFile();
                outputBinaryFile.IsTemporary      = true;
                outputBinaryFile.ContentStream    = outputDocStream;
                outputBinaryFile.FileName         = "MergeTemplateOutput" + Path.GetExtension(templateBinaryFile.FileName);
                outputBinaryFile.MimeType         = templateBinaryFile.MimeType;
                outputBinaryFile.BinaryFileTypeId = new BinaryFileTypeService(rockContext).Get(Rock.SystemGuid.BinaryFiletype.DEFAULT.AsGuid()).Id;

                binaryFileService.Add(outputBinaryFile);
                rockContext.SaveChanges();
            }

            return(outputBinaryFile);
        }
Пример #7
0
        /// <summary>
        /// RetrieveTOC
        /// </summary>
        /// <param name="fileStream">stream containing the docx file contents</param>
        /// <returns>List of DocumentSection objects</returns>
        public Task <IList <DocumentSection> > RetrieveTOCAsync(Stream fileStream, string requestId = "")
        {
            _logger.LogInformation($"RequestId: {requestId} - RetrieveTOC called.");

            try
            {
                List <DocumentSection> documentSections = new List <DocumentSection>();

                XElement TOC = null;

                using (var document = WordprocessingDocument.Open(fileStream, false))
                {
                    string currentSection1Id = String.Empty;
                    string currentSection2Id = String.Empty;
                    string currentSection3Id = String.Empty;

                    var docPart = document.MainDocumentPart;
                    var doc     = docPart.Document;

                    OpenXmlElement block = doc.Descendants <DocPartGallery>().
                                           Where(b => b.Val.HasValue &&
                                                 (b.Val.Value == "Table of Contents")).FirstOrDefault();


                    if (block != null)
                    {
                        // Back up to the enclosing SdtBlock and return that XML.
                        while ((block != null) && (!(block is SdtBlock)))
                        {
                            block = block.Parent;
                        }
                        TOC = new XElement("TOC", block.OuterXml);
                    }


                    // Extract the Table of Contents section information and create the list
                    foreach (var tocPart in document.MainDocumentPart.Document.Body.Descendants <SdtContentBlock>().First())
                    {
                        // Locate each section and add them to the list
                        if (tocPart.InnerXml.Contains("TOC1"))
                        {
                            currentSection1Id = Guid.NewGuid().ToString();

                            // Create a new DocumentSection object and add it to the list
                            documentSections.Add(new DocumentSection
                            {
                                Id                   = currentSection1Id,
                                SubSectionId         = String.Empty, // TOC1 has no parent
                                DisplayName          = tocPart.Descendants <Text>().ToArray()[0].InnerText,
                                LastModifiedDateTime = DateTimeOffset.MinValue,
                                Owner                = new UserProfile
                                {
                                    Id          = String.Empty,
                                    DisplayName = String.Empty,
                                    Fields      = new UserProfileFields()
                                },
                                SectionStatus = ActionStatus.NotStarted
                            });
                        }
                        else if (tocPart.InnerXml.Contains("TOC2"))
                        {
                            currentSection2Id = Guid.NewGuid().ToString();

                            // Create a new DocumentSection object and add it to the list
                            documentSections.Add(new DocumentSection
                            {
                                Id                   = currentSection2Id,
                                SubSectionId         = currentSection1Id,
                                DisplayName          = tocPart.Descendants <Text>().ToArray()[0].InnerText,
                                LastModifiedDateTime = DateTimeOffset.MinValue,
                                Owner                = new UserProfile
                                {
                                    Id          = String.Empty,
                                    DisplayName = String.Empty,
                                    Fields      = new UserProfileFields()
                                },
                                SectionStatus = ActionStatus.NotStarted
                            });
                        }
                        else if (tocPart.InnerXml.Contains("TOC3"))
                        {
                            currentSection3Id = Guid.NewGuid().ToString();

                            // Create a new DocumentSection object and add it to the list
                            documentSections.Add(new DocumentSection
                            {
                                Id                   = currentSection3Id,
                                SubSectionId         = currentSection2Id,
                                DisplayName          = tocPart.Descendants <Text>().ToArray()[0].InnerText,
                                LastModifiedDateTime = DateTimeOffset.MinValue,
                                Owner                = new UserProfile
                                {
                                    Id          = String.Empty,
                                    DisplayName = String.Empty,
                                    Fields      = new UserProfileFields()
                                },
                                SectionStatus = ActionStatus.NotStarted
                            });
                        }
                    }
                }

                // Return the list of DocumentSections
                return(Task.FromResult <IList <DocumentSection> >(documentSections));
            }
            catch (Exception ex)
            {
                _logger.LogError($"RequestId: {requestId} - RetrieveTOC Service Exception: {ex}");
                throw new ResponseException($"RequestId: {requestId} - RetrieveTOC Service Exception: {ex}");
            }
        }
 public WordProcessor(string filepath)
 {
     _wordProcessingDocument = WordprocessingDocument.Open(filepath, true);
 }
 public WordProcessor(Stream stream)
 {
     _wordProcessingDocument = WordprocessingDocument.Open(stream, true);
 }
        protected List <ValidationResult> ValidatePrintWeekTemplate(PrintWeekTemplateModelBase model)
        {
            List <ValidationResult> errors = new List <ValidationResult>();

            if (model.DaysPerPage < MIN_DAYS || model.DaysPerPage > MAX_DAYS)
            {
                errors.Add(new ValidationResult($"Количество дней должно быть определено в интервале {MIN_DAYS}..{MAX_DAYS}", new List <string>()
                {
                    "DaysPerPage"
                }));
            }

            if (model.File != null)
            {
                //расширение
                var extension = Path.GetExtension(model.File.FileName);

                if (!EXTENSIONS.Contains(extension.ToLower()))
                {
                    errors.Add(new ValidationResult($"Разрешение файла {extension} недопустимо", new List <string>()
                    {
                        "File"
                    }));
                }

                //размер
                if (model.File.Length > MAX_FILE_SIZE)
                {
                    errors.Add(new ValidationResult($"Максимально допустимый размер файла составляет { MAX_FILE_SIZE} байтов.", new List <string>()
                    {
                        "File"
                    }));
                }

                //проверка полей для заполнения

                // создаем word документ
                try
                {
                    using (WordprocessingDocument weekDoc = WordprocessingDocument.Open(model.File.OpenReadStream(), false))
                    {
                        //[таблица]
                        var daysPlacements = weekDoc.MainDocumentPart.Document.Body
                                             .FindElementsByText(OutputTemplateConstants.DaysPlacement);

                        if (daysPlacements.Count() == 0)
                        {
                            errors.Add(new ValidationResult($"Поле {OutputTemplateConstants.DaysPlacement} отсутствует в определении шаблона", new List <string>()
                            {
                                "File"
                            }));
                        }
                        else if (daysPlacements.Count() > 1)
                        {
                            errors.Add(new ValidationResult($"Поле {OutputTemplateConstants.DaysPlacement} должно быть определено единожды в шаблоне", new List <string>()
                            {
                                "File"
                            }));
                        }
                    }
                }
                catch (Exception ex)
                    when(ex is IOException ||
                         ex is ArgumentNullException ||
                         ex is OpenXmlPackageException)
                    {
                        errors.Add(new ValidationResult($"Неверный формат файла. Произошла ошибка при чтении", new List <string>()
                        {
                            "File"
                        }));
                    }
            }

            return(errors);
        }
Пример #11
0
        public static (string title, string imageUrl, string body) ConvertToHtml(string docxFilePath, ConverterSettings settings)
        {
            var    title    = string.Empty;
            var    imageUrl = string.Empty;
            string content;
            var    fi = new FileInfo(docxFilePath);

            var byteArray = File.ReadAllBytes(fi.FullName);

            using (var memoryStream = new MemoryStream())
            {
                memoryStream.Write(byteArray, 0, byteArray.Length);
                using (var wDoc = WordprocessingDocument.Open(memoryStream, true))
                {
                    var part = wDoc.CoreFilePropertiesPart;
                    if (part != null)
                    {
                        title = (string)part.GetXDocument().Descendants(DC.title).FirstOrDefault();
                    }

                    var htmlSettings = new HtmlConverterSettings
                    {
                        // AdditionalCss = "body { margin: 1cm auto; max-width: 20cm; padding: 0; }",
                        PageTitle                           = title,
                        FabricateCssClasses                 = true,
                        CssClassPrefix                      = "pt-",
                        RestrictToSupportedLanguages        = false,
                        RestrictToSupportedNumberingFormats = false,
                        ImageHandler                        = imageInfo =>
                        {
                            if (settings.IsClearImages || string.IsNullOrEmpty(settings.ImageDirectoryPath))
                            {
                                return(null);
                            }
                            DirectoryUtils.CreateDirectoryIfNotExists(settings.ImageDirectoryPath);

                            var         extension   = StringUtils.ToLower(imageInfo.ContentType.Split('/')[1]);
                            ImageFormat imageFormat = null;
                            if (extension == "png")
                            {
                                imageFormat = ImageFormat.Png;
                            }
                            else if (extension == "gif")
                            {
                                imageFormat = ImageFormat.Gif;
                            }
                            else if (extension == "bmp")
                            {
                                imageFormat = ImageFormat.Bmp;
                            }
                            else if (extension == "jpeg")
                            {
                                imageFormat = ImageFormat.Jpeg;
                            }
                            else if (extension == "tiff")
                            {
                                // Convert tiff to gif.
                                extension   = "gif";
                                imageFormat = ImageFormat.Gif;
                            }
                            else if (extension == "x-wmf")
                            {
                                extension   = "wmf";
                                imageFormat = ImageFormat.Wmf;
                            }

                            // If the image format isn't one that we expect, ignore it,
                            // and don't return markup for the link.
                            if (imageFormat == null)
                            {
                                return(null);
                            }

                            var imageFileName = StringUtils.GetShortGuid(false) + "." + extension;

                            var imageFilePath = PathUtils.Combine(settings.ImageDirectoryPath, imageFileName);
                            try
                            {
                                imageInfo.Bitmap.Save(imageFilePath, imageFormat);
                            }
                            catch (System.Runtime.InteropServices.ExternalException)
                            {
                                return(null);
                            }
                            var imageSource = PageUtils.Combine(settings.ImageDirectoryUrl, imageFileName);
                            if (string.IsNullOrEmpty(imageUrl))
                            {
                                imageUrl = imageSource;
                            }

                            var img = new XElement(Xhtml.img,
                                                   new XAttribute(NoNamespace.src, imageSource),
                                                   imageInfo.ImgStyleAttribute,
                                                   imageInfo.AltText != null ?
                                                   new XAttribute(NoNamespace.alt, imageInfo.AltText) : null);
                            return(img);
                        }
                    };
                    var htmlElement = HtmlConverter.ConvertToHtml(wDoc, htmlSettings);

                    // Produce HTML document with <!DOCTYPE html > declaration to tell the browser
                    // we are using HTML5.
                    var html = new XDocument(
                        new XDocumentType("html", null, null, null),
                        htmlElement);

                    // Note: the xhtml returned by ConvertToHtmlTransform contains objects of type
                    // XEntity.  PtOpenXmlUtil.cs define the XEntity class.  See
                    // http://blogs.msdn.com/ericwhite/archive/2010/01/21/writing-entity-references-using-linq-to-xml.aspx
                    // for detailed explanation.
                    //
                    // If you further transform the XML tree returned by ConvertToHtmlTransform, you
                    // must do it correctly, or entities will not be serialized properly.

                    var htmlString = html.ToString(SaveOptions.DisableFormatting);
                    var htmlDoc    = new HtmlDocument();
                    htmlDoc.LoadHtml(htmlString);
                    var style = htmlDoc.DocumentNode.SelectSingleNode("//style").OuterHtml;
                    var body  = htmlDoc.DocumentNode.SelectSingleNode("//body").InnerHtml;

                    content = $"{style}{Environment.NewLine}{body}";

                    if (settings.IsSaveHtml && !string.IsNullOrEmpty(settings.HtmlDirectoryPath) && DirectoryUtils.IsDirectoryExists(settings.HtmlDirectoryPath))
                    {
                        var htmlFilePath = PathUtils.Combine(settings.HtmlDirectoryPath, PathUtils.GetFileNameWithoutExtension(docxFilePath) + ".html");
                        File.WriteAllText(htmlFilePath, htmlString, Encoding.UTF8);
                    }
                }
            }

            if (settings.IsFirstLineTitle)
            {
                var contentTitle = RegexUtils.GetInnerContent("p", content);
                contentTitle = StringUtils.StripTags(contentTitle);
                if (!string.IsNullOrEmpty(contentTitle))
                {
                    contentTitle = contentTitle.Trim();
                    contentTitle = contentTitle.Trim(' ', ' ');
                    contentTitle = StringUtils.StripEntities(contentTitle);
                }

                if (!string.IsNullOrEmpty(contentTitle))
                {
                    title = contentTitle;
                }
            }

            if (settings.IsClearFormat)
            {
                content = HtmlUtils.ClearFormat(content);
            }

            if (settings.IsFirstLineIndent)
            {
                content = HtmlUtils.FirstLineIndent(content);
            }

            if (settings.IsClearFontSize)
            {
                content = HtmlUtils.ClearFontSize(content);
            }

            if (settings.IsClearFontFamily)
            {
                content = HtmlUtils.ClearFontFamily(content);
            }

            return(title, imageUrl, content);
        }
Пример #12
0
        public static byte[] GetOwnerVerification(OwnerVerificationReportModel reportModel, string name)
        {
            try
            {
                // ******************************************************
                // get document template
                // ******************************************************
                Assembly assembly   = Assembly.GetExecutingAssembly();
                byte[]   byteArray  = new byte[] { };
                int      ownerCount = 0;

                using (Stream templateStream = assembly.GetManifestResourceStream(ResourceName))
                {
                    if (templateStream != null)
                    {
                        byteArray = new byte[templateStream.Length];
                        templateStream.Read(byteArray, 0, byteArray.Length);
                        templateStream.Close();
                    }
                }

                using (MemoryStream documentStream = new MemoryStream())
                {
                    WordprocessingDocument wordDocument = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document, true);

                    // add a main document part
                    wordDocument.AddMainDocumentPart();

                    using (MemoryStream templateStream = new MemoryStream())
                    {
                        templateStream.Write(byteArray, 0, byteArray.Length);
                        WordprocessingDocument wordTemplate = WordprocessingDocument.Open(templateStream, true);

                        if (wordTemplate == null)
                        {
                            throw new Exception("Owner Verification template not found");
                        }

                        // ******************************************************
                        // merge document content
                        // ******************************************************
                        foreach (HetOwner owner in reportModel.Owners)
                        {
                            ownerCount++;

                            using (MemoryStream ownerStream = new MemoryStream())
                            {
                                WordprocessingDocument ownerDocument = (WordprocessingDocument)wordTemplate.Clone(ownerStream);
                                ownerDocument.Save();

                                // update address and contact information
                                string[] addressLabels = GetAddressLabels(owner.OrganizationName, owner.DoingBusinessAs, owner.Address1, owner.Address2);
                                string[] addressInfo   = GetAddressDetail(owner.OrganizationName, owner.DoingBusinessAs, owner.Address1, owner.Address2);

                                string[] contactLabels = GetContactLabels(owner.PrimaryContact.WorkPhoneNumber, owner.PrimaryContact.MobilePhoneNumber, owner.PrimaryContact.FaxPhoneNumber);
                                string[] contactInfo   = GetContactDetail(owner.PrimaryContact.WorkPhoneNumber, owner.PrimaryContact.MobilePhoneNumber, owner.PrimaryContact.FaxPhoneNumber);

                                Dictionary <string, string> values = new Dictionary <string, string>
                                {
                                    { "classification", owner.Classification },
                                    { "districtAddress", reportModel.DistrictAddress },
                                    { "districtContact", reportModel.DistrictContact },
                                    { "addressLabels0", addressLabels[0] },
                                    { "addressLabels1", addressLabels[1] },
                                    { "addressLabels2", addressLabels[2] },
                                    { "addressLabels3", addressLabels[3] },
                                    { "addressInfo0", addressInfo[0] },
                                    { "addressInfo1", addressInfo[1] },
                                    { "addressInfo2", addressInfo[2] },
                                    { "addressInfo3", addressInfo[3] },
                                    { "reportDate", reportModel.ReportDate },
                                    { "ownerCode", owner.OwnerCode },
                                    { "sharedKeyHeader", owner.SharedKeyHeader },
                                    { "sharedKey", owner.SharedKey },
                                    { "contactLabels0", contactLabels[0] },
                                    { "contactLabels1", contactLabels[1] },
                                    { "contactLabels2", contactLabels[2] },
                                    { "contactInfo0", contactInfo[0] },
                                    { "contactInfo1", contactInfo[1] },
                                    { "contactInfo2", contactInfo[2] }
                                };

                                // update classification number first [ClassificationNumber]
                                owner.Classification = owner.Classification.Replace("&", "&amp;");
                                bool found = false;

                                foreach (OpenXmlElement paragraphs in ownerDocument.MainDocumentPart.Document.Body.Elements())
                                {
                                    foreach (OpenXmlElement paragraphRun in paragraphs.Elements())
                                    {
                                        foreach (OpenXmlElement text in paragraphRun.Elements())
                                        {
                                            if (text.InnerText.Contains("ClassificationNumber"))
                                            {
                                                // replace text
                                                text.InnerXml = text.InnerXml.Replace("<w:t>ClassificationNumber</w:t>",
                                                                                      $"<w:t xml:space='preserve'>ORCS: {owner.Classification}</w:t>");

                                                found = true;
                                                break;
                                            }
                                        }

                                        if (found)
                                        {
                                            break;
                                        }
                                    }

                                    if (found)
                                    {
                                        break;
                                    }
                                }

                                ownerDocument.MainDocumentPart.Document.Save();
                                ownerDocument.Save();

                                // update merge fields
                                MergeHelper.ConvertFieldCodes(ownerDocument.MainDocumentPart.Document);
                                MergeHelper.MergeFieldsInElement(values, ownerDocument.MainDocumentPart.Document);
                                ownerDocument.MainDocumentPart.Document.Save();

                                // setup table for equipment data
                                Table     equipmentTable = GenerateEquipmentTable(owner.HetEquipment);
                                Paragraph tableParagraph = null;
                                found = false;

                                foreach (OpenXmlElement paragraphs in ownerDocument.MainDocumentPart.Document.Body.Elements())
                                {
                                    foreach (OpenXmlElement paragraphRun in paragraphs.Elements())
                                    {
                                        foreach (OpenXmlElement text in paragraphRun.Elements())
                                        {
                                            if (text.InnerText.Contains("Owner Equipment Table"))
                                            {
                                                // insert table here...
                                                text.RemoveAllChildren();
                                                tableParagraph = (Paragraph)paragraphRun.Parent;
                                                found          = true;
                                                break;
                                            }
                                        }

                                        if (found)
                                        {
                                            break;
                                        }
                                    }

                                    if (found)
                                    {
                                        break;
                                    }
                                }

                                // append table to document
                                if (tableParagraph != null)
                                {
                                    Run run = tableParagraph.AppendChild(new Run());
                                    run.AppendChild(equipmentTable);
                                }

                                ownerDocument.MainDocumentPart.Document.Save();
                                ownerDocument.Save();

                                // merge owner into the master document
                                if (ownerCount == 1)
                                {
                                    // update document header
                                    foreach (HeaderPart headerPart in ownerDocument.MainDocumentPart.HeaderParts)
                                    {
                                        MergeHelper.ConvertFieldCodes(headerPart.Header);
                                        MergeHelper.MergeFieldsInElement(values, headerPart.Header);
                                        headerPart.Header.Save();
                                    }

                                    wordDocument = (WordprocessingDocument)ownerDocument.Clone(documentStream);

                                    ownerDocument.Close();
                                    ownerDocument.Dispose();
                                }
                                else
                                {
                                    // DELETE document header from owner document
                                    ownerDocument.MainDocumentPart.DeleteParts(ownerDocument.MainDocumentPart.HeaderParts);

                                    List <HeaderReference> headers = ownerDocument.MainDocumentPart.Document.Descendants <HeaderReference>().ToList();

                                    foreach (HeaderReference header in headers)
                                    {
                                        header.Remove();
                                    }

                                    // DELETE document footers from owner document
                                    ownerDocument.MainDocumentPart.DeleteParts(ownerDocument.MainDocumentPart.FooterParts);

                                    List <FooterReference> footers = ownerDocument.MainDocumentPart.Document.Descendants <FooterReference>().ToList();

                                    foreach (FooterReference footer in footers)
                                    {
                                        footer.Remove();
                                    }

                                    // DELETE section properties from owner document
                                    List <SectionProperties> properties = ownerDocument.MainDocumentPart.Document.Descendants <SectionProperties>().ToList();

                                    foreach (SectionProperties property in properties)
                                    {
                                        property.Remove();
                                    }

                                    ownerDocument.Save();

                                    // insert section break in master
                                    MainDocumentPart mainPart = wordDocument.MainDocumentPart;

                                    Paragraph         para      = new Paragraph();
                                    SectionProperties sectProp  = new SectionProperties();
                                    SectionType       secSbType = new SectionType()
                                    {
                                        Val = SectionMarkValues.OddPage
                                    };
                                    PageSize pageSize = new PageSize()
                                    {
                                        Width = 11900U, Height = 16840U, Orient = PageOrientationValues.Portrait
                                    };
                                    PageMargin pageMargin = new PageMargin()
                                    {
                                        Top = 2642, Right = 23U, Bottom = 278, Left = 23U, Header = 714, Footer = 0, Gutter = 0
                                    };

                                    // page numbering throws out the "odd page" section breaks
                                    //PageNumberType pageNum = new PageNumberType() {Start = 1};

                                    sectProp.AppendChild(secSbType);
                                    sectProp.AppendChild(pageSize);
                                    sectProp.AppendChild(pageMargin);
                                    //sectProp.AppendChild(pageNum);

                                    ParagraphProperties paragraphProperties = new ParagraphProperties(sectProp);
                                    para.AppendChild(paragraphProperties);

                                    mainPart.Document.Body.InsertAfter(para, mainPart.Document.Body.LastChild);
                                    mainPart.Document.Save();

                                    // append document body
                                    string altChunkId = $"AltChunkId{ownerCount}";

                                    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);

                                    ownerDocument.Close();
                                    ownerDocument.Dispose();

                                    ownerStream.Seek(0, SeekOrigin.Begin);
                                    chunk.FeedData(ownerStream);

                                    AltChunk altChunk = new AltChunk {
                                        Id = altChunkId
                                    };

                                    Paragraph para3 = new Paragraph();
                                    Run       run3  = para3.InsertAfter(new Run(), para3.LastChild);
                                    run3.AppendChild(altChunk);

                                    mainPart.Document.Body.InsertAfter(para3, mainPart.Document.Body.LastChild);
                                    mainPart.Document.Save();
                                }
                            }
                        }

                        wordTemplate.Close();
                        wordTemplate.Dispose();
                        templateStream.Close();
                    }

                    // ******************************************************
                    // secure & return completed document
                    // ******************************************************
                    wordDocument.CompressionOption = CompressionOption.Maximum;
                    SecurityHelper.PasswordProtect(wordDocument);

                    wordDocument.Close();
                    wordDocument.Dispose();

                    documentStream.Seek(0, SeekOrigin.Begin);
                    byteArray = documentStream.ToArray();
                }

                return(byteArray);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Пример #13
0
        public string SetLock(string szFilePath, DocumentProtectionValues objLockType, string strPwd = "")
        {
            string strResult = string.Empty;

            try
            {
                using (WordprocessingDocument _objDoc = WordprocessingDocument.Open(szFilePath, true))
                {
                    DocumentProtection documentProtection = new DocumentProtection();

                    documentProtection.Edit = objLockType;

                    // Generate the Salt
                    byte[] arrSalt             = new byte[16];
                    RandomNumberGenerator rand = new RNGCryptoServiceProvider();
                    rand.GetNonZeroBytes(arrSalt);

                    //Array to hold Key Values
                    byte[] generatedKey = new byte[4];

                    //Maximum length of the password is 15 chars.
                    int intMaxPasswordLength = 15;

                    if (!string.IsNullOrEmpty(strPwd))
                    {
                        // Truncate the password to 15 characters
                        strPwd = strPwd.Substring(0, Math.Min(strPwd.Length, intMaxPasswordLength));

                        // Construct a new NULL-terminated string consisting of single-byte characters:
                        //  -- > Get the single-byte values by iterating through the Unicode characters of the truncated Password.
                        //   --> For each character, if the low byte is not equal to 0, take it. Otherwise, take the high byte.

                        byte[] arrByteChars = new byte[strPwd.Length];

                        for (int intLoop = 0; intLoop < strPwd.Length; intLoop++)
                        {
                            int intTemp = Convert.ToInt32(strPwd[intLoop]);
                            arrByteChars[intLoop] = Convert.ToByte(intTemp & 0x00FF);
                            if (arrByteChars[intLoop] == 0)
                            {
                                arrByteChars[intLoop] = Convert.ToByte((intTemp & 0xFF00) >> 8);
                            }
                        }

                        // Compute the high-order word of the new key:

                        // --> Initialize from the initial code array (see below), depending on the strPassword’s length.
                        int intHighOrderWord = InitialCodeArray[arrByteChars.Length - 1];

                        // --> For each character in the strPassword:
                        //      --> For every bit in the character, starting with the least significant and progressing to (but excluding)
                        //          the most significant, if the bit is set, XOR the key’s high-order word with the corresponding word from
                        //          the Encryption Matrix

                        for (int intLoop = 0; intLoop < arrByteChars.Length; intLoop++)
                        {
                            int tmp = intMaxPasswordLength - arrByteChars.Length + intLoop;
                            for (int intBit = 0; intBit < 7; intBit++)
                            {
                                if ((arrByteChars[intLoop] & (0x0001 << intBit)) != 0)
                                {
                                    intHighOrderWord ^= EncryptionMatrix[tmp, intBit];
                                }
                            }
                        }

                        // Compute the low-order word of the new key:

                        // Initialize with 0
                        int intLowOrderWord = 0;

                        // For each character in the strPassword, going backwards
                        for (int intLoopChar = arrByteChars.Length - 1; intLoopChar >= 0; intLoopChar--)
                        {
                            // low-order word = (((low-order word SHR 14) AND 0x0001) OR (low-order word SHL 1) AND 0x7FFF)) XOR character
                            intLowOrderWord = (((intLowOrderWord >> 14) & 0x0001) | ((intLowOrderWord << 1) & 0x7FFF)) ^ arrByteChars[intLoopChar];
                        }

                        // Lastly,low-order word = (((low-order word SHR 14) AND 0x0001) OR (low-order word SHL 1) AND 0x7FFF)) XOR strPassword length XOR 0xCE4B.
                        intLowOrderWord = (((intLowOrderWord >> 14) & 0x0001) | ((intLowOrderWord << 1) & 0x7FFF)) ^ arrByteChars.Length ^ 0xCE4B;

                        // Combine the Low and High Order Word
                        int intCombinedkey = (intHighOrderWord << 16) + intLowOrderWord;

                        // The byte order of the result shall be reversed [Example: 0x64CEED7E becomes 7EEDCE64. end example],
                        // and that value shall be hashed as defined by the attribute values.

                        for (int intTemp = 0; intTemp < 4; intTemp++)
                        {
                            generatedKey[intTemp] = Convert.ToByte(((uint)(intCombinedkey & (0x000000FF << (intTemp * 8)))) >> (intTemp * 8));
                        }
                    }

                    // Implementation Notes List:
                    // --> In this third stage, the reversed byte order legacy hash from the second stage shall be converted to Unicode hex
                    // --> string representation
                    StringBuilder sb = new StringBuilder();
                    for (int intTemp = 0; intTemp < 4; intTemp++)
                    {
                        sb.Append(Convert.ToString(generatedKey[intTemp], 16));
                    }
                    generatedKey = Encoding.Unicode.GetBytes(sb.ToString().ToUpper());

                    // Implementation Notes List:
                    //Word appends the binary form of the salt attribute and not the base64 string representation when hashing
                    // Before calculating the initial hash, you are supposed to prepend (not append) the salt to the key
                    byte[] tmpArray1 = generatedKey;
                    byte[] tmpArray2 = arrSalt;
                    byte[] tempKey   = new byte[tmpArray1.Length + tmpArray2.Length];
                    Buffer.BlockCopy(tmpArray2, 0, tempKey, 0, tmpArray2.Length);
                    Buffer.BlockCopy(tmpArray1, 0, tempKey, tmpArray2.Length, tmpArray1.Length);
                    generatedKey = tempKey;

                    // Iterations specifies the number of times the hashing function shall be iteratively run (using each
                    // iteration's result as the input for the next iteration).
                    int iterations = 50000;

                    // Implementation Notes List:
                    //Word requires that the initial hash of the password with the salt not be considered in the count.
                    //    The initial hash of salt + key is not included in the iteration count.
                    HashAlgorithm sha1 = new SHA1Managed();
                    generatedKey = sha1.ComputeHash(generatedKey);
                    byte[] iterator = new byte[4];
                    for (int intTmp = 0; intTmp < iterations; intTmp++)
                    {
                        //When iterating on the hash, you are supposed to append the current iteration number.
                        iterator[0] = Convert.ToByte((intTmp & 0x000000FF) >> 0);
                        iterator[1] = Convert.ToByte((intTmp & 0x0000FF00) >> 8);
                        iterator[2] = Convert.ToByte((intTmp & 0x00FF0000) >> 16);
                        iterator[3] = Convert.ToByte((intTmp & 0xFF000000) >> 24);

                        generatedKey = concatByteArrays(iterator, generatedKey);
                        generatedKey = sha1.ComputeHash(generatedKey);
                    }

                    DocumentFormat.OpenXml.OnOffValue docProtection = new DocumentFormat.OpenXml.OnOffValue(true);
                    documentProtection.Enforcement = docProtection;

                    documentProtection.CryptographicAlgorithmClass = CryptAlgorithmClassValues.Hash;
                    documentProtection.CryptographicProviderType   = CryptProviderValues.RsaFull;
                    documentProtection.CryptographicAlgorithmType  = CryptAlgorithmValues.TypeAny;
                    documentProtection.CryptographicAlgorithmSid   = 4; // SHA1
                    //    The iteration count is unsigned
                    UInt32 uintVal = new UInt32();
                    uintVal = (uint)iterations;
                    documentProtection.CryptographicSpinCount = uintVal;
                    documentProtection.Hash = Convert.ToBase64String(generatedKey);
                    documentProtection.Salt = Convert.ToBase64String(arrSalt);
                    _objDoc.MainDocumentPart.DocumentSettingsPart.Settings.AppendChild(documentProtection);
                    _objDoc.MainDocumentPart.DocumentSettingsPart.Settings.Save();
                    _objDoc.Close();
                }
            }
            catch (Exception ex)
            {
                strResult = ex.Message;
            }

            return(strResult);
        }
Пример #14
0
        private void ConvertToTransitional(string fileName, byte[] tempByteArray)
        {
            Type type;

            try
            {
                type = GetDocumentType(tempByteArray);
            }
            catch (FileFormatException)
            {
                throw new PowerToolsDocumentException("Not an Open XML document.");
            }

            using var ms = new MemoryStream();
            ms.Write(tempByteArray, 0, tempByteArray.Length);
            if (type == typeof(WordprocessingDocument))
            {
                using var sDoc = WordprocessingDocument.Open(ms, true);
                // following code forces the SDK to serialize
                foreach (var part in sDoc.Parts)
                {
                    try
                    {
                        var z = part.OpenXmlPart.RootElement;
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }
            else if (type == typeof(SpreadsheetDocument))
            {
                using var sDoc = SpreadsheetDocument.Open(ms, true);
                // following code forces the SDK to serialize
                foreach (var part in sDoc.Parts)
                {
                    try
                    {
                        var z = part.OpenXmlPart.RootElement;
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }
            else if (type == typeof(PresentationDocument))
            {
                using var sDoc = PresentationDocument.Open(ms, true);
                // following code forces the SDK to serialize
                foreach (var part in sDoc.Parts)
                {
                    try
                    {
                        var z = part.OpenXmlPart.RootElement;
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }
            this.FileName     = fileName;
            DocumentByteArray = ms.ToArray();
        }
Пример #15
0
 public static WordprocessingDocument AsWordprocessingDocument(this Stream source, bool isEditable = false)
 {
     source.Position = 0;
     return(WordprocessingDocument.Open(source, isEditable));
 }
Пример #16
0
    public void WriteFile(string basedOn, string fn)
    {
        using (var templateDoc = WordprocessingDocument.Open(basedOn, false))
            using (var resultDoc = WordprocessingDocument.Create(fn, WordprocessingDocumentType.Document))
            {
                foreach (var part in templateDoc.Parts)
                {
                    resultDoc.AddPart(part.OpenXmlPart, part.RelationshipId);
                }
                var body = resultDoc.MainDocumentPart.Document.Body;

                // We have to find the TOC, if one exists, and replace it...
                var tocFirst = -1;
                var tocLast  = -1;
                var tocInstr = "";
                var tocSec   = null as Paragraph;

                if (FindToc(body, out tocFirst, out tocLast, out tocInstr, out tocSec))
                {
                    var tocRunFirst = new Run(new FieldChar {
                        FieldCharType = FieldCharValues.Begin
                    },
                                              new FieldCode {
                        Text = tocInstr, Space = SpaceProcessingModeValues.Preserve
                    },
                                              new FieldChar {
                        FieldCharType = FieldCharValues.Separate
                    });
                    var tocRunLast = new Run(new FieldChar {
                        FieldCharType = FieldCharValues.End
                    });
                    //
                    for (int i = tocLast; i >= tocFirst; i--)
                    {
                        body.RemoveChild(body.ChildElements[i]);
                    }
                    var afterToc = body.ChildElements[tocFirst];
                    //
                    for (int i = 0; i < Sections.Count; i++)
                    {
                        var section = Sections[i];
                        if (section.Level > 3)
                        {
                            continue;
                        }
                        var p = new Paragraph();
                        if (i == 0)
                        {
                            p.AppendChild(tocRunFirst);
                        }
                        p.AppendChild(new Hyperlink(new Run(new Text(section.Number + " " + section.Title)))
                        {
                            Anchor = section.BookmarkName
                        });
                        if (i == Sections.Count - 1)
                        {
                            p.AppendChild(tocRunLast);
                        }
                        p.ParagraphProperties = new ParagraphProperties(new ParagraphStyleId {
                            Val = $"TOC{section.Level}"
                        });
                        body.InsertBefore(p, afterToc);
                    }
                    if (tocSec != null)
                    {
                        body.InsertBefore(tocSec, afterToc);
                    }
                }

                var sectionDictionary = Sections.ToDictionary(sr => sr.Url);
                var maxBookmarkId     = new StrongBox <int>(1 + body.Descendants <BookmarkStart>().Max(bookmark => int.Parse(bookmark.Id)));
                foreach (var src in Sources())
                {
                    var converter = new MarkdownConverter
                    {
                        mddoc         = Markdown.Parse(src.Item2),
                        filename      = Path.GetFileName(src.Item1),
                        wdoc          = resultDoc,
                        sections      = sectionDictionary,
                        maxBookmarkId = maxBookmarkId
                    };
                    foreach (var p in converter.Paragraphs())
                    {
                        body.AppendChild(p);
                    }
                }
            }
    }
Пример #17
0
        static void Main(string[] args)
        {
            string siteURL = args[0];
            string docLib  = args[1];

            using (SPSite spSite = new SPSite(siteURL))
            {
                SPDocumentLibrary library     = spSite.RootWeb.Lists[docLib] as SPDocumentLibrary;
                string            docPath     = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Automation.xml";
                SPFile            file        = spSite.RootWeb.GetFile(docPath);
                XDocument         automation  = XDocument.Load(new StreamReader(file.OpenBinaryStream()));
                XElement          autoElement = automation.Element("Automation");
                string            masterName  = autoElement.Attribute("Master").Value;
                string            printerName = autoElement.Attribute("Printer").Value;

                // Open the master document
                docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/" + masterName + ".docx";
                SPFile       masterFile      = spSite.RootWeb.GetFile(docPath);
                Stream       docStream       = new MemoryStream();
                Stream       docMasterStream = masterFile.OpenBinaryStream();
                BinaryReader docMasterReader = new BinaryReader(docMasterStream);
                BinaryWriter docWriter       = new BinaryWriter(docStream);
                docWriter.Write(docMasterReader.ReadBytes((int)docMasterStream.Length));
                docWriter.Flush();
                docMasterReader.Close();
                docMasterStream.Dispose();
                Package package = Package.Open(docStream, FileMode.Open, FileAccess.ReadWrite);
                WordprocessingDocument master = WordprocessingDocument.Open(package);
                string guid;
                Uri    XMLUri = CreateCustomXML(master, automation.Descendants("Record").First(), out guid);
                BindControls(master, guid);
                master.Close();
                docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Output 00001.docx";
                spSite.RootWeb.Files.Add(docPath, docStream, true);

                // Loop through all the records from the XML file
                int count = 1;
                foreach (XElement element in automation.Descendants("Record"))
                {
                    if (count != 1)
                    {
                        package = Package.Open(docStream, FileMode.Open, FileAccess.ReadWrite);
                        master  = WordprocessingDocument.Open(package);
                        foreach (CustomXmlPart part in master.MainDocumentPart.CustomXmlParts)
                        {
                            if (part.Uri == XMLUri)
                            {
                                Stream       stream = part.GetStream(FileMode.Create, FileAccess.ReadWrite);
                                StreamWriter sw     = new StreamWriter(stream);
                                sw.Write(element.ToString());
                                sw.Flush();
                                sw.Close();
                                break;
                            }
                        }
                        master.Close();
                        docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Output " + count.ToString("D5") + ".docx";
                        spSite.RootWeb.Files.Add(docPath, docStream, true);
                    }
                    count++;
                }

                // Use Word Automation Services to convert to XPS files
                ConversionJob job = new ConversionJob(WordAutomationServicesName);
                job.UserToken                   = spSite.UserToken;
                job.Settings.UpdateFields       = true;
                job.Settings.OutputFormat       = SaveFormat.XPS;
                job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
                SPList listToConvert = spSite.RootWeb.Lists[docLib];
                job.AddLibrary(listToConvert, listToConvert);
                job.Start();
                for (; ;)
                {
                    Thread.Sleep(5000);
                    ConversionJobStatus status = new ConversionJobStatus(WordAutomationServicesName, job.JobId, null);
                    if (status.Count == status.Succeeded + status.Failed)
                    {
                        break;
                    }
                }

                // Print output XPS files
                LocalPrintServer srv = new LocalPrintServer();
                PrintQueue       pq  = srv.GetPrintQueue(printerName);
                for (int num = 1; num < count; num++)
                {
                    XpsDocumentWriter xdw = PrintQueue.CreateXpsDocumentWriter(pq);
                    docPath = spSite.MakeFullUrl(library.RootFolder.ServerRelativeUrl) + "/Output " + num.ToString("D5") + ".xps";
                    SPFile docFile = spSite.RootWeb.GetFile(docPath);
                    package = Package.Open(docFile.OpenBinaryStream(), FileMode.Open, FileAccess.Read);
                    XpsDocument xdoc = new XpsDocument(package);
                    xdoc.Uri = new Uri(docPath);
                    xdw.Write(xdoc.GetFixedDocumentSequence());
                    xdoc.Close();
                }
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            string curDir = System.IO.Directory.GetCurrentDirectory();

            string шаблон = curDir + @"\проверка1дом.docx";

            if (!System.IO.File.Exists(шаблон.ToString()))
            {
                MessageBox.Show("Нет файла " + шаблон.ToString());
                Cursor = Cursors.Default;
                return;
            }

            var    template = new System.IO.FileInfo(шаблон);
            string tempFile = curDir + @"\temp\temp.docx";

            try
            {
                клTemp.закрытьWord();
            }
            catch
            {
                MessageBox.Show("Сохраните файл Word...");
            }

            try
            {
                template.CopyTo(tempFile, true);
            }
            catch
            {
                MessageBox.Show("Закройте файл Word...");
                return;
            }

            try
            {
                using (WordprocessingDocument package = WordprocessingDocument.Open(tempFile, true))
                {
                    //int строкаРаб = 0;

                    var tables = package.MainDocumentPart.Document.Body.Elements <Table>();

                    Table table1 = tables.ElementAt(0);
                    Table table2 = tables.ElementAt(1);


                    клXML.ChangeTextInCell(table1, 0, 0, this.Text + " " + DateTime.Today.ToLongDateString());

                    TableRow lastRow = table2.Elements <TableRow>().Last();

                    //      var queryTemp = listTemp.ToArray();
                    int j = 0;


                    foreach (temp kRow in listTemp)
                    {
                        TableRow newRow1 = lastRow.Clone() as TableRow;


                        table2.AppendChild <TableRow>(newRow1);


                        j++;

                        клXML.ChangeTextInCell(table2, j, 0, kRow.квартира.ToString("0;#;#"));
                        клXML.ChangeTextInCell(table2, j, 1, kRow.ввод.ToString("0;#;#"));
                        клXML.ChangeTextInCell(table2, j, 2, kRow.фио);

                        клXML.ChangeTextInCell(table2, j, 3, kRow.наимен_услуги);

                        клXML.ChangeTextInCell(table2, j, 4, kRow.долг_мес.ToString("0;#;#"));

                        if (kRow.отключить)
                        {
                            клXML.ChangeTextInCell(table2, j, 5, "V");
                        }
                        else
                        {
                            клXML.ChangeTextInCell(table2, j, 5, "");
                        }
                        if (kRow.договор_с != null)
                        {
                            клXML.ChangeTextInCell(table2, j, 6, kRow.договор_с.Value.ToShortDateString());
                        }
                        else
                        {
                            клXML.ChangeTextInCell(table2, j, 6, "");
                        }
                        if (kRow.отключен != null)
                        {
                            клXML.ChangeTextInCell(table2, j, 7, kRow.отключен.Value.ToShortDateString());
                        }
                        else
                        {
                            клXML.ChangeTextInCell(table2, j, 7, "");
                        }
                        if (kRow.повтор != null)
                        {
                            клXML.ChangeTextInCell(table2, j, 8, kRow.повтор.Value.ToShortDateString());
                        }
                        else
                        {
                            клXML.ChangeTextInCell(table2, j, 8, "");
                        }
                    }


                    j++;
                    клXML.ChangeTextInCell(table2, j, 0, "");
                    клXML.ChangeTextInCell(table2, j, 1, "");
                    клXML.ChangeTextInCell(table2, j, 2, "");
                    клXML.ChangeTextInCell(table2, j, 3, "");
                    клXML.ChangeTextInCell(table2, j, 4, "");
                    клXML.ChangeTextInCell(table2, j, 5, "");
                    клXML.ChangeTextInCell(table2, j, 6, "");
                    клXML.ChangeTextInCell(table2, j, 7, "");
                    клXML.ChangeTextInCell(table2, j, 8, "");
                }
                //  }
            }
            catch
            {
                MessageBox.Show("Закройте файл Word...");
                return;
            }



            клTemp.закрытьWord();


            клXML.просмотрWord(tempFile);

            Cursor = Cursors.Default;
        }
Пример #19
0
        private byte[] SetContentInPlaceholders()
        {
            byte[] output;

            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(this.generationInfo.TemplateData, 0, this.generationInfo.TemplateData.Length);

                using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(ms, true))
                {
                    wordDocument.ChangeDocumentType(WordprocessingDocumentType.Document);
                    MainDocumentPart mainDocumentPart = wordDocument.MainDocumentPart;
                    Document         document         = mainDocumentPart.Document;

                    // The sections that the user decided to remove from the build notes
                    foreach (var exclusion in this.exclusions)
                    {
                        var section =
                            document.Body.Descendants <SdtElement>().FirstOrDefault(
                                r => r.SdtProperties.GetFirstChild <Tag>().Val.HasValue&&
                                r.SdtProperties.GetFirstChild <Tag>().Val.Value ==
                                string.Format("{0}ContentControlRow", exclusion));
                        mainDocumentPart.Document.Body.RemoveChild(section);
                    }

                    if (this.generationInfo.Metadata != null)
                    {
                        this.SetDocumentProperties(mainDocumentPart, this.generationInfo.Metadata);
                    }

                    if (this.generationInfo.IsDataBoundControls)
                    {
                        this.SaveDataToDataBoundControlsDataStore(mainDocumentPart);
                    }

                    foreach (HeaderPart part in mainDocumentPart.HeaderParts)
                    {
                        this.SetContentInPlaceholders(new OpenXmlElementDataContext {
                            Element = part.Header, DataContext = this.generationInfo.DataContext
                        });
                        part.Header.Save();
                    }

                    foreach (FooterPart part in mainDocumentPart.FooterParts)
                    {
                        this.SetContentInPlaceholders(new OpenXmlElementDataContext {
                            Element = part.Footer, DataContext = this.generationInfo.DataContext
                        });
                        part.Footer.Save();
                    }

                    this.SetContentInPlaceholders(new OpenXmlElementDataContext {
                        Element = document, DataContext = this.generationInfo.DataContext
                    });

                    OpenXmlHelper.EnsureUniqueContentControlIdsForMainDocumentPart(mainDocumentPart);

                    document.Save();
                }

                ms.Position = 0;
                output      = new byte[ms.Length];
                ms.Read(output, 0, output.Length);
            }

            return(output);
        }
Пример #20
0
        public void process()
        {
            // Load docx into memory
            Package wordPackage = Package.Open(filename.Trim(), FileMode.Open, FileAccess.Read);

            using WordprocessingDocument document = WordprocessingDocument.Open(wordPackage);
            Body body = document.MainDocumentPart.Document.Body;

            List <string> lines = new List <String>();

            HashSet <string> uniqueStyles = new HashSet <string>();

            foreach (var child in body.ChildElements)
            {
                // Some method here to determine the "style" of the current block.
                // Will need to parse XML out to find a style value (header1, header2, list, etc)
                // Probably useful to just use some sort of enum here.
                Style style = parseStyle(child.InnerXml);

                if (style == Style.EMPTY_LINE && child.InnerText != "")
                {
                    style = Style.SECTION_HEADER;
                }

                int indentLevel = 0;
                if (style == Style.LIST_ELEMENT)
                {
                    int indexOfIndent       = child.InnerXml.IndexOf("<w:numPr><w:ilvl w:val=\"");
                    int indexOfOpeningQuote = indexOfIndent + "<w:numPr><w:ilvl w:val=\"".Length;
                    int indexOfClosingQuote = child.InnerXml.Substring(indexOfOpeningQuote).IndexOf("\"");

                    if (indexOfIndent != -1)
                    {
                        indentLevel = Int32.Parse(child.InnerXml.Substring(indexOfOpeningQuote, indexOfClosingQuote));
                    }
                }

                // Once style is determined, conditionally add to the MarkdownDoc out element.
                switch (style)
                {
                case Style.DOC_HEADER:
                    lines.Add("# " + child.InnerText);
                    break;

                case Style.SECTION_HEADER:
                    lines.Add("## " + child.InnerText);
                    break;

                case Style.LIST_ELEMENT:
                    if (child.InnerText != "")
                    {
                        string indents = "";
                        for (int i = 0; i < indentLevel; i++)
                        {
                            indents += "  ";
                        }
                        lines.Add(indents + "- " + child.InnerText);
                    }
                    else
                    {
                        lines.Add("\n");
                    }
                    break;

                case Style.BASIC_LINE:
                    lines.Add(child.InnerText);
                    break;

                case Style.EMPTY_LINE:
                    lines.Add("\n");
                    break;
                }
            }

            // Output is just writing the markdown to a .md file.
            // Trim output filename
            string outname = filename.Substring(0, filename.LastIndexOf(".docx"));

            outname = outname.Substring(outname.LastIndexOf("\\") + 1);
            outname = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + outname + ".md";
            File.WriteAllLines(outname, lines);
        }
        // Take the data from a 2-dimensional array and build a table at the
        // end of the supplied document.
        public static void WDAddTable(string fileName, string[,] data)
        {
            using (var document = WordprocessingDocument.Open(fileName, true))
            {
                var doc = document.MainDocumentPart.Document;

                Table table = new Table();

                TableProperties props = new TableProperties(
                    new TableBorders(
                        new TopBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 12
                },
                        new BottomBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 12
                },
                        new LeftBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 12
                },
                        new RightBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 12
                },
                        new InsideHorizontalBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 12
                },
                        new InsideVerticalBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 12
                }));
                table.AppendChild <TableProperties>(props);

                for (var i = 0; i <= data.GetUpperBound(0); i++)
                {
                    var tr = new TableRow();
                    for (var j = 0; j <= data.GetUpperBound(1); j++)
                    {
                        var tc = new TableCell();
                        tc.Append(new Paragraph(new Run(new Text(data[i, j]))));
                        // Assume you want columns that are automatically sized.
                        tc.Append(new TableCellProperties(
                                      new TableCellWidth {
                            Type = TableWidthUnitValues.Auto
                        }));
                        tr.Append(tc);
                    }
                    table.Append(tr);
                }
                doc.Body.Append(table);
                doc.Save();
            }
        }
Пример #22
0
        public static void Main()
        {
            var n      = DateTime.Now;
            var tempDi = new DirectoryInfo(
                $"ExampleOutput-{n.Year - 2000:00}-{n.Month:00}-{n.Day:00}-{n.Hour:00}{n.Minute:00}{n.Second:00}");

            tempDi.Create();

            var sourceDoc = new FileInfo("../../TestDocument.docx");
            var newDoc    = new FileInfo(Path.Combine(tempDi.FullName, "Modified.docx"));

            File.Copy(sourceDoc.FullName, newDoc.FullName);
            using (var wDoc = WordprocessingDocument.Open(newDoc.FullName, true))
            {
                var xDoc = wDoc.MainDocumentPart.GetXDocument();

                // Match content (paragraph 1)
                var content = xDoc.Descendants(W.p).Take(1);
                var regex   = new Regex("Video");
                var count   = OpenXmlRegex.Match(content, regex);
                Console.WriteLine("Example #1 Count: {0}", count);

                // Match content, case insensitive (paragraph 1)
                content = xDoc.Descendants(W.p).Take(1);
                regex   = new Regex("video", RegexOptions.IgnoreCase);
                count   = OpenXmlRegex.Match(content, regex);
                Console.WriteLine("Example #2 Count: {0}", count);

                // Match content, with callback (paragraph 1)
                content = xDoc.Descendants(W.p).Take(1);
                regex   = new Regex("video", RegexOptions.IgnoreCase);
                OpenXmlRegex.Match(content, regex, (element, match) =>
                                   Console.WriteLine("Example #3 Found value: >{0}<", match.Value));

                // Replace content, beginning of paragraph (paragraph 2)
                content = xDoc.Descendants(W.p).Skip(1).Take(1);
                regex   = new Regex("^Video provides");
                count   = OpenXmlRegex.Replace(content, regex, "Audio gives", null);
                Console.WriteLine("Example #4 Replaced: {0}", count);

                // Replace content, middle of paragraph (paragraph 3)
                content = xDoc.Descendants(W.p).Skip(2).Take(1);
                regex   = new Regex("powerful");
                count   = OpenXmlRegex.Replace(content, regex, "good", null);
                Console.WriteLine("Example #5 Replaced: {0}", count);

                // Replace content, end of paragraph (paragraph 4)
                content = xDoc.Descendants(W.p).Skip(3).Take(1);
                regex   = new Regex(" [a-z.]*$");
                count   = OpenXmlRegex.Replace(content, regex, " super good point!", null);
                Console.WriteLine("Example #6 Replaced: {0}", count);

                // Delete content, beginning of paragraph (paragraph 5)
                content = xDoc.Descendants(W.p).Skip(4).Take(1);
                regex   = new Regex("^Video provides");
                count   = OpenXmlRegex.Replace(content, regex, "", null);
                Console.WriteLine("Example #7 Deleted: {0}", count);

                // Delete content, middle of paragraph (paragraph 6)
                content = xDoc.Descendants(W.p).Skip(5).Take(1);
                regex   = new Regex("powerful ");
                count   = OpenXmlRegex.Replace(content, regex, "", null);
                Console.WriteLine("Example #8 Deleted: {0}", count);

                // Delete content, end of paragraph (paragraph 7)
                content = xDoc.Descendants(W.p).Skip(6).Take(1);
                regex   = new Regex("[.]$");
                count   = OpenXmlRegex.Replace(content, regex, "", null);
                Console.WriteLine("Example #9 Deleted: {0}", count);

                // Replace content in inserted text, same author (paragraph 8)
                content = xDoc.Descendants(W.p).Skip(7).Take(1);
                regex   = new Regex("Video");
                count   = OpenXmlRegex.Replace(content, regex, "Audio", null, true, "Eric White");
                Console.WriteLine("Example #10 Deleted: {0}", count);

                // Delete content in inserted text, same author (paragraph 9)
                content = xDoc.Descendants(W.p).Skip(8).Take(1);
                regex   = new Regex("powerful ");
                count   = OpenXmlRegex.Replace(content, regex, "", null, true, "Eric White");
                Console.WriteLine("Example #11 Deleted: {0}", count);

                // Replace content partially in inserted text, same author (paragraph 10)
                content = xDoc.Descendants(W.p).Skip(9).Take(1);
                regex   = new Regex("Video provides ");
                count   = OpenXmlRegex.Replace(content, regex, "Audio gives ", null, true, "Eric White");
                Console.WriteLine("Example #12 Replaced: {0}", count);

                // Delete content partially in inserted text, same author (paragraph 11)
                content = xDoc.Descendants(W.p).Skip(10).Take(1);
                regex   = new Regex(" to help you prove your point");
                count   = OpenXmlRegex.Replace(content, regex, "", null, true, "Eric White");
                Console.WriteLine("Example #13 Deleted: {0}", count);

                // Replace content in inserted text, different author (paragraph 12)
                content = xDoc.Descendants(W.p).Skip(11).Take(1);
                regex   = new Regex("Video");
                count   = OpenXmlRegex.Replace(content, regex, "Audio", null, true, "John Doe");
                Console.WriteLine("Example #14 Deleted: {0}", count);

                // Delete content in inserted text, different author (paragraph 13)
                content = xDoc.Descendants(W.p).Skip(12).Take(1);
                regex   = new Regex("powerful ");
                count   = OpenXmlRegex.Replace(content, regex, "", null, true, "John Doe");
                Console.WriteLine("Example #15 Deleted: {0}", count);

                // Replace content partially in inserted text, different author (paragraph 14)
                content = xDoc.Descendants(W.p).Skip(13).Take(1);
                regex   = new Regex("Video provides ");
                count   = OpenXmlRegex.Replace(content, regex, "Audio gives ", null, true, "John Doe");
                Console.WriteLine("Example #16 Replaced: {0}", count);

                // Delete content partially in inserted text, different author (paragraph 15)
                content = xDoc.Descendants(W.p).Skip(14).Take(1);
                regex   = new Regex(" to help you prove your point");
                count   = OpenXmlRegex.Replace(content, regex, "", null, true, "John Doe");
                Console.WriteLine("Example #17 Deleted: {0}", count);

                const string leftDoubleQuotationMarks = @"[\u0022“„«»”]";
                const string words = @"[\w\-&/]+(?:\s[\w\-&/]+)*";
                const string rightDoubleQuotationMarks = @"[\u0022”‟»«“]";

                // Replace content using replacement pattern (paragraph 16)
                content = xDoc.Descendants(W.p).Skip(15).Take(1);
                regex   = new Regex($"{leftDoubleQuotationMarks}(?<words>{words}){rightDoubleQuotationMarks}");
                count   = OpenXmlRegex.Replace(content, regex, "‘${words}’", null);
                Console.WriteLine("Example #18 Replaced: {0}", count);

                // Replace content using replacement pattern in partially inserted text (paragraph 17)
                content = xDoc.Descendants(W.p).Skip(16).Take(1);
                regex   = new Regex($"{leftDoubleQuotationMarks}(?<words>{words}){rightDoubleQuotationMarks}");
                count   = OpenXmlRegex.Replace(content, regex, "‘${words}’", null, true, "John Doe");
                Console.WriteLine("Example #19 Replaced: {0}", count);

                // Replace content using replacement pattern (paragraph 18)
                content = xDoc.Descendants(W.p).Skip(17).Take(1);
                regex   = new Regex($"({leftDoubleQuotationMarks})(video)({rightDoubleQuotationMarks})");
                count   = OpenXmlRegex.Replace(content, regex, "$1audio$3", null, true, "John Doe");
                Console.WriteLine("Example #20 Replaced: {0}", count);

                // Recognize tabs (paragraph 19)
                content = xDoc.Descendants(W.p).Skip(18).Take(1);
                regex   = new Regex(@"([1-9])\.\t");
                count   = OpenXmlRegex.Replace(content, regex, "($1)\t", null);
                Console.WriteLine("Example #21 Replaced: {0}", count);

                // The next two examples deal with line breaks, i.e., the <w:br/> elements.
                // Note that you should use the U+000D (Carriage Return) character (i.e., '\r')
                // to match a <w:br/> (or <w:cr/>) and replace content with a <w:br/> element.
                // Depending on your platform, the end of line character(s) provided by
                // Environment.NewLine might be "\n" (Unix), "\r\n" (Windows), or "\r" (Mac).

                // Recognize tabs and insert line breaks (paragraph 20).
                content = xDoc.Descendants(W.p).Skip(19).Take(1);
                regex   = new Regex($@"([1-9])\.{UnicodeMapper.HorizontalTabulation}");
                count   = OpenXmlRegex.Replace(content, regex, $"Article $1{UnicodeMapper.CarriageReturn}", null);
                Console.WriteLine("Example #22 Replaced: {0}", count);

                // Recognize and remove line breaks (paragraph 21)
                content = xDoc.Descendants(W.p).Skip(20).Take(1);
                regex   = new Regex($"{UnicodeMapper.CarriageReturn}");
                count   = OpenXmlRegex.Replace(content, regex, " ", null);
                Console.WriteLine("Example #23 Replaced: {0}", count);

                // Remove soft hyphens (paragraph 22)
                var paras = xDoc.Descendants(W.p).Skip(21).Take(1).ToList();
                count  = OpenXmlRegex.Replace(paras, new Regex($"{UnicodeMapper.SoftHyphen}"), "", null);
                count += OpenXmlRegex.Replace(paras, new Regex("use"), "no longer use", null);
                Console.WriteLine("Example #24 Replaced: {0}", count);

                // The next example deals with symbols (i.e., w:sym elements).
                // To work with symbols, you should acquire the Unicode values for the
                // symbols you wish to match or use in replacement patterns. The reason
                // is that UnicodeMapper will (a) mimic Microsoft Word in shifting the
                // Unicode values into the Unicode private use area (by adding U+F000)
                // and (b) use replacements for Unicode values that have been used in
                // conjunction with different fonts already (by adding U+E000).
                //
                // The replacement Únicode values will depend on the order in which
                // symbols are retrieved. Therefore, you should not rely on any fixed
                // assignment.
                //
                // In the example below, pencil will be represented by U+F021, whereas
                // spider (same value with different font) will be represented by U+E001.
                // If spider had been assigned first, spider would be U+F021 and pencil
                // would be U+E001.
                var oldPhone = UnicodeMapper.SymToChar("Wingdings", 40);
                var newPhone = UnicodeMapper.SymToChar("Wingdings", 41);
                var pencil   = UnicodeMapper.SymToChar("Wingdings", 0x21);
                var spider   = UnicodeMapper.SymToChar("Webdings", 0x21);

                // Replace or comment on symbols (paragraph 23)
                paras  = xDoc.Descendants(W.p).Skip(22).Take(1).ToList();
                count  = OpenXmlRegex.Replace(paras, new Regex($"{oldPhone}"), $"{newPhone} (replaced with new phone)", null);
                count += OpenXmlRegex.Replace(paras, new Regex($"({pencil})"), "$1 (same pencil)", null);
                count += OpenXmlRegex.Replace(paras, new Regex($"({spider})"), "$1 (same spider)", null);
                Console.WriteLine("Example #25 Replaced: {0}", count);

                wDoc.MainDocumentPart.PutXDocument();
            }

            var sourcePres = new FileInfo("../../TestPresentation.pptx");
            var newPres    = new FileInfo(Path.Combine(tempDi.FullName, "Modified.pptx"));

            File.Copy(sourcePres.FullName, newPres.FullName);
            using var pDoc = PresentationDocument.Open(newPres.FullName, true);
            foreach (var slidePart in pDoc.PresentationPart.SlideParts)
            {
                var xDoc = slidePart.GetXDocument();

                // Replace content
                var content = xDoc.Descendants(A.p);
                var regex   = new Regex("Hello");
                var count   = OpenXmlRegex.Replace(content, regex, "H e l l o", null);
                Console.WriteLine("Example #18 Replaced: {0}", count);

                // If you absolutely want to preserve compatibility with PowerPoint 2007, then you will need to strip the xml:space="preserve" attribute throughout.
                // This is an issue for PowerPoint only, not Word, and for 2007 only.
                // The side-effect of this is that if a run has space at the beginning or end of it, the space will be stripped upon loading, and content/layout will be affected.
                xDoc.Descendants().Attributes(XNamespace.Xml + "space").Remove();

                slidePart.PutXDocument();
            }
        }
        public void GenerateTable(string document, string tag, string startDate, string endDate)
        {
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
            {
                MainDocumentPart mainPart = wordDoc.MainDocumentPart;

                string   fromString = startDate;
                string   toString   = endDate;
                DateTime fromDate   = DateTime.ParseExact(fromString, "dd/MM/yyyy", null);
                DateTime toDate     = DateTime.ParseExact(toString, "dd/MM/yyyy", null);
                // date tag
                SdtRun controlTag = mainPart.Document.Body.Descendants <SdtRun>().Where
                                        (r => r.SdtProperties.GetFirstChild <Tag>().Val == "dateTag").SingleOrDefault();
                SdtContentRun contentRun = controlTag.GetFirstChild <SdtContentRun>();
                contentRun.GetFirstChild <Run>().GetFirstChild <Text>().Text = "Date: " + fromDate.ToLongDateString() + " to " + toDate.ToLongDateString();

                // This should return only one content control element: the one with
                // the specified tag value.
                // If not, "Single()" throws an exception.
                SdtBlock ccWithTable = mainPart.Document.Body.Descendants <SdtBlock>().Where
                                           (r => r.SdtProperties.GetFirstChild <Tag>().Val == tag).Single();
                // This should return only one table.
                Table theTable = ccWithTable.Descendants <Table>().Single();

                CurrentStatus     cstatus = CurrentStatus.Current;
                EndorsementStatus estatus = EndorsementStatus.Active;

                /***********************Area of health with active committees***********************/
                // display area of health which has active committees
                // in which the active committees have active reps
                // in which the active reps have prep and meeting time
                var areaOfHealth = (from aoh in db.CommitteeAreaOfHealth
                                    from comm in db.Committees
                                    from area in db.CommitteeModel_CommitteeAreaOfHealth
                                    from conh in db.ConsumerRepCommitteeHistory
                                    from conr in db.ConsumerReps
                                    where aoh.CommitteeAreaOfHealthModelID == area.CommitteeAreaOfHealthModelID
                                    where area.CommitteeModelID == comm.CommitteeModelID
                                    where conh.CommitteeModelID == comm.CommitteeModelID
                                    where conr.ConsumerRepModelID == conh.ConsumerRepModelID
                                    where comm.CurrentStatus == cstatus
                                    where conr.EndorsementStatus == estatus
                                    where conh.ReportedDate >= fromDate && conh.ReportedDate <= toDate
                                    where conh.PrepTime > 0 || conh.Meetingtime > 0
                                    select aoh).Distinct();

                int sumTotalCommittees       = 0;
                int totalSumTotalReps        = 0;
                int totalSumTotalPrepTime    = 0;
                int totalSumTotalMeetingTime = 0;
                int totalSumTotalTime        = 0;

                foreach (var aoh in areaOfHealth)
                {
                    // copy the table
                    Table tableCopy = (Table)theTable.CloneNode(true);
                    // add the table
                    ccWithTable.AppendChild(tableCopy);

                    // get the first row first element in the table
                    TableRow firstRow = tableCopy.Elements <TableRow>().First();
                    // get the last row in the table
                    TableRow lastRow = tableCopy.Elements <TableRow>().Last();

                    // add value to the first row in the table
                    firstRow.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                               (new Run(
                                                                                   new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "24"
                    }, new Bold()),
                                                                                   new Text(aoh.AreaOfHealthName.ToString()))));
                    firstRow.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                               (new Run(
                                                                                   new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                   new Text("Number of Reps"))));
                    firstRow.Descendants <TableCell>().ElementAt(2).Append(new Paragraph
                                                                               (new Run(
                                                                                   new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                   new Text("Prep Hours"))));
                    firstRow.Descendants <TableCell>().ElementAt(3).Append(new Paragraph
                                                                               (new Run(
                                                                                   new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                   new Text("Meeting Hours"))));
                    firstRow.Descendants <TableCell>().ElementAt(4).Append(new Paragraph
                                                                               (new Run(
                                                                                   new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                   new Text("Total Hours"))));

                    // display active committees within the area of health
                    // in which active committees have active reps with prep time or meeting time
                    var committees = (from com in db.Committees
                                      from aohh in db.CommitteeModel_CommitteeAreaOfHealth
                                      from crch in db.ConsumerRepCommitteeHistory
                                      from csr in db.ConsumerReps
                                      where com.CommitteeModelID == aohh.CommitteeModelID
                                      where aohh.CommitteeAreaOfHealthModelID == aoh.CommitteeAreaOfHealthModelID
                                      where crch.CommitteeModelID == com.CommitteeModelID
                                      where crch.ConsumerRepModelID == csr.ConsumerRepModelID
                                      where com.CurrentStatus == cstatus
                                      where csr.EndorsementStatus == estatus
                                      where crch.PrepTime > 0 || crch.Meetingtime > 0
                                      where crch.ReportedDate >= fromDate && crch.ReportedDate <= toDate
                                      select com).Distinct();

                    int totalCommittees     = 0;
                    int sumTotalReps        = 0;
                    int sumTotalPrepTime    = 0;
                    int sumTotalMeetingTime = 0;
                    int sumTotalTime        = 0;

                    foreach (var com in committees)
                    {
                        // all consumer reps within the committee
                        var consumerReps = (from cr in db.ConsumerReps
                                            from ch in db.ConsumerRepCommitteeHistory
                                            where ch.CommitteeModelID == com.CommitteeModelID
                                            where ch.ConsumerRepModelID == cr.ConsumerRepModelID
                                            where cr.EndorsementStatus == estatus
                                            where ch.ReportedDate >= fromDate && ch.ReportedDate <= toDate
                                            where ch.PrepTime > 0 || ch.Meetingtime > 0
                                            select cr).Distinct();

                        int totalReps        = 0;
                        int totalPrepTime    = 0;
                        int totalMeetingTime = 0;
                        int totalTime        = 0;

                        foreach (var cr in consumerReps)
                        {
                            // newest reported date of the consumer rep
                            var maxReportedDate = (from ch in db.ConsumerRepCommitteeHistory
                                                   where cr.ConsumerRepModelID == ch.ConsumerRepModelID
                                                   where ch.CommitteeModelID == com.CommitteeModelID
                                                   where ch.ReportedDate >= fromDate && ch.ReportedDate <= toDate
                                                   where cr.EndorsementStatus == estatus
                                                   select ch.ReportedDate).Max();

                            // newest consumer rep history of the consumer rep
                            var consumerRepHisotry = (from ch in db.ConsumerRepCommitteeHistory
                                                      where cr.ConsumerRepModelID == ch.ConsumerRepModelID
                                                      where ch.CommitteeModelID == com.CommitteeModelID
                                                      where ch.ReportedDate >= fromDate && ch.ReportedDate <= toDate
                                                      where cr.EndorsementStatus == estatus
                                                      where ch.ReportedDate == maxReportedDate
                                                      select ch).Distinct();

                            // total
                            totalReps++;

                            foreach (var ch in consumerRepHisotry)
                            {
                                totalPrepTime    += ch.PrepTime;
                                totalMeetingTime += ch.Meetingtime;
                                totalTime         = totalMeetingTime + totalPrepTime;
                            }
                        }

                        // row for each committee
                        TableRow rowCopy = (TableRow)lastRow.CloneNode(true);
                        rowCopy.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                                  (new Run(
                                                                                      new RunFonts {
                            Ascii = "Arial"
                        }, new RunProperties(new FontSize {
                            Val = "20"
                        }),
                                                                                      new Text(com.CommitteeName.ToString()))));
                        rowCopy.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                                  (new Run(
                                                                                      new RunFonts {
                            Ascii = "Arial"
                        }, new RunProperties(new FontSize {
                            Val = "20"
                        }),
                                                                                      new Text(totalReps.ToString()))));
                        rowCopy.Descendants <TableCell>().ElementAt(2).Append(new Paragraph
                                                                                  (new Run(
                                                                                      new RunFonts {
                            Ascii = "Arial"
                        }, new RunProperties(new FontSize {
                            Val = "20"
                        }),
                                                                                      new Text(totalPrepTime.ToString()))));
                        rowCopy.Descendants <TableCell>().ElementAt(3).Append(new Paragraph
                                                                                  (new Run(
                                                                                      new RunFonts {
                            Ascii = "Arial"
                        }, new RunProperties(new FontSize {
                            Val = "20"
                        }),
                                                                                      new Text(totalMeetingTime.ToString()))));
                        rowCopy.Descendants <TableCell>().ElementAt(4).Append(new Paragraph
                                                                                  (new Run(
                                                                                      new RunFonts {
                            Ascii = "Arial"
                        }, new RunProperties(new FontSize {
                            Val = "20"
                        }),
                                                                                      new Text(totalTime.ToString()))));
                        tableCopy.AppendChild(rowCopy);

                        // sum of total
                        totalCommittees++;
                        sumTotalReps        += totalReps;
                        sumTotalPrepTime    += totalPrepTime;
                        sumTotalMeetingTime += totalMeetingTime;
                        sumTotalTime        += totalTime;
                    }
                    // remove the empty placeholder row from the table.
                    tableCopy.RemoveChild(lastRow);

                    // add a final row to the table
                    tableCopy.AppendChild(lastRow);
                    lastRow.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                              (new Run(
                                                                                  new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                  new Text("Committees active in the period: " + totalCommittees.ToString()))));
                    lastRow.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                              (new Run(
                                                                                  new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                  new Text(sumTotalReps.ToString()))));
                    lastRow.Descendants <TableCell>().ElementAt(2).Append(new Paragraph
                                                                              (new Run(
                                                                                  new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                  new Text(sumTotalPrepTime.ToString()))));
                    lastRow.Descendants <TableCell>().ElementAt(3).Append(new Paragraph
                                                                              (new Run(
                                                                                  new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                  new Text(sumTotalMeetingTime.ToString()))));
                    lastRow.Descendants <TableCell>().ElementAt(4).Append(new Paragraph
                                                                              (new Run(
                                                                                  new RunFonts {
                        Ascii = "Arial"
                    }, new RunProperties(new FontSize {
                        Val = "20"
                    }, new Bold()),
                                                                                  new Text(sumTotalTime.ToString()))));

                    // total sum of total
                    sumTotalCommittees       += totalCommittees;
                    totalSumTotalReps        += sumTotalReps;
                    totalSumTotalPrepTime    += sumTotalPrepTime;
                    totalSumTotalMeetingTime += sumTotalMeetingTime;
                    totalSumTotalTime        += sumTotalTime;
                }
                //remove the template table
                theTable.Remove();

                //***********************Other active committees***********************/
                //get last row of active committees
                TableRow lastRowActive = theTable.Elements <TableRow>().Last();
                //get first row of active committees
                TableRow firstRowActive = theTable.Elements <TableRow>().First();

                //first row values
                firstRowActive.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                                 (new Run(
                                                                                     new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                     new Text("Active Committees that Have Not Met in This Period".ToString()))));
                firstRowActive.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                                 (new Run(
                                                                                     new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "20"
                }, new Bold()),
                                                                                     new Text("Number of Reps".ToString()))));

                var activeCommittees = (from aCom in db.Committees
                                        from aComh in db.ConsumerRepCommitteeHistory
                                        where aComh.CommitteeModelID == aCom.CommitteeModelID
                                        where aComh.PrepTime == 0 && aComh.Meetingtime == 0
                                        where aComh.ReportedDate >= fromDate && aComh.ReportedDate <= toDate
                                        where aCom.CurrentStatus == cstatus
                                        select aCom).Distinct();

                int totalcommittees = 0;
                int totalsumrep     = 0;

                foreach (var aCom in activeCommittees)
                {
                    var activeReps = (from aRep in db.ConsumerReps
                                      from aComh in db.ConsumerRepCommitteeHistory
                                      where aRep.ConsumerRepModelID == aComh.ConsumerRepModelID
                                      where aComh.CommitteeModelID == aCom.CommitteeModelID
                                      where aComh.ReportedDate >= fromDate && aComh.ReportedDate <= toDate
                                      where aRep.EndorsementStatus == estatus
                                      select aRep).Distinct();

                    int totalprep = 0;
                    int totalmeet = 0;
                    int totalrep  = 0;

                    foreach (var aRep in activeReps)
                    {
                        var maxDate = (from aComh in db.ConsumerRepCommitteeHistory
                                       where aComh.CommitteeModelID == aCom.CommitteeModelID
                                       where aComh.ConsumerRepModelID == aRep.ConsumerRepModelID
                                       where aComh.ReportedDate >= fromDate && aComh.ReportedDate <= toDate
                                       select aComh.ReportedDate).Max();

                        var activeComh = from aComh in db.ConsumerRepCommitteeHistory
                                         where aComh.CommitteeModelID == aCom.CommitteeModelID
                                         where aComh.ConsumerRepModelID == aRep.ConsumerRepModelID
                                         where aComh.ReportedDate >= fromDate && aComh.ReportedDate <= toDate
                                         where aComh.ReportedDate == maxDate
                                         select aComh;

                        foreach (var aComh in activeComh)
                        {
                            totalprep += aComh.PrepTime;
                            totalmeet += aComh.Meetingtime;
                        }

                        totalrep++;
                    }

                    if (totalprep == 0 && totalmeet == 0)
                    {
                        TableRow rowCopyActive = (TableRow)lastRowActive.CloneNode(true);
                        rowCopyActive.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                                        (new Run(
                                                                                            new RunFonts {
                            Ascii = "Arial"
                        }, new RunProperties(new FontSize {
                            Val = "20"
                        }),
                                                                                            new Text(aCom.CommitteeName.ToString()))));
                        rowCopyActive.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                                        (new Run(
                                                                                            new RunFonts {
                            Ascii = "Arial"
                        }, new RunProperties(new FontSize {
                            Val = "20"
                        }),
                                                                                            new Text(totalrep.ToString()))));
                        // add row
                        theTable.AppendChild(rowCopyActive);

                        // total active committees and reps that is doesn't have a prep time
                        totalcommittees++;
                        totalsumrep += totalrep;
                    }
                }
                // remove empty row
                theTable.RemoveChild(lastRowActive);

                /***********************Total number***********************/
                sumTotalCommittees += totalcommittees;
                totalSumTotalReps  += totalsumrep;

                // three more rows
                for (int i = 0; i < 3; i++)
                {
                    TableRow rowFinalCopy = (TableRow)lastRowActive.CloneNode(true);
                    theTable.AppendChild(rowFinalCopy);
                }
                // Get the last row in the last two rows
                TableRow theLastRow = theTable.Elements <TableRow>().Last();
                // Get the second last row
                TableRow theSecondLastRow = theTable.Elements <TableRow>().Reverse().Skip(1).First();
                // Get the third last row
                TableRow theThirdLastRow = theTable.Elements <TableRow>().Reverse().Skip(2).First();

                // edit the final three rows
                theThirdLastRow.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                                  (new Run(
                                                                                      new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "20"
                }, new Bold()),
                                                                                      new Text("Committees Active in the Period in this Grouping: " + totalcommittees.ToString()))));
                theThirdLastRow.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                                  (new Run(
                                                                                      new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "20"
                }, new Bold()),
                                                                                      new Text(totalsumrep.ToString()))));

                theSecondLastRow.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                                   (new Run(
                                                                                       new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                       new Text("Total Reps".ToString()))));
                theSecondLastRow.Descendants <TableCell>().ElementAt(2).Append(new Paragraph
                                                                                   (new Run(
                                                                                       new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                       new Text("Total Prep Hours".ToString()))));
                theSecondLastRow.Descendants <TableCell>().ElementAt(3).Append(new Paragraph
                                                                                   (new Run(
                                                                                       new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                       new Text("Total Meeting Hours"))));
                theSecondLastRow.Descendants <TableCell>().ElementAt(4).Append(new Paragraph
                                                                                   (new Run(
                                                                                       new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                       new Text("Total Hours"))));

                theLastRow.Descendants <TableCell>().ElementAt(0).Append(new Paragraph
                                                                             (new Run(
                                                                                 new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                 new Text("Total Committees Active in this Period: " + sumTotalCommittees.ToString()))));
                theLastRow.Descendants <TableCell>().ElementAt(1).Append(new Paragraph
                                                                             (new Run(
                                                                                 new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                 new Text(totalSumTotalReps.ToString()))));
                theLastRow.Descendants <TableCell>().ElementAt(2).Append(new Paragraph
                                                                             (new Run(
                                                                                 new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                 new Text(totalSumTotalPrepTime.ToString()))));
                theLastRow.Descendants <TableCell>().ElementAt(3).Append(new Paragraph
                                                                             (new Run(
                                                                                 new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                 new Text(totalSumTotalMeetingTime.ToString()))));
                theLastRow.Descendants <TableCell>().ElementAt(4).Append(new Paragraph
                                                                             (new Run(
                                                                                 new RunFonts {
                    Ascii = "Arial"
                }, new RunProperties(new FontSize {
                    Val = "32"
                }, new Bold(), new Italic()),
                                                                                 new Text(totalSumTotalTime.ToString()))));

                // add the template table
                ccWithTable.AppendChild(theTable);

                // Save the changes to the table back into the document.
                mainPart.Document.Save();
            }
        }
Пример #24
0
        /// <summary>
        /// Fills in a .docx file with the provided data.
        /// </summary>
        /// <returns>The filled-in document.</returns>
        private byte[] GetWordReport()
        {
            var dataset = new DataSet();

            // first read document in as stream
            byte[] original = File.ReadAllBytes(FileName);

            using (var stream = new MemoryStream())
            {
                stream.Write(original, 0, original.Length);

                // Create a Wordprocessing document object.
                using (var docx = WordprocessingDocument.Open(stream, true))
                {
                    // 2010/08/01: addition
                    ConvertFieldCodes(docx.MainDocumentPart.Document);

                    // first: process all tables
                    string[] switches;
                    foreach (var field in docx.MainDocumentPart.Document.Descendants <SimpleField>())
                    {
                        string fieldname = GetFieldName(field, out switches);
                        if (!string.IsNullOrEmpty(fieldname) &&
                            fieldname.StartsWith("tbl_"))
                        {
                            var wrow = GetFirstParent <TableRow>(field);
                            if (wrow == null)
                            {
                                continue;   // can happen: is because table contains multiple fields, and after 1 pass, the initial row is already deleted
                            }

                            var wtable = GetFirstParent <Table>(wrow);
                            if (wtable == null)
                            {
                                continue;   // can happen: is because table contains multiple fields, and after 1 pass, the initial row is already deleted
                            }

                            string tablename = GetTableNameFromFieldName(fieldname);

                            if (dataset == null ||
                                !dataset.Tables.Contains(tablename) ||
                                dataset.Tables[tablename].Rows.Count == 0)
                            {
                                continue;   // don't remove table here: will be done in next pass
                            }

                            var table = dataset.Tables[tablename];

                            var props           = new List <TableCellProperties>();
                            var cellcolumnnames = new List <string>();
                            var paragraphInfo   = new List <string>();
                            var cellfields      = new List <SimpleField>();

                            foreach (TableCell cell in wrow.Descendants <TableCell>())
                            {
                                props.Add(cell.GetFirstChild <TableCellProperties>());
                                var p = cell.GetFirstChild <Paragraph>();
                                if (p != null)
                                {
                                    var pp = p.GetFirstChild <ParagraphProperties>();
                                    paragraphInfo.Add(pp != null ? pp.OuterXml : null);
                                }
                                else
                                {
                                    paragraphInfo.Add(null);
                                }

                                var         colname  = string.Empty;
                                SimpleField colfield = null;
                                foreach (SimpleField cellfield in cell.Descendants <SimpleField>())
                                {
                                    colfield = cellfield;
                                    colname  = GetColumnNameFromFieldName(GetFieldName(cellfield, out switches));
                                    break;  // supports only 1 cellfield per table
                                }

                                cellcolumnnames.Add(colname);
                                cellfields.Add(colfield);
                            }

                            // keep reference to row properties
                            var rprops = wrow.GetFirstChild <TableRowProperties>();

                            foreach (DataRow row in table.Rows)
                            {
                                var nrow = new TableRow();

                                if (rprops != null)
                                {
                                    nrow.Append(new TableRowProperties(rprops.OuterXml));
                                }

                                for (int i = 0; i < props.Count; i++)
                                {
                                    var cellproperties = new TableCellProperties(props[i].OuterXml);
                                    var cell           = new TableCell();
                                    cell.Append(cellproperties);
                                    var p = new Paragraph(new ParagraphProperties(paragraphInfo[i]));
                                    cell.Append(p);   // cell must contain at minimum a paragraph !

                                    if (!string.IsNullOrEmpty(cellcolumnnames[i]))
                                    {
                                        if (!table.Columns.Contains(cellcolumnnames[i]))
                                        {
                                            throw new Exception(string.Format("Unable to complete template: column name '{0}' is unknown in parameter tables !", cellcolumnnames[i]));
                                        }

                                        if (!row.IsNull(cellcolumnnames[i]))
                                        {
                                            string val = row[cellcolumnnames[i]].ToString();
                                            p.Append(GetRunElementForText(val, cellfields[i]));
                                        }
                                    }

                                    nrow.Append(cell);
                                }

                                wtable.Append(nrow);
                            }

                            // finally : delete template-row (and thus also the mergefields in the table)
                            wrow.Remove();
                        }
                    }

                    // clean empty tables
                    foreach (var field in docx.MainDocumentPart.Document.Descendants <SimpleField>())
                    {
                        string fieldname = GetFieldName(field, out switches);
                        if (!string.IsNullOrEmpty(fieldname) &&
                            fieldname.StartsWith("tbl_"))
                        {
                            var wrow = GetFirstParent <TableRow>(field);
                            if (wrow == null)
                            {
                                continue;   // can happen: is because table contains multiple fields, and after 1 pass, the initial row is already deleted
                            }

                            var wtable = GetFirstParent <Table>(wrow);
                            if (wtable == null)
                            {
                                continue;   // can happen: is because table contains multiple fields, and after 1 pass, the initial row is already deleted
                            }

                            var tablename = GetTableNameFromFieldName(fieldname);
                            if (dataset == null ||
                                !dataset.Tables.Contains(tablename) ||
                                dataset.Tables[tablename].Rows.Count == 0)
                            {
                                // if there's a 'dt' switch: delete Word-table
                                if (switches.Contains("dt"))
                                {
                                    wtable.Remove();
                                }
                            }
                        }
                    }

                    // next : process all remaining fields in the main document
                    FillWordFieldsInElement(MergeColsValues, docx.MainDocumentPart.Document);

                    docx.MainDocumentPart.Document.Save();  // save main document back in package

                    // process header(s)
                    foreach (HeaderPart hpart in docx.MainDocumentPart.HeaderParts)
                    {
                        // 2010/08/01: addition
                        ConvertFieldCodes(hpart.Header);
                        FillWordFieldsInElement(MergeColsValues, hpart.Header);
                        hpart.Header.Save();    // save header back in package
                    }

                    // process footer(s)
                    foreach (FooterPart fpart in docx.MainDocumentPart.FooterParts)
                    {
                        // 2010/08/01: addition
                        ConvertFieldCodes(fpart.Footer);
                        FillWordFieldsInElement(MergeColsValues, fpart.Footer);
                        fpart.Footer.Save();    // save footer back in package
                    }
                }

                // get package bytes
                stream.Seek(0, SeekOrigin.Begin);
                byte[] data = stream.ToArray();

                // WdRetrieveToc(FileName);
                return(data);
            }
        }
        public void gerarContrato()
        {
            PessoaDTO fornecedor = ContratoSelected.ContratoSolicitacaoServico.Fornecedor.Pessoa;
            PessoaDTO cliente    = ContratoSelected.ContratoSolicitacaoServico.Cliente.Pessoa;

            using (ServicoContratosClient serv = new ServicoContratosClient())
            {
                cliente    = serv.selectPessoa(cliente);
                fornecedor = serv.selectPessoa(fornecedor);
            }

            string caminho = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            if (File.Exists(caminho + @"\" + ContratoSelected.Id + ".docx"))
            {
                File.Delete(caminho + @"\" + ContratoSelected.Id + ".docx");
            }

            File.Copy(caminho + @"\Modelos\contrato_servico.docx", caminho + @"\" + ContratoSelected.Id + ".docx");

            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(caminho + @"\" + ContratoSelected.Id + ".docx", true))
            {
                string docText = null;
                using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                {
                    docText = sr.ReadToEnd();
                }

                TextInfo TI = new CultureInfo("pt-BR", false).TextInfo;

                Regex regexText = new Regex("#CONTRATANTE#");
                docText = regexText.Replace(docText, TI.ToTitleCase(cliente.Nome.ToLower()));

                regexText = new Regex("#ENDERECO_CONTRATANTE#");
                docText   = regexText.Replace(docText, TI.ToTitleCase(cliente.Endereco.Logradouro.ToLower()) + ", " +
                                              cliente.Endereco.Numero + ", " + TI.ToTitleCase(cliente.Endereco.Bairro.ToLower()));

                regexText = new Regex("#CIDADE_CONTRATANTE#");
                docText   = regexText.Replace(docText, TI.ToTitleCase(cliente.Endereco.Cidade));

                regexText = new Regex("#UF_CONTRATANTE#");
                docText   = regexText.Replace(docText, TI.ToTitleCase(cliente.Endereco.Uf));

                regexText = new Regex("#CONTRATADO#");
                docText   = regexText.Replace(docText, TI.ToTitleCase(fornecedor.Nome.ToLower()));

                regexText = new Regex("#ENDERECO_CONTRATADO#");
                docText   = regexText.Replace(docText, TI.ToTitleCase(fornecedor.Endereco.Logradouro.ToLower()) + ", " +
                                              fornecedor.Endereco.Numero + ", " + TI.ToTitleCase(fornecedor.Endereco.Bairro.ToLower()));

                regexText = new Regex("#CIDADE_CONTRATADO#");
                docText   = regexText.Replace(docText, TI.ToTitleCase(cliente.Endereco.Cidade));

                regexText = new Regex("#UF_CONTRATADO#");
                docText   = regexText.Replace(docText, TI.ToTitleCase(cliente.Endereco.Uf));

                regexText = new Regex("#TIPO_SERVICO#");
                docText   = regexText.Replace(docText, ContratoSelected.ContratoSolicitacaoServico.Descricao);

                regexText = new Regex("#VALOR#");
                docText   = regexText.Replace(docText, ContratoSelected.Valor != null ? ((decimal)ContratoSelected.Valor).ToString("N2", CultureInfo.CreateSpecificCulture("pt-BR")) : "0,00");

                using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
                {
                    sw.Write(docText);
                }
            }
        }
Пример #26
0
        public void HyperlinkRelationshipTest2()
        {
            using (var stream = new MemoryStream())
            {
                using (var testDocument = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document))
                {
                    var mainPart  = testDocument.AddMainDocumentPart();
                    var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new Body());
                    mainPart.Document = new Document(new Body(paragraph));
                    mainPart.Document.Save();

                    var newUri = new System.Uri("#New", System.UriKind.Relative);
                    var ridnew = mainPart.AddHyperlinkRelationship(newUri, false);
                    var newRel = mainPart.PackagePart.GetRelationship(ridnew.Id);
                    Assert.Equal(System.IO.Packaging.TargetMode.Internal, newRel.TargetMode);
                    Assert.Equal(ridnew.Id, newRel.Id);
                    Assert.Equal(newUri, newRel.TargetUri);
                    Assert.Equal(HyperlinkRelationship.RelationshipTypeConst, newRel.RelationshipType);

                    mainPart.DeleteReferenceRelationship(ridnew);
                    Assert.Empty(mainPart.HyperlinkRelationships);

                    newUri = new System.Uri("http://microsoft.com", System.UriKind.Absolute);
                    ridnew = mainPart.AddHyperlinkRelationship(newUri, true, ridnew.Id);
                    newRel = mainPart.PackagePart.GetRelationship(ridnew.Id);
                    Assert.Equal(System.IO.Packaging.TargetMode.External, newRel.TargetMode);
                    Assert.Equal(ridnew.Id, newRel.Id);
                    Assert.Equal(newUri, newRel.TargetUri);
                    Assert.Equal(HyperlinkRelationship.RelationshipTypeConst, newRel.RelationshipType);
                }

                // Test the OpenXmlPartContainer.AddSubPartFromOtherPackage().
                // The method should import all hyperlink relationships.
                stream.Seek(0, SeekOrigin.Begin);
                using (var testDocument = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document))
                    using (var sourcestream = GetStream(TestFiles.May_12_04))
                        using (var sourceDocument = WordprocessingDocument.Open(sourcestream, false))
                        {
                            var parts = new System.Collections.Generic.Dictionary <OpenXmlPart, bool>();
                            sourceDocument.MainDocumentPart.FindAllReachableParts(parts);
                            var partCounts = parts.Count;

                            var hyperlinksBefore   = sourceDocument.MainDocumentPart.HyperlinkRelationships.ToArray();
                            var externalRelsBefore = sourceDocument.MainDocumentPart.ExternalRelationships.ToArray();

                            testDocument.AddPart(sourceDocument.MainDocumentPart);
                            parts.Clear();
                            testDocument.MainDocumentPart.FindAllReachableParts(parts);

                            // all parts under the main document part should be imported.
                            Assert.Equal(partCounts, parts.Count);

                            var hyperlinksAfter   = testDocument.MainDocumentPart.HyperlinkRelationships.ToArray();
                            var externalRelsAfter = testDocument.MainDocumentPart.ExternalRelationships.ToArray();

                            // all hyperlink relationships should be imported.
                            Assert.Equal(hyperlinksBefore.Length, hyperlinksAfter.Length);
                            for (int i = 0; i < hyperlinksBefore.Length; i++)
                            {
                                Assert.Equal(hyperlinksBefore[i].Id, hyperlinksAfter[i].Id);
                                Assert.Equal(hyperlinksBefore[i].IsExternal, hyperlinksAfter[i].IsExternal);
                                Assert.Equal(hyperlinksBefore[i].Uri, hyperlinksAfter[i].Uri);
                            }

                            // all external relationships should be imported.
                            Assert.Equal(externalRelsBefore.Length, externalRelsAfter.Length);
                        }
            }
        }
Пример #27
0
 public TemplateProcessor(Stream stream)
     : this(WordprocessingDocument.Open(stream, true))
 {
 }
Пример #28
0
        /// <summary>
        /// Generates the Word Document and performs the Mail Merge
        /// </summary>
        /// <returns>True or false(with exception) if the generation was successful or not</returns>
        public TemplateGenerationResult GenerateDocument()
        {
            try
            {
                // Don't continue if the template file name is not found
                if (!File.Exists(_templateFileName))
                {
                    _log.Error("TemplateFileName (" + _templateFileName + ") does not exist");
                    //System.IO.File.AppendAllText(@"c:\temp\errors.txt","In GenerateDocument:   " +  _templateFileName);

                    throw new Exception(message: "TemplateFileName (" + _templateFileName + ") does not exist");
                }

                // If the file is a DOTX file convert it to docx
                if (_templateFileName.ToUpper().EndsWith("DOTX"))
                {
                    TemplateGenerationResult resultValue = ConvertTemplate();

                    if (!resultValue.Value)
                    {
                        return(resultValue);
                    }
                }
                else
                {
                    // Otherwise make a copy of the Word Document to the targetFileName
                    File.Copy(_templateFileName, _targetFileName);
                }

                using (WordprocessingDocument docGenerated = WordprocessingDocument.Open(_targetFileName, true))
                {
                    docGenerated.ChangeDocumentType(WordprocessingDocumentType.Document);

                    foreach (FieldCode field in docGenerated.MainDocumentPart.RootElement.Descendants <FieldCode>())
                    {
                        string fieldname;


                        try
                        {
                            var fieldNameStart = field.Text.LastIndexOf(FieldDelimeter, System.StringComparison.Ordinal);

                            fieldname = field.Text.Substring(fieldNameStart + FieldDelimeter.Length).Trim();
                            fieldname = fieldname.Replace("\\* MERGEFORMAT", "").Trim();
                        }
                        catch (Exception)
                        {
                            continue;
                        }



                        string fieldValue = "";
                        try
                        {
                            fieldValue = _values[fieldname];
                            if (fieldname == "FundSource" && fieldValue == "Donation")
                            {
                                fieldValue = "\u2713";
                            }
                            else if (fieldname == "BudgetType" && fieldValue == "Regular")
                            {
                                fieldValue = "\u2713";
                            }
                            else if (fieldname == "FundSource")
                            {
                                fieldValue = "";
                            }
                            else if (fieldname == "BudgetType")
                            {
                                fieldValue = "";
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }


                        // Go through all of the Run elements and replace the Text Elements Text Property
                        foreach (Run run in docGenerated.MainDocumentPart.Document.Descendants <Run>())
                        {
                            foreach (Text txtFromRun in run.Descendants <Text>().Where(a => a.Text == "«" + fieldname + "»"))
                            {
                                txtFromRun.Text = fieldValue;
                            }
                        }
                    }

                    if (_transactionDetailsList.Any())
                    {
                        var table = new Table();

                        var props = new TableProperties(
                            new TableBorders(
                                new TopBorder
                        {
                            Val   = new EnumValue <BorderValues>(BorderValues.Single),
                            Size  = 6,
                            Color = "grey"
                        },
                                new BottomBorder
                        {
                            Val   = new EnumValue <BorderValues>(BorderValues.Single),
                            Size  = 6,
                            Color = "grey"
                        },
                                new LeftBorder
                        {
                            Val   = new EnumValue <BorderValues>(BorderValues.Single),
                            Size  = 6,
                            Color = "grey"
                        },
                                new RightBorder
                        {
                            Val   = new EnumValue <BorderValues>(BorderValues.Single),
                            Size  = 6,
                            Color = "grey"
                        },
                                new InsideHorizontalBorder
                        {
                            Val   = new EnumValue <BorderValues>(BorderValues.Single),
                            Size  = 6,
                            Color = "grey"
                        },
                                new InsideVerticalBorder
                        {
                            Val   = new EnumValue <BorderValues>(BorderValues.Single),
                            Size  = 6,
                            Color = "grey"
                        }));

                        //table.AppendChild<TableProperties>(props);
                        var uniqueRegions = _transactionDetailsList.Select(t => t.Region).Distinct();
                        var enumerable    = uniqueRegions as List <string> ?? uniqueRegions.ToList();
                        foreach (var uniqueRegion in uniqueRegions)
                        {
                            var transactionDetailsListOfARegion = _transactionDetailsList.Where(t => t.Region == uniqueRegion);
                            var detailsListOfARegion            = transactionDetailsListOfARegion as List <TransactionDetail> ?? transactionDetailsListOfARegion.ToList();
                            var firstOrDefault = detailsListOfARegion.FirstOrDefault();

                            var regionTr        = new TableRow();
                            var regionTc        = new TableCell();
                            var regionTcContent = new TableCell();
                            regionTc.Append(new Paragraph(new Run(new Text("Region: "))));
                            regionTcContent.Append(new Paragraph(new Run(new Text(uniqueRegion))));
                            regionTr.Append(regionTc);
                            regionTr.Append(regionTcContent);
                            table.Append(regionTr);

                            var bidNumberTr        = new TableRow();
                            var bidNumberTc        = new TableCell();
                            var bidNumberTcContent = new TableCell();
                            bidNumberTc.Append(new Paragraph(new Run(new Text("Bid Contract: "))));
                            if (firstOrDefault != null)
                            {
                                bidNumberTcContent.Append(new Paragraph(new Run(new Text(firstOrDefault.BidNumber))));
                            }
                            bidNumberTr.Append(bidNumberTc);
                            bidNumberTr.Append(bidNumberTcContent);
                            table.Append(bidNumberTr);

                            var bidDateTr        = new TableRow();
                            var bidDateTc        = new TableCell();
                            var bidDateTcContent = new TableCell();
                            bidDateTc.Append(new Paragraph(new Run(new Text("Bid Date: "))));
                            if (firstOrDefault != null)
                            {
                                bidDateTcContent.Append(new Paragraph(new Run(new Text(firstOrDefault.BidStratingDate))));
                            }
                            bidDateTr.Append(bidDateTc);
                            bidDateTr.Append(bidDateTcContent);
                            table.Append(bidDateTr);

                            var transactionTh = new TableRow();

                            var rowNoTh = new TableCell();
                            rowNoTh.Append(new Paragraph(new Run(new Text("No."))));
                            //zoneTh.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto}));
                            transactionTh.Append(rowNoTh);

                            var zoneTh = new TableCell();
                            zoneTh.Append(new Paragraph(new Run(new Text("Zone"))));
                            //zoneTh.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto}));
                            transactionTh.Append(zoneTh);

                            var woredaTh = new TableCell();
                            woredaTh.Append(new Paragraph(new Run(new Text("Woreda"))));
                            //woredaTh.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto}));
                            transactionTh.Append(woredaTh);

                            var warehouseTh = new TableCell();
                            warehouseTh.Append(new Paragraph(new Run(new Text("Warehouse (Origin)"))));
                            //warehouseTh.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto}));
                            transactionTh.Append(warehouseTh);

                            var distanceTh = new TableCell();
                            distanceTh.Append(new Paragraph(new Run(new Text("Distance From Origin"))));
                            //warehouseTh.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto}));
                            transactionTh.Append(distanceTh);

                            var tariffTh = new TableCell();
                            tariffTh.Append(new Paragraph(new Run(new Text("Tariff/Qtl (in birr)"))));
                            //tariffTh.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto}));
                            transactionTh.Append(tariffTh);
                            table.Append(transactionTh);
                            var rowNoCount = 1;
                            foreach (var transaction in detailsListOfARegion)
                            {
                                var transactionTr = new TableRow();

                                var rowNoTc = new TableCell();
                                rowNoTc.Append(new Paragraph(new Run(new Text(rowNoCount.ToString()))));
                                //zoneTc.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto }));
                                transactionTr.Append(rowNoTc);

                                var zoneTc = new TableCell();
                                zoneTc.Append(new Paragraph(new Run(new Text(transaction.Zone))));
                                //zoneTc.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto }));
                                transactionTr.Append(zoneTc);

                                var woredaTc = new TableCell();
                                woredaTc.Append(new Paragraph(new Run(new Text(transaction.Woreda))));
                                //woredaTc.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto }));
                                transactionTr.Append(woredaTc);

                                var warehouseTc = new TableCell();
                                warehouseTc.Append(new Paragraph(new Run(new Text(transaction.Warehouse))));
                                //warehouseTc.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto }));
                                transactionTr.Append(warehouseTc);

                                var distanceTc = new TableCell();
                                distanceTc.Append(new Paragraph(new Run(new Text(transaction.DistanceFromOrigin))));
                                //warehouseTc.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto }));
                                transactionTr.Append(distanceTc);

                                var tariffTc = new TableCell();
                                tariffTc.Append(new Paragraph(new Run(new Text(transaction.Tariff.ToString()))));
                                //tariffTc.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto }));
                                transactionTr.Append(tariffTc);
                                table.Append(transactionTr);

                                rowNoCount++;
                            }
                            var spacingTr = new TableRow();
                            var spacingTc = new TableCell();
                            spacingTc.Append(new Paragraph(new Run(new Text(" "))));
                            spacingTr.Append(spacingTc);
                            table.Append(spacingTr);
                            //table.Append(spacingTr);
                        }
                        docGenerated.MainDocumentPart.Document.Append(table);
                    }

                    // If the Document has settings remove them so the end user doesn't get prompted to use the data source
                    DocumentSettingsPart settingsPart = docGenerated.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();

                    var oxeSettings = settingsPart.Settings.Where(a => a.LocalName == "mailMerge").FirstOrDefault();

                    if (oxeSettings != null)
                    {
                        settingsPart.Settings.RemoveChild(oxeSettings);

                        settingsPart.Settings.Save();
                    }

                    docGenerated.MainDocumentPart.Document.Save();
                }

                return(new TemplateGenerationResult {
                    Value = true, ResultPath = _targetFileName
                });
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message.ToString(CultureInfo.InvariantCulture), ex.GetBaseException());
                //System.IO.File.AppendAllText(@"c:\temp\errors.txt", "In DocumentGeneration::generateDocument():   " + ex.Message.ToString(CultureInfo.InvariantCulture));

                return(new TemplateGenerationResult {
                    Value = false, Exception = "DocumentGeneration::generateDocument() - " + ex.ToString()
                });
            }
        }
        //[InlineData("", "")]
        //[InlineData("", "")]
        //[InlineData("", "")]
        //[InlineData("", "")]
        //[InlineData("", "")]
        //[InlineData("", "")]
        //[InlineData("", "")]
        //[InlineData("", "")]
        //[InlineData("", "")]


        public void WC002_Consolidate_Bulk_Test(string name1, string name2)
        {
            FileInfo source1Docx = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name1));
            FileInfo source2Docx = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name2));

            var source1CopiedToDestDocx = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, source1Docx.Name));
            var source2CopiedToDestDocx = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, source2Docx.Name));

            if (!source1CopiedToDestDocx.Exists)
            {
                File.Copy(source1Docx.FullName, source1CopiedToDestDocx.FullName);
            }
            if (!source2CopiedToDestDocx.Exists)
            {
                File.Copy(source2Docx.FullName, source2CopiedToDestDocx.FullName);
            }

            /************************************************************************************************************************/

            if (s_OpenWord)
            {
                FileInfo source1DocxForWord = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name1));
                FileInfo source2DocxForWord = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name2));

                var source1CopiedToDestDocxForWord = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, source1Docx.Name.Replace(".docx", "-For-Word.docx")));
                var source2CopiedToDestDocxForWord = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, source2Docx.Name.Replace(".docx", "-For-Word.docx")));
                if (!source1CopiedToDestDocxForWord.Exists)
                {
                    File.Copy(source1Docx.FullName, source1CopiedToDestDocxForWord.FullName);
                }
                if (!source2CopiedToDestDocxForWord.Exists)
                {
                    File.Copy(source2Docx.FullName, source2CopiedToDestDocxForWord.FullName);
                }

                FileInfo wordExe = new FileInfo(@"C:\Program Files (x86)\Microsoft Office\root\Office16\WINWORD.EXE");
                var      path    = new DirectoryInfo(@"C:\Users\Eric\Documents\WindowsPowerShellModules\Open-Xml-PowerTools\TestFiles");
                WordRunner.RunWord(wordExe, source2CopiedToDestDocxForWord);
                WordRunner.RunWord(wordExe, source1CopiedToDestDocxForWord);
            }

            /************************************************************************************************************************/

            var before = source1CopiedToDestDocx.Name.Replace(".docx", "");
            var after  = source2CopiedToDestDocx.Name.Replace(".docx", "");
            var docxWithRevisionsFi = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, before + "-COMPARE-" + after + ".docx"));
            var docxConsolidatedFi  = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, before + "-CONSOLIDATED-" + after + ".docx"));

            WmlDocument         source1Wml  = new WmlDocument(source1CopiedToDestDocx.FullName);
            WmlDocument         source2Wml  = new WmlDocument(source2CopiedToDestDocx.FullName);
            WmlComparerSettings settings    = new WmlComparerSettings();
            WmlDocument         comparedWml = WmlComparer.Compare(source1Wml, source2Wml, settings);

            comparedWml.SaveAs(docxWithRevisionsFi.FullName);

            List <WmlRevisedDocumentInfo> revisedDocInfo = new List <WmlRevisedDocumentInfo>()
            {
                new WmlRevisedDocumentInfo()
                {
                    RevisedDocument = source2Wml,
                    Color           = Color.LightBlue,
                    Revisor         = "Revised by Eric White",
                }
            };
            WmlDocument consolidatedWml = WmlComparer.Consolidate(
                source1Wml,
                revisedDocInfo,
                settings);

            consolidatedWml.SaveAs(docxConsolidatedFi.FullName);

            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(consolidatedWml.DocumentByteArray, 0, consolidatedWml.DocumentByteArray.Length);
                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true))
                {
                    OpenXmlValidator validator = new OpenXmlValidator();
                    var errors = validator.Validate(wDoc).Where(e => !ExpectedErrors.Contains(e.Description));
                    if (errors.Count() > 0)
                    {
                        var ind = "  ";
                        var sb  = new StringBuilder();
                        foreach (var err in errors)
                        {
#if true
                            sb.Append("Error" + Environment.NewLine);
                            sb.Append(ind + "ErrorType: " + err.ErrorType.ToString() + Environment.NewLine);
                            sb.Append(ind + "Description: " + err.Description + Environment.NewLine);
                            sb.Append(ind + "Part: " + err.Part.Uri.ToString() + Environment.NewLine);
                            sb.Append(ind + "XPath: " + err.Path.XPath + Environment.NewLine);
#else
                            sb.Append("            \"" + err.Description + "\"," + Environment.NewLine);
#endif
                        }
                        var sbs = sb.ToString();
                        Assert.Equal("", sbs);
                    }
                }
            }

            /************************************************************************************************************************/

            if (s_OpenWord)
            {
                FileInfo wordExe = new FileInfo(@"C:\Program Files (x86)\Microsoft Office\root\Office16\WINWORD.EXE");
                WordRunner.RunWord(wordExe, docxConsolidatedFi);
            }

            /************************************************************************************************************************/
        }
Пример #30
0
        public void MakeReport(/*string client, string analyst, int type*/)
        {
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(reportFile, true))
            {
                var             mainPart  = wordDocument.MainDocumentPart.Document;
                Table           testtable = new Table();
                TableProperties vishProps = new TableProperties();
                //****------ TABLE BORDERS
                TableBorders vishBorders = new TableBorders();
                TopBorder    top         = new TopBorder()
                {
                    Val = BorderValues.Single, Color = "auto"
                };
                LeftBorder left = new LeftBorder()
                {
                    Val = BorderValues.Single, Color = "auto"
                };
                RightBorder right = new RightBorder()
                {
                    Val = BorderValues.Single, Color = "auto"
                };
                BottomBorder bottom = new BottomBorder()
                {
                    Val = BorderValues.Single, Color = "auto"
                };
                InsideHorizontalBorder horizontal = new InsideHorizontalBorder()
                {
                    Val = BorderValues.Single, Color = "auto",
                };
                InsideVerticalBorder vertical = new InsideVerticalBorder()
                {
                    Val = BorderValues.Single, Color = "auto"
                };
                vishBorders.Append(top);
                vishBorders.Append(left);
                vishBorders.Append(right);
                vishBorders.Append(bottom);
                vishBorders.Append(horizontal);
                vishBorders.Append(vertical);

                //****------ TABLE STYLE
                StyleRunProperties      stylerunprops = new StyleRunProperties();
                TablePositionProperties tableposprops = new TablePositionProperties()
                {
                    VerticalAnchor = VerticalAnchorValues.Margin, HorizontalAnchor = HorizontalAnchorValues.Margin
                };

                RunFonts headResRunFonts = new RunFonts()
                {
                    Ascii = "Arial"
                };
                FontSize fontSize = new FontSize()
                {
                    Val = "9"
                };
                stylerunprops.Append(headResRunFonts, fontSize);
                TableStyle tableStyle = new TableStyle()
                {
                    Val = "TableGrid"
                };
                TableWidth tableWidth = new TableWidth()
                {
                    Width = "10920", Type = TableWidthUnitValues.Dxa
                };
                TableLook tableLook = new TableLook()
                {
                    Val = "04A0", FirstRow = true, LastRow = false, FirstColumn = true, LastColumn = false, NoHorizontalBand = false, NoVerticalBand = true
                };
                TableIndentation tableIndentation = new TableIndentation()
                {
                    Width = -10, Type = TableWidthUnitValues.Dxa
                };
                vishProps.Append(vishBorders, stylerunprops, tableWidth, tableposprops, tableStyle, tableLook, tableIndentation);
                testtable.Append(Columns(), vishProps);
                int[] widthIndex = new int[4] {
                    1780, 6230, 1590, 1320
                };
                int rows = perfectArray.GetUpperBound(0) + 1;
                int h    = 0;
                for (int i = 0; i < rows; i++)
                {
                    testtable.Append(HeaderRow());
                    var datarow = new TableRow();
                    var result  = new TableCell();
                    var name    = new TableCell();
                    var phone   = new TableCell();
                    var ext     = new TableCell();
                    var par1    = new Paragraph(new Run(new Text(String.Empty)));
                    var par2    = new Paragraph(new Run(new Text(perfectArray[i, 0])));
                    var par3    = new Paragraph(new Run(new Text(perfectArray[i, 1])));
                    var par4    = new Paragraph(new Run(new Text(perfectArray[i, 2])));

                    result.Append(par1);
                    name.Append(par2);
                    phone.Append(par3);
                    ext.Append(par4);
                    datarow.Append(result, name, phone, ext);

                    testtable.Append(datarow);
                    testtable.Append(DatesRow());
                    testtable.Append(DescriptionRow());
                }

                foreach (SdtBlock item in wordDocument.MainDocumentPart.Document.Body.Descendants <SdtBlock>().Where(e => e.Descendants <SdtAlias>().FirstOrDefault().Val == "PhoneTable"))
                {
                    item.InsertAfterSelf(testtable);
                }
                using (WordprocessingDocument newDocument = WordprocessingDocument.Create(saveFile, WordprocessingDocumentType.Document, true))
                {
                    var maindoc = newDocument.MainDocumentPart;
                    foreach (var parts in wordDocument.MainDocumentPart.Document.Descendants())
                    {
                        maindoc.Document.Append(parts);
                    }
                    newDocument.MainDocumentPart.Document.Save();
                }
            }
        }