コード例 #1
0
        public Result <FileDownloadResponse> Execute(int typiconId, FilteredOutputWeek week)
        {
            if (week == null || week.Days.Count == 0)
            {
                throw new ArgumentNullException(nameof(week));
            }

            //находим путь к файлу docx
            var docxFilePath = _configRepo.GetConfigurationValue(DOCX_CONFIG);

            byte[] byteArray = File.ReadAllBytes(docxFilePath);

            if (byteArray.Length == 0)
            {
                Result.Fail <FileDownloadResponse>("Файл шаблона не найден. Обратитесь к администратору системы.");
            }

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

                var weekViewer = new DocxScheduleWeekViewer(stream, DAYS_PER_PAGE);

                weekViewer.Execute(typiconId, week);

                DateTime date = week.Days[0].Date;

                var response = new FileDownloadResponse(stream.ToArray()
                                                        , "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                                                        , GetFileName(typiconId, date));

                return(Result.Ok(response));
            }
        }
コード例 #2
0
        public string Execute(int typiconId, FilteredOutputWeek week)
        {
            var strBuilder = new StringBuilder();

            strBuilder.AppendLine(week.Name.Text);

            foreach (var day in week.Days)
            {
                strBuilder.AppendLine("--------------------------");
                strBuilder.Append(_dayViewer.Execute(day));
            }

            return(strBuilder.ToString());
        }
コード例 #3
0
        public void DocxToStreamWeekViewer_Test()
        {

            var query = DataQueryProcessorFactory.Create();

            var mock = new Mock<IConfigurationRepository>();
            mock.Setup(c => c.GetConfigurationValue(It.IsAny<string>()))
                .Returns($@"{TestContext.CurrentContext.TestDirectory}\Data\BigTemplate.docx");

            var viewer = new DocxToStreamWeekViewer(query, mock.Object);

            var week = new FilteredOutputWeek()
            {
                Name = new ItemTextUnit("cs-ru", "Первая седмица Великого поста"),
                Days = new List<FilteredOutputDay>()
                {
                    new FilteredOutputDay()
                    {
                        Date = DateTime.Today,
                        Header = new FilteredOutputDayHeader()
                        {
                            Name = new ItemTextUnit("cs-ru", "Торжество Православия")
                        },
                        Worships = new List<FilteredOutputWorship>()
                        {
                            new FilteredOutputWorship()
                            {
                                Time = "06.00",
                                Name = new FilteredParagraph() { Text = new ItemTextUnit("cs-ru", "Полунощница") }
                            }
                        }
                    }
                }
            };

            var result = viewer.Execute(1, week);

            //using (Stream file = File.Create($@"{TestContext.CurrentContext.TestDirectory}\Data\Output.docx"))
            //{
            //    file.Write(result.Value.Content, 0, result.Value.Content.Length);
            //}

            Assert.True(result.Value.Content.Length > 0, "Пустой файл");
        }
コード例 #4
0
        public string Execute(int typiconId, FilteredOutputWeek week)
        {
            //находим путь к файлу xslt
            var xsltFilePath = configRepo.GetConfigurationValue(XSLT_CONFIG);

            var xslt = new XslCompiledTransform();

            xslt.Load(xsltFilePath);

            //получаем xml-строку
            var xml = xmlSerializer.Serialize(week);

            var xmlreader = XmlReader.Create(new StringReader(xml));

            var stringWriter = new StringWriter();
            var xmlWriter    = XmlWriter.Create(stringWriter);

            //выполняем xslt-трансформацию
            xslt.Transform(xmlreader, xmlWriter);

            return(stringWriter.ToString());
        }
