Exemplo n.º 1
0
        //Вертикальная вставка данных в таблицу
        private static void AddToTableVertical(MainDocumentPart doc, int table_number, List<List<string>> data)
        {
            Table table = doc.Document.Body.Elements<Table>().ElementAt(table_number);
            // строка-образец
            TableRow ltr = table.Elements<TableRow>().Last();
            foreach (var item in data)
            {
                var tr = new TableRow();
                int j = 0;
                int i = 0;
                foreach (var val in item)
                {
                    // получаем форматирование очередной ячейки в строке-образце
                    TableCell template_cell = ltr.Elements<TableCell>().ElementAt(j);
                    j++;
                    Paragraph template_paragraph = template_cell.Elements<Paragraph>().First();
                    ParagraphMarkRunProperties template_run = template_paragraph.ParagraphProperties.Elements<ParagraphMarkRunProperties>().First();

                    //Создаем новую ячейку
                    var tc = new TableCell();
                    Paragraph new_paragraph = new Paragraph();
                    Run new_run = new Run();

                    // устанавливаем форматирование новой ячейки
                    new_paragraph.Append(template_paragraph.ParagraphProperties.CloneNode(true));
                    new_run.Append(template_run.CloneNode(true));
                    new_paragraph.Append(new_run);
                    //Вставляем текст в новую ячейку
                    tc.Append(new_paragraph);
                    InsertTableText(new_run, val);
                    tr.Append(tc);
                }
                i++;
                table.Append(tr);
            }
            table.RemoveChild(table.Elements<TableRow>().ElementAt(1));
        }
Exemplo n.º 2
0
        //向下插入資料並保持原格式
        //undo
        public static void TableRowInsert(Table tb, DataTable data)
        {
            //if (tb.Elements<GridColumn>().Count() != data.Columns.Count)
            //{
            //    throw new Exception("目標表格與dataTable不符");
            //}
            foreach (DataRow dr in data.Rows)
            {
                TableRow tr = (TableRow)tb.Elements <TableRow>().Last().CloneNode(true);

                for (int i = 0; i < data.Columns.Count; i++)
                {
                    //TableCell tc = (TableCell)tr.Elements<TableCell>().First().CloneNode(true);
                    //tr.RemoveAllChildren<TableCell>();
                    //tc.AppendChild(tc);
                    TableCell tc = tr.Elements <TableCell>().ElementAt(i);

                    Paragraph p = tc.Elements <Paragraph>().FirstOrDefault() ?? new Paragraph();
                    if (p.Parent == null)
                    {
                        tc.AppendChild <Paragraph>(p);
                    }
                    Run  r    = (Run)(p.Elements <Run>().FirstOrDefault() ?? new Run()).CloneNode(true);
                    Text text = r.Elements <Text>().FirstOrDefault() ?? new Text();
                    if (text.Parent == null)
                    {
                        r.AppendChild <Text>(text);
                    }
                    text.Text = dr[i].ToString();
                    p.RemoveAllChildren <Run>();
                    p.AppendChild <Run>(r);
                    //tr.AppendChild<TableCell>(new TableCell(new TableCellProperties(new Paragraph(new Run(new Text(dr[i].ToString()))))));
                }
                tb.AppendChild <TableRow>(tr);
            }
        }
Exemplo n.º 3
0
        private void ProcessTd(int colIndex, DocxNode td, TableRow row, DocxTableProperties tableProperties)
        {
            TableCell cell       = new TableCell();
            bool      hasRowSpan = false;

            string rowSpan = td.ExtractAttributeValue(DocxTableProperties.rowSpan);
            Int32  rowSpanValue;

            if (Int32.TryParse(rowSpan, out rowSpanValue))
            {
                tableProperties.RowSpanInfo[colIndex] = rowSpanValue - 1;
                hasRowSpan = true;
            }

            DocxTableCellStyle style = new DocxTableCellStyle();

            style.HasRowSpan = hasRowSpan;
            style.Process(cell, tableProperties, td);

            if (td.HasChildren)
            {
                Paragraph para = null;

                //If the cell is th header, apply font-weight:bold to the text
                if (tableProperties.IsCellHeader)
                {
                    SetThStyleToRun(td);
                }

                foreach (DocxNode child in td.Children)
                {
                    td.CopyExtentedStyles(child);

                    if (child.IsText)
                    {
                        if (!IsEmptyText(child.InnerHtml))
                        {
                            if (para == null)
                            {
                                para = cell.AppendChild(new Paragraph());
                                OnParagraphCreated(DocxTableCellStyle.GetHtmlNodeForTableCellContent(td), para);
                            }

                            Run run = para.AppendChild(new Run(new Text()
                            {
                                Text  = ClearHtml(child.InnerHtml),
                                Space = SpaceProcessingModeValues.Preserve
                            }));

                            RunCreated(child, run);
                        }
                    }
                    else
                    {
                        child.ParagraphNode = DocxTableCellStyle.GetHtmlNodeForTableCellContent(td);
                        child.Parent        = cell;
                        td.CopyExtentedStyles(child);
                        ProcessChild(child, ref para);
                    }
                }
            }

            //The last element of the table cell must be a paragraph.
            var lastElement = cell.Elements().LastOrDefault();

            if (lastElement == null || !(lastElement is Paragraph))
            {
                cell.AppendChild(new Paragraph());
            }

            row.Append(cell);
        }
Exemplo n.º 4
0
        public void FillTableCell(int tableIndex, int colIndex, int rowIndex, TImgResult img)
        {
            Table table = doc.MainDocumentPart.Document.Body.Elements <Table>().ElementAt(tableIndex);

            // Find the second row in the table.
            TableRow row = table.Elements <TableRow>().ElementAt(rowIndex);

            // Find the third cell in the row.
            TableCell cell = row.Elements <TableCell>().ElementAt(colIndex);

            // Find the first paragraph in the table cell.
            Paragraph p = cell.Elements <Paragraph>().First();


            // Define the reference of the image.
            var element =
                new Drawing(
                    new DW.Inline(
                        new DW.Extent()
            {
                Cx = img.width, Cy = img.height
            },
                        new DW.EffectExtent()
            {
                LeftEdge   = 0L,
                TopEdge    = 0L,
                RightEdge  = 0L,
                BottomEdge = 0L
            },
                        new DW.DocProperties()
            {
                Id   = (UInt32Value)1U,
                Name = "Picture 1"
            },
                        new DW.NonVisualGraphicFrameDrawingProperties(
                            new A.GraphicFrameLocks()
            {
                NoChangeAspect = true
            }),
                        new A.Graphic(
                            new A.GraphicData(
                                new PIC.Picture(
                                    new PIC.NonVisualPictureProperties(
                                        new PIC.NonVisualDrawingProperties()
            {
                Id   = (UInt32Value)0U,
                Name = "New Bitmap Image.png"
            },
                                        new PIC.NonVisualPictureDrawingProperties()),
                                    new PIC.BlipFill(
                                        new A.Blip(
                                            new A.BlipExtensionList(
                                                new A.BlipExtension()
            {
                Uri =
                    "{28A0092B-C50C-407E-A947-70E740481C1C}"
            })
                                            )
            {
                Embed            = img.ID,
                CompressionState =
                    A.BlipCompressionValues.Print
            },
                                        new A.Stretch(
                                            new A.FillRectangle())),
                                    new PIC.ShapeProperties(
                                        new A.Transform2D(
                                            new A.Offset()
            {
                X = 0L, Y = 0L
            },
                                            new A.Extents()
            {
                Cx = img.width, Cy = img.height
            }),
                                        new A.PresetGeometry(
                                            new A.AdjustValueList()
                                            )
            {
                Preset = A.ShapeTypeValues.Rectangle
            }))
                                )
            {
                Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
            })
                        )
            {
                DistanceFromTop    = (UInt32Value)0U,
                DistanceFromBottom = (UInt32Value)0U,
                DistanceFromLeft   = (UInt32Value)0U,
                DistanceFromRight  = (UInt32Value)0U,
                EditId             = "50D07946"
            });



            // Find the first run in the paragraph.
            Run r = p.Elements <Run>().First();

            r.Append(element);

            // Set the text for the run.
            //Text t = r.Elements<Text>().First();
            //t.Text = txt;
        }