コード例 #5
0
        public Result <FileDownloadResponse> Execute(int typiconId, FilteredOutputWeek week)
        {
            if (week == null || week.Days.Count == 0)
            {
                return(Result.Fail <FileDownloadResponse>("Ошибка: выходная форма седмицы не имеет дней богослужения."));
            }

            var result = PerformWork(typiconId, week);

            if (!result.Success)
            {
                return(Result.Fail <FileDownloadResponse>(result.Error));
            }

            DateTime date = week.Days[0].Date;

            var response = new FileDownloadResponse(result.Value
                                                    , "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                                                    , GetFileName(typiconId, date));

            return(Result.Ok(response));
        }
コード例 #6
0
        /// <summary>
        /// Вставляет наименование седмицы в шаблон
        /// </summary>
        /// <param name="weekDoc"></param>
        /// <param name="week"></param>
        private void SetWeekName(WordprocessingDocument weekDoc, FilteredOutputWeek week)
        {
            //находим место для вставки

            //документ
            List <Run> places = weekDoc.MainDocumentPart.Document.Body
                                .FindElementsByText(OutputTemplateConstants.WeekName)
                                .ToList();

            //заголовки
            foreach (var h in weekDoc.MainDocumentPart.HeaderParts)
            {
                places.AddRange(h.Header.FindElementsByText(OutputTemplateConstants.WeekName));
            }

            //footnotes
            foreach (var h in weekDoc.MainDocumentPart.FooterParts)
            {
                places.AddRange(h.Footer.FindElementsByText(OutputTemplateConstants.WeekName));
            }

            //заменям значения
            places.ForEach(c => c.ReplaceText(OutputTemplateConstants.WeekName, week.Name.Text));
        }
コード例 #7
0
        private Result <byte[]> PerformWork(int typiconId, FilteredOutputWeek week)
        {
            var weekTemplate = _queryProcessor.Process(new PrintWeekTemplateQuery(typiconId));

            if (weekTemplate == null)
            {
                return(Result.Fail <byte[]>($"Печатный шаблон седмицы для Устава с Id={typiconId} не был найден."));
            }

            using (MemoryStream stream = new MemoryStream())
            {
                stream.Write(weekTemplate.PrintFile, 0, weekTemplate.PrintFile.Length);

                var errors = new StringBuilder();

                using (WordprocessingDocument weekDoc = WordprocessingDocument.Open(stream, true))
                {
                    SetWeekName(weekDoc, week);

                    var placeToPasteSchedule = weekDoc.MainDocumentPart.Document.Body
                                               .FindElementsByText(OutputTemplateConstants.DaysPlacement)
                                               .FirstOrDefault();

                    if (placeToPasteSchedule == null)
                    {
                        return(Result.Fail <byte[]>("Ошибка: в шаблоне седмицы не определено место для вставки дней."));
                    }
                    //находим элемент, после которого можно вставлять шаблоны дней
                    var parentToPasteSchedule = GetParentToPasteSchedule(placeToPasteSchedule);
                    /*var */ parentToPasteSchedule = weekDoc.MainDocumentPart.Document.Body.LastChild;

                    int d = week.Days.Count % weekTemplate.DaysPerPage;

                    using (var dayRep = new PrintTemplateRepository(_queryProcessor))
                    {
                        for (int i = week.Days.Count - 1; i >= 0; i--)
                        {
                            var day = week.Days[i];

                            var modDayTemplate = GetFilledDayElements(dayRep, typiconId, day);

                            if (modDayTemplate.Success)
                            {
                                //добавляем в конечный документ ссылочные объекты (изображения)
                                CopyRelativeElements(weekDoc, modDayTemplate.Value.DocumentPart, modDayTemplate.Value.XmlElements);

                                foreach (var ins in modDayTemplate.Value.XmlElements)
                                {
                                    parentToPasteSchedule.InsertAfterSelf(ins);
                                    //ins.CopyRelativeElements(weekDoc, modDayTemplate.Value.DocumentPart);
                                }

                                d--;
                                if (d == 0 && i > 0)
                                {
                                    //вставляем разрыв страницы
                                    parentToPasteSchedule.InsertAfterSelf(PageBreak);
                                    d = weekTemplate.DaysPerPage;
                                }
                            }
                            else
                            {
                                errors.AppendLine(modDayTemplate.Error);
                            }
                        }
                    }

                    RemovePlaceToPaste(placeToPasteSchedule);

                    weekDoc.MainDocumentPart.Document.Save();

                    weekDoc.Close();
                }

                return((errors.Length == 0)
                        ? Result.Ok(stream.ToArray())
                        : Result.Fail <byte[]>(errors.ToString()));
            }
        }
コード例 #8
0
        public string Execute(int typiconId, FilteredOutputWeek week)
        {
            string _resultString = "";

            _resultString += "<div class=\"schedule\">";

            //Название седмицы пропускаем. Считаем, что название седмицы будет в наименовании файла
            _resultString += "<h4 class=\"subtitle\">" + week.Name.Text.ToUpper() + "</h4>";

            //теперь начинаем наполнять дни
            foreach (var day in week.Days)
            {
                _resultString += "<div style=\"margin - top:10px; \">";

                //Sign
                if (day.Header?.Icon.HasValue == true)
                {
                    _resultString += "<img src=\"http://www.typicon.online/images/sign/" + day.Header.Icon + ".png\"/>";
                }

                //если бдение или бдение с литией или воскресный день - красим в красный цвет
                if (day.Header?.IsRed == true)
                {
                    _resultString += "<span style=\"color: #ff0000;\">";
                }

                _resultString += "<strong>" + day.Date.ToString("dd MMMM yyyy г.") + "<br/>";
                _resultString += day.Date.ToString("dddd").ToUpper() + "<br/>";

                if (day.Header != null)
                {
                    _resultString += day.Header.Name + "</strong>";
                }

                if (day.Header?.IsRed == true)
                {
                    _resultString += "</span>";
                }

                _resultString += "</div>";

                _resultString += "<table border=0>";

                foreach (var service in day.Worships)
                {
                    _resultString += "<tr><td>";

                    _resultString += service.Time.ToString() + "&nbsp;</td><td>";
                    _resultString += service.Name.Text;

                    //additionalName
                    if (service.AdditionalName != null)
                    {
                        _resultString += "<strong>" + service.AdditionalName.Text + "</strong>";
                    }
                    _resultString += "</td></tr>";
                }

                _resultString += "</table>";
            }

            _resultString += "</div>";

            return(_resultString);
        }
コード例 #9
0
        public void Execute(int typiconId, FilteredOutputWeek week)
        {
            if (week == null)
            {
                throw new ArgumentNullException(nameof(week));
            }

            using (WordprocessingDocument doc = WordprocessingDocument.Open(_stream, true))
            {
                //просматриваем все элементы ChildElements и выбираем только таблицы
                //считаем, что всего таблиц 10.
                //0 - шапка с названием седмицы, а остальные - шаблоны для обозначения знаков служб

                //эта коллекция будет вместилищем таблиц - docx-шаблонов
                var templateTables = new List <Table>();
                //ищем их все и добавляем в коллекцию
                foreach (OpenXmlElement element in doc.MainDocumentPart.Document.Body.ChildElements)
                {
                    if (element.GetType() == typeof(Table))
                    {
                        templateTables.Add((Table)element);
                    }
                }

                //создаем коллекцию таблиц, которые будут результирующим содержанием выходного документа
                List <OpenXmlElement> resultElements = new List <OpenXmlElement>();

                int i = _daysPerPage;

                bool firstTime = true;

                foreach (var day in week.Days)
                {
                    //шапка
                    if (i == _daysPerPage)
                    {
                        if (!firstTime)
                        {
                            //вставляем разрыв страницы
                            resultElements.Add(GetPageBreak());
                        }
                        firstTime = false;

                        //Название седмицы
                        //table[2]->tr[1]->td[1]->p[1]->r[1]->t[1]
                        Table headerTable = GetHeaderTable(templateTables[0], week.Name.Text);
                        resultElements.Add(headerTable);
                    }
                    Table dayTable = GetDayTable(day, templateTables);
                    //добавляем таблицу к выходной коллекции
                    resultElements.Add(dayTable);

                    i--;
                    if (i == 0)
                    {
                        i = _daysPerPage;
                    }
                }

                //в конце удаляем все из документа, оставляя только колонтитулы (прописаны в SectionProperties) и результирующие таблицы

                foreach (OpenXmlElement el in doc.MainDocumentPart.Document.Body.ChildElements)
                {
                    if (el.GetType() == typeof(SectionProperties))
                    {
                        resultElements.Add(el);
                        break;
                    }
                }

                doc.MainDocumentPart.Document.Body.RemoveAllChildren();
                foreach (OpenXmlElement t in resultElements)
                {
                    doc.MainDocumentPart.Document.Body.AppendChild(t);
                }

                if (_isFromFileName)
                {
                    //если место было указано из файла, сохраняем его
                    doc.MainDocumentPart.Document.Save();
                }
            }
        }