Exemplo n.º 5
0
        public void FillTableCell(int tableIndex, int colIndex, int rowIndex, TextBoxProps tbp)
        {
            Table table = doc.MainDocumentPart.Document.Body.Elements <Table>().ElementAt(tableIndex);

            // Find the second row in the table.
            TableRow row = table.Elements <TableRow>().ElementAt(rowIndex);

            // Find the third cell in the row.
            TableCell cell = row.Elements <TableCell>().ElementAt(colIndex);

            // Find the first paragraph in the table cell.
            Paragraph p = cell.Elements <Paragraph>().First();

            Picture pict = new Picture();

            DocumentFormat.OpenXml.Vml.Shape s = new DocumentFormat.OpenXml.Vml.Shape()
            {
                Style = "position:absolute;top:" + (tbp.y * 3.79).ToString() + ";left:" + (tbp.x * 4).ToString() + ";width:" + (tbp.width * 3.79).ToString() + ";height:" + (tbp.height * 3.79).ToString() + ";margin-left:0pt;margin-top:0pt;rotation:0;v-rotate-letters:true;mso-rotate:90", Filled = false, Stroked = false
            };
            //DocumentFormat.OpenXml.Vml.Shapetype st = new DocumentFormat.OpenXml.Vml.Shapetype();
            //st.

            DocumentFormat.OpenXml.Vml.TextBox tb = new DocumentFormat.OpenXml.Vml.TextBox()
            {
                Inset = "0,0,0,0"
            };
            Paragraph           par = new Paragraph();
            ParagraphProperties paragraphProperties = new ParagraphProperties();
            SpacingBetweenLines spacing             = new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            };

            paragraphProperties.Append(spacing);
            paragraphProperties.Append(new ParagraphStyleId()
            {
                Val = "No Spacing"
            });
            par.Append(paragraphProperties);
            Run           r   = new Run();
            RunProperties rPr = new RunProperties(new RunFonts()
            {
                HighAnsi = tbp.font.Name, Ascii = tbp.font.Name, ComplexScript = tbp.font.Name
            }, new FontSize()
            {
                Val = ((int)(tbp.font.Size * 2)).ToString()
            }, new DocumentFormat.OpenXml.Wordprocessing.Color()
            {
                Val = tbp.color.R.ToString("X2") + tbp.color.G.ToString("X2") + tbp.color.B.ToString("X2")
            });                                                                                                                                                                                                                                                                                                                                                           // fontsize in half-points

            r.PrependChild <RunProperties>(rPr);
            r.Append(new Text(tbp.text));
            par.Append(r);
            TextBoxContent tbc = new TextBoxContent();

            tbc.Append(par);
            tb.Append(tbc);
            s.Append(tb);
            pict.Append(s);
            p.Append(new Run(pict));


            // Set the text for the run.
            //Text t = r.Elements<Text>().First();
            //t.Text = txt;
        }
Exemplo n.º 6
0
    public static void AddRow(this Table table, string[] cells, string[] styles = null, bool singleSpace = true)
    {
        TableRow tr = new TableRow();
        for (int i = 0; i < cells.Length; i++)
        {
            TableCell tc = new TableCell();
            if(cells[i].Contains("|"))
            {
                Paragraph para = tc.AppendChild(new Paragraph(new ParagraphProperties()));
                Run run = para.AppendChild(new Run(new RunProperties()));

                string[] values = cells[i].Split('|');
                for(int j = 0, jj = values.Length; j < jj; j++)
                {
                    if(j != 0)
                        run.AppendChild(new Break());

                    run.AppendChild(new Text(values[j]));
                }
            }
            else
                tc.AppendChild(new Paragraph(new ParagraphProperties(), new Run(new RunProperties(), new Text(cells[i]))));

            tr.Append(tc);

            foreach (OpenXmlElement els in tc.Elements())
            {
                if (els.GetType() == typeof(Paragraph))
                {
                    Paragraph para = (Paragraph)els;
                    if(singleSpace)
                        para.ParagraphProperties.AppendChild(new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" });
                    else
                        para.ParagraphProperties.AppendChild(new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "240", After = "0" });
                }
            }
            if (styles != null && styles.Length > i && !string.IsNullOrEmpty(styles[i]))
            {
                TableCellProperties props = new TableCellProperties();
                tc.Append(props);
                if (styles[i].Contains("LeftIndent"))
                {
                    string value = styles[i].Substring(styles[i].IndexOf("LeftIndent:") + 11);
                    if (value.Contains("|"))
                        value = value.Substring(0, value.IndexOf("|"));
                    props.LeftIndent(value);
                }
                if (styles[i].Contains("RightIndent"))
                {
                    string value = styles[i].Substring(styles[i].IndexOf("RightIndent:") + 12);
                    if (value.Contains("|"))
                        value = value.Substring(0, value.IndexOf("|"));
                    props.RightIndent(value);
                }
                if (styles[i].Contains("TopIndent"))
                {
                    string value = styles[i].Substring(styles[i].IndexOf("TopIndent:") + 10);
                    if (value.Contains("|"))
                        value = value.Substring(0, value.IndexOf("|"));
                    props.TopIndent(value);
                }
                if (styles[i].Contains("Background"))
                {
                    string value = styles[i].Substring(styles[i].IndexOf("Background:") + 11);
                    if (value.Contains("|"))
                        value = value.Substring(0, value.IndexOf("|"));
                    props.BackgroundColor(value);
                }
                if (styles[i].Contains("Bold"))
                    tc.Bold();
                if (styles[i].Contains("JustifyRight"))
                    tc.Right();
                if (styles[i].Contains("JustifyCenter"))
                    tc.Center();
                if(styles[i].Contains("FontSize"))
                {
                    string value = styles[i].Substring(styles[i].IndexOf("FontSize:") + 9);
                    if (value.Contains("|"))
                        value = value.Substring(0, value.IndexOf("|"));
                    tc.FontSize(value);
                }
                if (styles[i].Contains("FontColor"))
                {
                    string value = styles[i].Substring(styles[i].IndexOf("FontColor:") + 10);
                    if (value.Contains("|"))
                        value = value.Substring(0, value.IndexOf("|"));
                    tc.FontColor(value);
                }
                if (styles[i].Contains("VerticalText"))
                {
                    string value = styles[i].Substring(styles[i].IndexOf("VerticalText:") + 13);
                    if (value.Contains("|"))
                        value = value.Substring(0, value.IndexOf("|"));
                    props.VerticalText(value);
                }
                if (styles[i].Contains("Borders"))
                {
                    string value = styles[i].Substring(styles[i].IndexOf("Borders:") + 8);
                    if (value.Contains("|"))
                        value = value.Substring(0, value.IndexOf("|"));
                    props.Borders(value);
                }
                if (styles[i].Contains("VerticalMerge"))
                {
                    string value = styles[i].Substring(styles[i].IndexOf("VerticalMerge:") + 14);
                    if (value.Contains("|"))
                        value = value.Substring(0, value.IndexOf("|"));
                    props.VertMerge(value);
                }
                if (styles[i].Contains("HorizontalMerge"))
                {
                    string value = styles[i].Substring(styles[i].IndexOf("HorizontalMerge:") + 16);
                    if (value.Contains("|"))
                        value = value.Substring(0, value.IndexOf("|"));
                    props.HorizMerge(value);
                }
            }
        }

        table.AppendChild(tr);
    }
Exemplo n.º 7
0
        private void ProcessTd(int colIndex, DocxNode td, TableRow row, DocxTableProperties tableProperties)
        {
            TableCell cell = new TableCell();
            bool hasRowSpan = false;

            string rowSpan = td.ExtractAttributeValue(DocxTableProperties.rowSpan);
            Int32 rowSpanValue;
            if (Int32.TryParse(rowSpan, out rowSpanValue))
            {
                tableProperties.RowSpanInfo[colIndex] = rowSpanValue - 1;
                hasRowSpan = true;
            }

            DocxTableCellStyle style = new DocxTableCellStyle();
            style.HasRowSpan = hasRowSpan;
            style.Process(cell, tableProperties, td);

            if (td.HasChildren)
            {
                Paragraph para = null;

                //If the cell is th header, apply font-weight:bold to the text
                if (tableProperties.IsCellHeader)
                {
                    SetThStyleToRun(td);
                }

                foreach (DocxNode child in td.Children)
                {
                    td.CopyExtentedStyles(child);
                    
                    if (child.IsText)
                    {
                        if (!IsEmptyText(child.InnerHtml))
                        {
                            if (para == null)
                            {
                                para = cell.AppendChild(new Paragraph());
                                OnParagraphCreated(DocxTableCellStyle.GetHtmlNodeForTableCellContent(td), para);
                            }

                            Run run = para.AppendChild(new Run(new Text()
                            {
                                Text = ClearHtml(child.InnerHtml),
                                Space = SpaceProcessingModeValues.Preserve
                            }));

                            RunCreated(child, run);
                        }
                    }
                    else
                    {
                        child.ParagraphNode = DocxTableCellStyle.GetHtmlNodeForTableCellContent(td);
                        child.Parent = cell;
                        td.CopyExtentedStyles(child);
                        ProcessChild(child, ref para);
                    }
                }
            }

            //The last element of the table cell must be a paragraph.
            var lastElement = cell.Elements().LastOrDefault();

            if (lastElement == null || !(lastElement is Paragraph))
            {
                cell.AppendChild(new Paragraph());
            }

            row.Append(cell);
        }
Exemplo n.º 8
0
        public void CreateMSWordDocument(Guid identifier)
        {
            var    myResume    = _resumeManagerRepository.Get(m => m.Guid.Equals(identifier)).First().Resume;
            string projPath    = HttpContext.Current.Server.MapPath("~/Content/");
            string outFilePath = Path.Combine(projPath, "doc", myResume.ResumeManager.Link);

            byte[] templateBytes = System.IO.File.ReadAllBytes(projPath + "MSWordTemplates\\template4.dotx");

            using (MemoryStream templateStream = new MemoryStream())
            {
                templateStream.Write(templateBytes, 0, (int)templateBytes.Length);

                using (WordprocessingDocument doc = WordprocessingDocument.Open(templateStream, true))
                {
                    doc.ChangeDocumentType(WordprocessingDocumentType.Document);
                    var mainPart = doc.MainDocumentPart;

                    // Get the Document Settings Part
                    DocumentSettingsPart documentSettingPart1 = mainPart.DocumentSettingsPart;

                    // Create a new attachedTemplate and specify a relationship ID
                    AttachedTemplate attachedTemplate1 = new AttachedTemplate()
                    {
                        Id = "relationId1"
                    };

                    // Append the attached template to the DocumentSettingsPart
                    documentSettingPart1.Settings.Append(attachedTemplate1);

                    // Add an ExternalRelationShip of type AttachedTemplate.
                    // Specify the path of template and the relationship ID
                    documentSettingPart1.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new Uri(projPath + "MSWordTemplates\\template4.dotx", UriKind.Absolute), "relationId1");

                    string fullname = string.Format("{0} {1}", myResume.FirstName, myResume.LastName);
                    SetCCText(mainPart, "FullName", fullname);

                    SetCCText(mainPart, "Goal", myResume.Goal);
                    SetCCText(mainPart, "Location", myResume.CurrentLocation);

                    string email = myResume.Contacts.First(c => c.ContactTitle.Title.Equals("EMail")).Data;
                    SetCCText(mainPart, "Email", email);

                    string phone = myResume.Contacts.First(c => c.ContactTitle.Title.Equals("Phone")).Data;
                    SetCCText(mainPart, "Phone", phone);

                    RemoveCCChild(mainPart, "OtherContacts");
                    foreach (var contact in myResume.Contacts.Where(c => !c.ContactTitle.Title.Equals("EMail") && !c.ContactTitle.Title.Equals("Phone")))
                    {
                        AppendCCText(mainPart, "OtherContacts", string.Format("{0}: {1}", contact.ContactTitle.Title, contact.Data));
                    }

                    // ОБРАЗОВАНИЕ
                    if (myResume.Education.Count > 0)
                    {
                        SdtBlock contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Education").Single();
                        Table    theTable       = contentControl.Descendants <Table>().Single();
                        TableRow defaultRow     = theTable.Elements <TableRow>().Last();

                        foreach (var institution in myResume.Education)
                        {
                            TableRow rowCopy = (TableRow)defaultRow.CloneNode(true);

                            // период учебы
                            var periodRun = rowCopy.Descendants <TableCell>().ElementAt(0).GetFirstChild <Paragraph>().GetFirstChild <Run>();
                            periodRun.GetFirstChild <Text>().Text = string.Format("{0} –", institution.From.Format());
                            periodRun.Append(new Break());
                            periodRun.Append(new Text(institution.To.Format()));

                            // описание уч. заведениия:
                            // название и город
                            TableCell secondColumn = rowCopy.Descendants <TableCell>().ElementAt(1);
                            SetCCText(secondColumn, "InstitutionName", string.Format("{0}, г. {1}", institution.Name, institution.City));

                            // кафедра
                            if (string.IsNullOrEmpty(institution.Department))
                            {
                                secondColumn.Descendants <SdtRun>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "InstitutionDepartment").Single().Parent.Remove();
                            }
                            else
                            {
                                SetCCText(secondColumn, "InstitutionDepartment", institution.Department);
                            }

                            // специальность
                            SetCCText(secondColumn, "InstitutionSpeciality", institution.Specialty);
                            secondColumn.Elements <Paragraph>().Last().Append(new Run(new Break()));

                            theTable.AppendChild(rowCopy);
                        }
                        theTable.RemoveChild(defaultRow);
                    }
                    else
                    {
                        mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Education").Single().Remove();
                    }

                    // ОПЫТ РАБОТЫ
                    if (myResume.WorkExp.Count > 0)
                    {
                        SdtBlock contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Experience").Single();
                        Table    theTable       = contentControl.Descendants <Table>().Single();
                        TableRow defaultRow     = theTable.Elements <TableRow>().Last();

                        foreach (var workPlace in myResume.WorkExp)
                        {
                            TableRow rowCopy = (TableRow)defaultRow.CloneNode(true);

                            // период в который работали
                            var periodRun = rowCopy.Descendants <TableCell>().ElementAt(0).GetFirstChild <Paragraph>().GetFirstChild <Run>();
                            periodRun.GetFirstChild <Text>().Text = string.Format("{0} –", workPlace.From.Format());
                            periodRun.Append(new Break());
                            periodRun.Append(new Text(workPlace.To.Format()));

                            // описание работы:
                            // название работы и город
                            TableCell secondColumn = rowCopy.Descendants <TableCell>().ElementAt(1);
                            SetCCText(secondColumn, "WorkplaceName", string.Format("{0}, г. {1}", workPlace.Name, workPlace.City));

                            // должность
                            SetCCText(secondColumn, "WorkplacePosition", workPlace.Position);

                            // обязанности
                            if (workPlace.Duties.Count > 0)
                            {
                                RemoveCCChild(secondColumn, "WorkplaceDuties");
                                foreach (var duty in workPlace.Duties)
                                {
                                    AppendCCText(secondColumn, "WorkplaceDuties", string.Format("– {0}", duty.Name));
                                }
                            }
                            else
                            {
                                secondColumn.Descendants <SdtRun>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "WorkplaceDuties").Single().Parent.Remove();
                            }

                            //secondColumn.Elements<Paragraph>().Last().Append(new Run(new Break()));

                            theTable.AppendChild(rowCopy);
                        }
                        theTable.RemoveChild(defaultRow);
                    }
                    else
                    {
                        mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Experience").Single().Remove();
                    }


                    // СЕРТИФИКАТЫ
                    if (myResume.CertificatesAndTrainings.Count > 0)
                    {
                        RemoveCCChild(mainPart, "Certificates");
                        foreach (var certificate in myResume.CertificatesAndTrainings)
                        {
                            AppendCCText(mainPart, "Certificates", string.Format("{0} – {1}{2}", certificate.Date.Year, certificate.Name, certificate.Location != null ? string.Format(", г. {0}", certificate.Location) : ""));
                        }
                    }
                    else
                    {
                        RemoveCC(mainPart, "Section_Certificates");
                    }

                    // ЯЗЫКИ
                    if (myResume.Languages.Count > 0)
                    {
                        SdtBlock        contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Languages").Single();
                        SdtContentBlock contentRun     = contentControl.GetFirstChild <SdtContentBlock>();
                        Paragraph       defaultLi      = contentRun.GetFirstChild <Paragraph>();

                        foreach (var language in myResume.Languages)
                        {
                            Paragraph copy = (Paragraph)defaultLi.CloneNode(true);
                            copy.Descendants <Text>().Where(t => t.Text == "lang").Single().Text  = language.Name;
                            copy.Descendants <Text>().Where(t => t.Text == "level").Single().Text = language.Level;
                            contentRun.Append(copy);
                        }
                        contentRun.RemoveChild(defaultLi);
                    }
                    else
                    {
                        RemoveCC(mainPart, "Section_Languages");
                    }

                    // ЛИЧНЫЕ КАЧЕСТВА
                    if (myResume.PersonalQualities.Count > 0)
                    {
                        SdtBlock        contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "PersonalQualities").Single();
                        SdtContentBlock contentRun     = contentControl.GetFirstChild <SdtContentBlock>();
                        Paragraph       defaultLi      = contentRun.GetFirstChild <Paragraph>();

                        foreach (var quality in myResume.PersonalQualities)
                        {
                            Paragraph copy = (Paragraph)defaultLi.CloneNode(true);
                            copy.Descendants <Text>().Where(t => t.Text == "quality").Single().Text = quality.Name;
                            contentRun.Append(copy);
                        }
                        contentRun.RemoveChild(defaultLi);
                    }
                    else
                    {
                        mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_PersonalQualities").Single().Remove();
                    }

                    // НАВЫКИ
                    if (myResume.Skills.Count > 0)
                    {
                        SdtBlock        contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Skills").Single();
                        SdtContentBlock contentRun     = contentControl.GetFirstChild <SdtContentBlock>();
                        Paragraph       defaultLi      = contentRun.GetFirstChild <Paragraph>();

                        foreach (var skill in myResume.Skills)
                        {
                            Paragraph copy = (Paragraph)defaultLi.CloneNode(true);
                            copy.Descendants <Text>().Where(t => t.Text == "skill").Single().Text = skill.Name;
                            contentRun.Append(copy);
                        }
                        contentRun.RemoveChild(defaultLi);
                    }
                    else
                    {
                        mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Skills").Single().Remove();
                    }

                    mainPart.Document.Save();
                }
                File.WriteAllBytes(outFilePath, templateStream.ToArray());
            }
        }
Exemplo n.º 9
0
        private void FillTables(WordprocessingDocument document, DocTable[] tables)
        {
            // get WORD tables
            Table[] originalTables = document.MainDocumentPart.Document.Body.Elements <Table>().ToArray();

            for (int i = 0; i < tables.Length; i++)
            {
                var clientTable = tables[i];

                Table table = originalTables[i];

                TableRow firstRow = table.Elements <TableRow>().ElementAt(0);

                // проход по всем строкам xml таблицы
                foreach (var tr in clientTable.Rows)
                {
                    TableRow newRow = firstRow.CloneRow();
                    var      cells  = tr.Cells;

                    int j = 0;
                    foreach (var td in cells)
                    {
                        if (td == "-")
                        {
                            TableCell firstNewCell = newRow.Elements <TableCell>().First();
                            TableCell toDelCell    = newRow.Elements <TableCell>().ToList()[1];
                            toDelCell.Remove();
                            GridSpan gs = new GridSpan();
                            // TODO: think about skip parameter
                            int countToSkip = cells.Count(x => x == "-") + 1;
                            gs.Val = countToSkip;
                            firstNewCell.TableCellProperties.Append(gs);
                        }
                        else
                        {
                            TableCell newCell = newRow.Elements <TableCell>().ElementAt(j);

                            Text textCop = newCell.Elements <Paragraph>().First().Elements <Run>().First().Elements <Text>().First();

                            // clear all paragraphs
                            foreach (var paragraph in newCell.Elements <Paragraph>())
                            {
                                foreach (var currun in paragraph.Elements <Run>())
                                {
                                    foreach (var curText in currun.Elements <Text>())
                                    {
                                        curText.Remove();
                                    }
                                }
                            }

                            newCell.Elements <Paragraph>().First().Elements <Run>().First().AppendChild(textCop);

                            Paragraph par  = newCell.Elements <Paragraph>().First();
                            Run       run  = par.Elements <Run>().First();
                            Text      text = run.Elements <Text>().First();
                            text.Text = td;

                            j++;
                        }
                    }
                    table.AppendChild(newRow);
                }
            }
        }
Exemplo n.º 10
0
        public string DAIRCellTextGetter(TableCell cell)
        {
            string text = cell.InnerText.Trim();

            if (text.Contains("FORMDROPDOWN"))
            {
                bool containsYes = text.IndexOf("yes", StringComparison.OrdinalIgnoreCase) >= 0;
                bool containsNo  = text.IndexOf("no", StringComparison.OrdinalIgnoreCase) >= 0;
                if (containsYes)
                {
                    return("YES");
                }
                else if (containsNo)
                {
                    return("NO");
                }
                else if (text.Length > 12)
                {
                    string formText = "";
                    int    index    = text.IndexOf("FORMDROPDOWN");
                    if (index != -1)
                    {
                        formText = garbageCollector(text, "FORMDROPDOWN");
                    }
                    return(formText);
                }
                else
                {
                    DropDownListFormField dropdown = cell.Elements <Paragraph>().First().Elements <Run>().First().Elements <FieldChar>().First().Elements <FormFieldData>().First().Elements <DropDownListFormField>().First();
                    var ddls = dropdown.DropDownListSelection;
                    if (ddls == null)
                    {
                        return("(empty)");
                    }
                    else
                    {
                        int selectedIndex               = dropdown.DropDownListSelection.Val;
                        ListEntryFormField selected     = dropdown.Elements <ListEntryFormField>().ElementAt(selectedIndex);
                        string             selectedText = selected.Val;
                        return(selectedText);
                    }
                }
            }

            else if (text.Contains("FORMTEXT"))
            {
                string cellText = "(empty)";
                if (text.Length > 8)
                {
                    int index = text.IndexOf("FORMTEXT");
                    if (index != -1)
                    {
                        cellText = garbageCollector(text, "FORMTEXT");
                    }
                }
                return(cellText);
            }
            else
            {
                return(cell.InnerText);
            }

            // gets rid of unwanted text in a string and returns the concatenated substrings
        }
Exemplo n.º 11
0
 public SmartParagraph(TableCell cell)
 {
     Paragraph = cell.Elements <Paragraph>().First();
 }