Ejemplo n.º 1
0
        private void CreateParts(WordprocessingDocument document)
        {
            DocxBase.CurrentTitle = DocxServiceProvinceRes.Title;

            ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart <ExtendedFilePropertiesPart>("rId3");

            DocxBase.GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1);

            MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart();

            GenerateMainDocumentPart1Content(mainDocumentPart1);

            FontTablePart fontTablePart1 = mainDocumentPart1.AddNewPart <FontTablePart>("rId13");

            DocxBase.GenerateFontTablePart1Content(fontTablePart1);

            StyleDefinitionsPart styleDefinitionsPart1 = mainDocumentPart1.AddNewPart <StyleDefinitionsPart>("rId3");

            DocxBase.GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1);

            EndnotesPart endnotesPart1 = mainDocumentPart1.AddNewPart <EndnotesPart>("rId7");

            DocxBase.GenerateEndnotesPart1Content(endnotesPart1);

            FooterPart footerPart1 = mainDocumentPart1.AddNewPart <FooterPart>("rId12");

            DocxBase.GenerateFooterPart1Content(footerPart1);

            NumberingDefinitionsPart numberingDefinitionsPart1 = mainDocumentPart1.AddNewPart <NumberingDefinitionsPart>("rId2");

            DocxBase.GenerateNumberingDefinitionsPart1Content(numberingDefinitionsPart1);

            CustomXmlPart customXmlPart1 = mainDocumentPart1.AddNewPart <CustomXmlPart>("application/xml", "rId1");

            DocxBase.GenerateCustomXmlPart1Content(customXmlPart1);

            CustomXmlPropertiesPart customXmlPropertiesPart1 = customXmlPart1.AddNewPart <CustomXmlPropertiesPart>("rId1");

            DocxBase.GenerateCustomXmlPropertiesPart1Content(customXmlPropertiesPart1);

            FootnotesPart footnotesPart1 = mainDocumentPart1.AddNewPart <FootnotesPart>("rId6");

            DocxBase.GenerateFootnotesPart1Content(footnotesPart1);

            HeaderPart headerPart1 = mainDocumentPart1.AddNewPart <HeaderPart>("rId11");

            DocxBase.GenerateHeaderPart1Content(headerPart1);

            WebSettingsPart webSettingsPart1 = mainDocumentPart1.AddNewPart <WebSettingsPart>("rId5");

            DocxBase.GenerateWebSettingsPart1Content(webSettingsPart1);

            //ChartPart chartPart1 = mainDocumentPart1.AddNewPart<ChartPart>("rId10");
            //DocxBase.GenerateChartPart1Content(chartPart1);

            //EmbeddedPackagePart embeddedPackagePart1 = chartPart1.AddNewPart<EmbeddedPackagePart>("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "rId3");
            //DocxBase.GenerateEmbeddedPackagePart1Content(embeddedPackagePart1);

            //ChartColorStylePart chartColorStylePart1 = chartPart1.AddNewPart<ChartColorStylePart>("rId2");
            //DocxBase.GenerateChartColorStylePart1Content(chartColorStylePart1);

            //ChartStylePart chartStylePart1 = chartPart1.AddNewPart<ChartStylePart>("rId1");
            //DocxBase.GenerateChartStylePart1Content(chartStylePart1);

            DocumentSettingsPart documentSettingsPart1 = mainDocumentPart1.AddNewPart <DocumentSettingsPart>("rId4");

            DocxBase.GenerateDocumentSettingsPart1Content(documentSettingsPart1);

            //ChartPart chartPart2 = mainDocumentPart1.AddNewPart<ChartPart>("rId9");
            //DocxBase.GenerateChartPart2Content(chartPart2);

            //EmbeddedPackagePart embeddedPackagePart2 = chartPart2.AddNewPart<EmbeddedPackagePart>("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "rId3");
            //DocxBase.GenerateEmbeddedPackagePart2Content(embeddedPackagePart2);

            //ChartColorStylePart chartColorStylePart2 = chartPart2.AddNewPart<ChartColorStylePart>("rId2");
            //DocxBase.GenerateChartColorStylePart2Content(chartColorStylePart2);

            //ChartStylePart chartStylePart2 = chartPart2.AddNewPart<ChartStylePart>("rId1");
            //DocxBase.GenerateChartStylePart2Content(chartStylePart2);

            ThemePart themePart1 = mainDocumentPart1.AddNewPart <ThemePart>("rId14");

            DocxBase.GenerateThemePart1Content(themePart1);

            foreach (UsedHyperlink usedHyperlink in DocxBase.UsedHyperlinkList)
            {
                mainDocumentPart1.AddHyperlinkRelationship(new System.Uri(usedHyperlink.URL, System.UriKind.Absolute), true, usedHyperlink.Id.ToString());
            }

            DocxBase.SetPackageProperties(document);
        }
Ejemplo n.º 2
0
        public void CreateWordprocessingDocument(string filepath, string title, List <string> conversation)
        {
            // Create a document by supplying the filepath.
            using (WordprocessingDocument wordDocument =
                       WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                // Add a main document part.
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
                AddSettingsToMainDocumentPart(mainPart);

                // Create the document structure and add some text.
                Document doc = new Document();

                HeaderPart headerPart = mainPart.AddNewPart <HeaderPart>("rId7");
                GenerateHeader(headerPart);

                Body body = new Body();
                // 1 paragrafo
                Paragraph para = new Paragraph();

                ParagraphProperties paragraphProperties1 = new ParagraphProperties();
                ParagraphStyleId    paragraphStyleId1    = new ParagraphStyleId()
                {
                    Val = "Bold"
                };
                Justification justification1 = new Justification()
                {
                    Val = JustificationValues.Center
                };
                ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();

                paragraphProperties1.Append(paragraphStyleId1);
                //paragraphProperties1.Append(fontSize1);
                paragraphProperties1.Append(justification1);
                paragraphProperties1.Append(paragraphMarkRunProperties1);

                Run           run            = new Run();
                RunProperties runProperties1 = new RunProperties(new FontSize()
                {
                    Val = "50"
                }, new Bold()
                {
                    Val = OnOffValue.FromBoolean(true)
                });

                Text text = new Text()
                {
                    Text = title
                };

                // siga a ordem
                run.Append(runProperties1);
                run.Append(text);
                para.Append(paragraphProperties1);
                para.Append(run);
                body.Append(para);
                //Paragraph titlePara = CreateParagraph( title, JustificationValues.Center);
                //body.Append(titlePara);

                // "Here are the discussed points:" Paragraph
                Paragraph pointsHeaderPara = CreateParagraph("Here are the discussed points:", JustificationValues.Left);

                body.Append(pointsHeaderPara);

                foreach (var line in conversation)
                {
                    Paragraph paragraph1 = CreateParagraphForBullets(line, wordDocument);
                    body.Append(paragraph1);
                }

                doc.Append(body);

                wordDocument.MainDocumentPart.Document = doc;

                wordDocument.Close();
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Add a note to the FootNotes part and ensure it exists.
        /// </summary>
        /// <param name="description">The description of an acronym, abbreviation, some book references, ...</param>
        /// <returns>Returns the id of the footnote reference.</returns>
        private int AddFootnoteReference(string description)
        {
            FootnotesPart fpart = mainPart.FootnotesPart;

            if (fpart == null)
            {
                fpart = mainPart.AddNewPart <FootnotesPart>();
            }

            if (fpart.Footnotes == null)
            {
                // Insert a new Footnotes reference
                new Footnotes(
                    new Footnote(
                        new Paragraph(
                            new ParagraphProperties {
                    SpacingBetweenLines = new SpacingBetweenLines()
                    {
                        After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto
                    }
                },
                            new Run(
                                new SeparatorMark())
                            )
                        )
                {
                    Type = FootnoteEndnoteValues.Separator, Id = -1
                },
                    new Footnote(
                        new Paragraph(
                            new ParagraphProperties {
                    SpacingBetweenLines = new SpacingBetweenLines()
                    {
                        After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto
                    }
                },
                            new Run(
                                new ContinuationSeparatorMark())
                            )
                        )
                {
                    Type = FootnoteEndnoteValues.ContinuationSeparator, Id = 0
                }).Save(fpart);
                footnotesRef = 1;
            }
            else
            {
                // The footnotesRef Id is a required field and should be unique. You can assign yourself some hard-coded
                // value but that's absolutely not safe. We will loop through the existing Footnote
                // to retrieve the highest Id.
                foreach (var fn in fpart.Footnotes.Elements <Footnote>())
                {
                    if (fn.Id.HasValue && fn.Id > footnotesRef)
                    {
                        footnotesRef = (int)fn.Id.Value;
                    }
                }
                footnotesRef++;
            }


            Paragraph p;

            fpart.Footnotes.Append(
                new Footnote(
                    p = new Paragraph(
                        new ParagraphProperties {
                ParagraphStyleId = new ParagraphStyleId()
                {
                    Val = htmlStyles.GetStyle(htmlStyles.DefaultStyles.FootnoteTextStyle, StyleValues.Paragraph)
                }
            },
                        new Run(
                            new RunProperties {
                RunStyle = new RunStyle()
                {
                    Val = htmlStyles.GetStyle(htmlStyles.DefaultStyles.FootnoteReferenceStyle, StyleValues.Character)
                }
            },
                            new FootnoteReferenceMark()),
                        new Run(
                            // Word insert automatically a space before the definition to separate the
                            // reference number with its description
                            new Text(" ")
            {
                Space = SpaceProcessingModeValues.Preserve
            })
                        )
                    )
            {
                Id = footnotesRef
            });


            // Description in footnote reference can be plain text or a web protocols/file share (like \\server01)
            Uri   uriReference;
            Regex linkRegex = new Regex(@"^((https?|ftps?|mailto|file)://|[\\]{2})(?:[\w][\w.-]?)");

            if (linkRegex.IsMatch(description) && Uri.TryCreate(description, UriKind.Absolute, out uriReference))
            {
                // when URI references a network server (ex: \\server01), System.IO.Packaging is not resolving the correct URI and this leads
                // to a bad-formed XML not recognized by Word. To enforce the "original URI", a fresh new instance must be created
                uriReference = new Uri(uriReference.AbsoluteUri, UriKind.Absolute);
                HyperlinkRelationship extLink = fpart.AddHyperlinkRelationship(uriReference, true);
                var h = new Hyperlink(
                    )
                {
                    History = true, Id = extLink.Id
                };

                h.Append(new Run(
                             new RunProperties {
                    RunStyle = new RunStyle()
                    {
                        Val = htmlStyles.GetStyle(htmlStyles.DefaultStyles.HyperlinkStyle, StyleValues.Character)
                    }
                },
                             new Text(description)));
                p.Append(h);
            }
            else
            {
                p.Append(new Run(
                             new Text(description)
                {
                    Space = SpaceProcessingModeValues.Preserve
                }));
            }

            fpart.Footnotes.Save();

            return(footnotesRef);
        }
Ejemplo n.º 4
0
        public static void CreateDoc(string docName)
        {
            // Create a Wordprocessing document.
            using (WordprocessingDocument myDoc = WordprocessingDocument.Create(docName, WordprocessingDocumentType.Document))
            {
                // Add a new main document part.
                MainDocumentPart mainPart = myDoc.AddMainDocumentPart();

                HeaderPart headerPart = mainPart.AddNewPart <HeaderPart>();
                FooterPart footerPart = mainPart.AddNewPart <FooterPart>();


                //Create DOM tree for simple document.
                mainPart.Document = new Document();
                Body body = new Body();
                mainPart.Document.Append(body);

                //Add Table

                Table table = new Table();

                TableProperties props = new TableProperties(
                    new TableWidth()
                {
                    Width = "100%", Type = TableWidthUnitValues.Auto
                },

                    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 = 8
                },
                        new InsideVerticalBorder
                {
                    Val  = new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 8
                }));
                props.BiDiVisual = new BiDiVisual();

                table.AppendChild <TableProperties>(props);

                var headerRow = new TableRow();

                var bgColor = "#cccccc";

                //var data = GetData();


                headerRow.Append(CreateTableCell("م", bgColor, JustificationValues.Center, "5%"));
                headerRow.Append(CreateTableCell("الإسم", bgColor, JustificationValues.Center, "20%"));
                headerRow.Append(CreateTableCell("الوظيفة", bgColor, JustificationValues.Center, "45%"));

                var cell4 = CreateTableCell("الملاحظات", bgColor, JustificationValues.Center);

                TableCellProperties tableCellProperties = new TableCellProperties()
                {
                    TableCellVerticalAlignment = new TableCellVerticalAlignment {
                        Val = TableVerticalAlignmentValues.Center
                    },
                    HorizontalMerge = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Restart
                    }
                };

                cell4.Append(tableCellProperties);
                headerRow.Append(cell4);

                var cell5 = CreateTableCell("");
                cell5.Append(new TableCellProperties {
                    HorizontalMerge = new HorizontalMerge {
                        Val = MergedCellValues.Continue
                    }
                });
                headerRow.Append(cell5);


                headerRow.TableRowProperties = new TableRowProperties();
                headerRow.TableRowProperties.AppendChild(new TableHeader());

                table.Append(headerRow);

                // add cheif and supervisor
                var row2 = new TableRow();

                row2.Append(CreateTableCell("1", "", JustificationValues.Center));
                var c1 = CreateTableCell("رئيس اللجنة", bgColor, JustificationValues.Left, "", "Arial", "14pt", true, true);
                c1.Append(CreateParagraph("محمد"));
                row2.Append(c1);

                row2.Append(CreateTableCell("ابراهيم"));
                row2.Append(CreateTableCell("إستلام وإمتحان"));
                row2.Append(CreateTableCell("تقدير الدرجات"));
                table.Append(row2);

                var row3 = new TableRow();

                row3.Append(CreateTableCell("1", "", JustificationValues.Center));
                var c2 = CreateTableCell("المراقب الأول", bgColor, JustificationValues.Left, "", "Arial", "14pt", true, true);
                c2.Append(CreateParagraph(""));
                row3.Append(c2);
                row3.Append(CreateTableCell(""));
                row3.Append(CreateTableCell("إستلام وإمتحان"));
                row3.Append(CreateTableCell("تقدير الدرجات"));
                table.Append(row3);

                for (var i = 0; i < 80; i++)
                {
                    var tr = new TableRow();
                    for (var j = 0; j < 5; j++)
                    {
                        var tc = new TableCell();

                        //tc.Append(new Paragraph(new Run(new Text(string.Format("cell {0}, {1}", i, j)))));
                        tc.Append(CreateParagraph($"{i}, {j}", JustificationValues.Center));
                        // Assume you want columns that are automatically sized.
                        tc.Append(new TableCellProperties(
                                      new TableCellWidth {
                            Type = TableWidthUnitValues.Auto
                        }
                                      , new TableCellMargin {
                            StartMargin = new StartMargin {
                                Width = "10pt"
                            }
                        }));

                        tr.Append(tc);
                    }
                    table.Append(tr);
                }

                var row = table.GetFirstChild <TableRow>();



                mainPart.Document.Append(table);

                ApplyHeader(myDoc);
                ApplyFooter(myDoc);
                // Save changes to the main document part.
                mainPart.Document.Save();
            }
        }
        /// <summary>
        /// Aggiunge gli stili.
        /// </summary>
        /// <param>Definisce tutt e le caratteristiche dello stile.</param>
        /// <returns>Lo stile.</returns>
        public static RunProperties AddStyle(MainDocumentPart mainPart, bool isBold = false, bool isItalic = false, bool isUnderline = false, bool isOnlyRun = false, string styleId = "00", string styleName = "Default", string fontName = "Calibri", int fontSize = 12, string rgbColor = "000000", UnderlineValues underline = UnderlineValues.Single)
        {
            RunProperties rPr   = new RunProperties();
            Color         color = new Color()
            {
                Val = rgbColor
            };
            RunFonts rFont = new RunFonts();

            rFont.Ascii = fontName;
            rPr.Append(color);
            rPr.Append(rFont);
            if (isBold)
            {
                rPr.Append(new Bold());
            }
            if (isItalic)
            {
                rPr.Append(new Italic());
            }
            if (isUnderline)
            {
                rPr.Append(new Underline()
                {
                    Val = underline
                });
            }
            rPr.Append(new FontSize()
            {
                Val = (fontSize * 2).ToString()
            });
            if (!isOnlyRun)
            {
                Style style = new Style();
                style.StyleId = styleId;
                if (styleName == null || styleName.Length == 0)
                {
                    styleName = styleId;
                }
                style.Append(new Name()
                {
                    Val = styleName
                });
                style.Append(rPr);

                StyleDefinitionsPart stylePart;
                if (mainPart.StyleDefinitionsPart == null)
                {
                    stylePart        = mainPart.AddNewPart <StyleDefinitionsPart>();
                    stylePart.Styles = new Styles();
                }
                else
                {
                    stylePart = mainPart.StyleDefinitionsPart;
                }

                stylePart.Styles.Append(style);
                stylePart.Styles.Save();
            }
            return(rPr);
        }
Ejemplo n.º 6
0
        public static void AddStyle(MainDocumentPart mainPart, bool isBold = false, bool isItalic = false, bool isUnderline = false, string styleId = "00", string styleName = "Default", string fontName = "Calibri", int fontSize = 12, string rgbColor = "000000")
        {
            // we have to set the properties
            RunProperties rPr   = new RunProperties();
            Color         color = new Color()
            {
                Val = rgbColor
            };
            RunFonts rFont = new RunFonts();

            rFont.Ascii = fontName;
            rPr.Append(color);
            rPr.Append(rFont);
            if (isBold)
            {
                rPr.Append(new Bold());
            }
            if (isItalic)
            {
                rPr.Append(new Italic());
            }
            if (isUnderline)
            {
                rPr.Append(new Underline()
                {
                    Val = UnderlineValues.Single
                });
            }
            rPr.Append(new FontSize()
            {
                Val = (fontSize * 2).ToString()
            });

            Style style = new Style();

            style.StyleId = styleId;
            if (styleName == null || styleName.Length == 0)
            {
                styleName = styleId;
            }
            style.Append(new Name()
            {
                Val = styleName
            });
            style.Append(rPr); //we are adding properties previously defined

            // we have to add style that we have created to the StylePart
            StyleDefinitionsPart stylePart;

            if (mainPart.StyleDefinitionsPart == null)
            {
                stylePart        = mainPart.AddNewPart <StyleDefinitionsPart>();
                stylePart.Styles = new Styles();
            }
            else
            {
                stylePart = mainPart.StyleDefinitionsPart;
            }

            stylePart.Styles.Append(style);
            stylePart.Styles.Save(); // we save the style part
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Add a note to the FootNotes part and ensure it exists.
        /// </summary>
        /// <param name="description">The description of an acronym, abbreviation, some book references, ...</param>
        /// <returns>Returns the id of the footnote reference.</returns>
        private int AddFootnoteReference(string description)
        {
            FootnotesPart fpart = mainPart.FootnotesPart;

            if (fpart == null)
            {
                fpart = mainPart.AddNewPart <FootnotesPart>();
            }

            if (fpart.Footnotes == null)
            {
                // Insert a new Footnotes reference
                new Footnotes(
                    new Footnote(
                        new Paragraph(
                            new ParagraphProperties {
                    SpacingBetweenLines = new SpacingBetweenLines()
                    {
                        After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto
                    }
                },
                            new Run(
                                new SeparatorMark())
                            )
                        )
                {
                    Type = FootnoteEndnoteValues.Separator, Id = -1
                },
                    new Footnote(
                        new Paragraph(
                            new ParagraphProperties {
                    SpacingBetweenLines = new SpacingBetweenLines()
                    {
                        After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto
                    }
                },
                            new Run(
                                new ContinuationSeparatorMark())
                            )
                        )
                {
                    Type = FootnoteEndnoteValues.ContinuationSeparator, Id = 0
                }).Save(fpart);
                footnotesRef = 1;
            }
            else
            {
                // The footnotesRef Id is a required field and should be unique. You can assign yourself some hard-coded
                // value but that's absolutely not safe. We will loop through the existing Footnote
                // to retrieve the highest Id.
                foreach (var fn in fpart.Footnotes.Elements <Footnote>())
                {
                    if (fn.Id.HasValue && fn.Id > footnotesRef)
                    {
                        footnotesRef = (int)fn.Id.Value;
                    }
                }
                footnotesRef++;
            }


            Run       markerRun;
            Paragraph p;

            fpart.Footnotes.Append(
                new Footnote(
                    p = new Paragraph(
                        new ParagraphProperties {
                ParagraphStyleId = new ParagraphStyleId()
                {
                    Val = htmlStyles.GetStyle("footnote text", StyleValues.Paragraph)
                }
            },
                        markerRun = new Run(
                            new RunProperties {
                RunStyle = new RunStyle()
                {
                    Val = htmlStyles.GetStyle("footnote reference", StyleValues.Character)
                }
            },
                            new FootnoteReferenceMark()),
                        new Run(
                            // Word insert automatically a space before the definition to separate the
                            // reference number with its description
                            new Text(" ")
            {
                Space = SpaceProcessingModeValues.Preserve
            })
                        )
                    )
            {
                Id = footnotesRef
            });


            // Description in footnote reference can be plain text or a web protocols/file share (like \\server01)
            Uri   uriReference;
            Regex linkRegex = new Regex(@"^((https?|ftps?|mailto|file)://|[\\]{2})(?:[\w][\w.-]?)");

            if (linkRegex.IsMatch(description) && Uri.TryCreate(description, UriKind.Absolute, out uriReference))
            {
                HyperlinkRelationship extLink = fpart.AddHyperlinkRelationship(uriReference, true);
                var h = new Hyperlink(
                    )
                {
                    History = true, Id = extLink.Id
                };

                htmlStyles.EnsureKnownStyle(HtmlDocumentStyle.KnownStyles.Hyperlink);

                h.Append(new Run(
                             new RunProperties {
                    RunStyle = new RunStyle()
                    {
                        Val = htmlStyles.GetStyle("Hyperlink", StyleValues.Character)
                    }
                },
                             new Text(description)));
                p.Append(h);
            }
            else
            {
                p.Append(new Run(
                             new Text(description)
                {
                    Space = SpaceProcessingModeValues.Preserve
                }));
            }


            if (!htmlStyles.DoesStyleExists("footnote reference"))
            {
                // Force the superscript style because if the footnote text style does not exists,
                // the rendering will be awful.
                markerRun.InsertInProperties(prop =>
                                             prop.VerticalTextAlignment = new VerticalTextAlignment()
                {
                    Val = VerticalPositionValues.Superscript
                });
            }
            fpart.Footnotes.Save();

            return(footnotesRef);
        }
        public string Post([FromBody] Models.Presentation.AgendaPostModel agenda)
        {
            string filePath = @"\\844dc2\Residential Incidents\";
            string fileName = string.Format("{0}{1}.docx", filePath, agenda.agendaTitle);

            //MemoryStream documentStream = new MemoryStream();


            using (WordprocessingDocument agendaDocument = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
            //using (WordprocessingDocument agendaDocument = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document))
            {
                var reports = from r in this._db.IncidentReports
                              join u in this._db.Users
                              on r.userId equals u.userId
                              join p in this._db.IncidentPrograms
                              on r.programId equals p.incidentProgramId
                              join s in this._db.ReportStatuses
                              on r.statusId equals s.reportStatusId
                              from d in this._db.IncidentDetails.Where(d => d.incidentId == r.incidentId).DefaultIfEmpty()
                              where r.incidentReportTypeId == 1 &&
                              r.incidentDate >= agenda.fromDate &&
                              r.incidentDate <= agenda.toDate
                              select new
                {
                    incidentId      = r.incidentId,
                    clientName      = r.clientName,
                    clientDob       = r.clientDob,
                    programTitle    = p.programTitle,
                    reportingAgency = r.reportingAgency,
                    incidentDate    = r.incidentDate,
                    createdStamp    = r.createdStamp,
                    lastModified    = r.lastModified,
                    createdByName   = u.firstName + " " + u.lastName,
                    statusId        = r.statusId,
                    currentStatus   = s.reportStatusText,
                    incidentDetails = d.incidentDetails,
                    staffs          = (
                        from st in this._db.IncidentStaffs
                        join e in this._db.Users
                        on st.userId equals e.userId
                        where st.incidentId == r.incidentId
                        select new
                    {
                        staffName = e.firstName + " " + e.lastName
                    }
                        )
                };



                MainDocumentPart root = agendaDocument.AddMainDocumentPart();

                root.Document = new Document();
                Body body = root.Document.AppendChild(new Body());


                // PAGE MARGINS
                SectionProperties sectionProperties = new SectionProperties();
                PageMargin        pageMargin        = new PageMargin()
                {
                    Top = 720, Right = (UInt32Value)720U, Bottom = 720, Left = (UInt32Value)720U, Header = (UInt32Value)720U, Footer = (UInt32Value)720U, Gutter = (UInt32Value)0U
                };
                sectionProperties.Append(pageMargin);
                root.Document.Body.Append(sectionProperties);

                // DOCUMENT STYLES
                StyleDefinitionsPart styleDefinitionsPart = root.AddNewPart <StyleDefinitionsPart>();
                Styles styles = new Styles();
                styles.Save(styleDefinitionsPart);

                Style style = new Style()
                {
                    Type        = StyleValues.Paragraph,
                    StyleId     = "AgendaStyle",
                    CustomStyle = true
                };
                StyleName styleHeading1 = new StyleName()
                {
                    Val = "Heading1"
                };
                style.Append(styleHeading1);
                StyleRunProperties styleRunPropertiesHeading1 = new StyleRunProperties();
                styleRunPropertiesHeading1.Append(new Bold());
                styleRunPropertiesHeading1.Append(new RunFonts()
                {
                    Ascii = "Calibri"
                });
                styleRunPropertiesHeading1.Append(new FontSize()
                {
                    Val = "24"
                });                                                                // Sizes are in half-points. Oy!
                style.Append(styleRunPropertiesHeading1);
                styles.Append(style);


                foreach (var report in reports)
                {
                    //Paragraph para = body.AppendChild(new Paragraph());
                    //Run run = para.AppendChild(new Run());

                    // CLIENT NAME HEADER
                    Paragraph clientNamePara = body.AppendChild(new Paragraph());
                    clientNamePara.AppendChild(new Run(new Text(report.clientName)));
                    clientNamePara.ParagraphProperties = new ParagraphProperties(new ParagraphStyleId()
                    {
                        Val = "Heading1"
                    });


                    // REPORT DETAILS
                    Paragraph infoPara = body.AppendChild(new Paragraph());
                    Run       infoRun  = infoPara.AppendChild(new Run());

                    infoRun.AppendChild(new Text(string.Format("Program: {0}", report.programTitle)));
                    infoRun.AppendChild(new Break());
                    infoRun.AppendChild(new Text(string.Format("Reporting Agency: {0}", report.reportingAgency)));
                    infoRun.AppendChild(new Break());
                    infoRun.AppendChild(new Text(string.Format("Date of Incident: {0}", report.incidentDate.ToShortDateString())));
                    infoRun.AppendChild(new Break());
                    infoRun.AppendChild(new Text(string.Format("Staff: {0}", report.createdByName)));


                    // INCIDENT DETAILS
                    Paragraph detailsPara = body.AppendChild(new Paragraph());
                    Run       detailsRun  = detailsPara.AppendChild(new Run());

                    detailsRun.AppendChild(new Text("Details of Incident: "));
                    detailsRun.AppendChild(new Break());

                    if (report.incidentDetails == string.Empty)
                    {
                        detailsRun.AppendChild(new Text("<No details given.  Report incomplete.>"));
                    }
                    else
                    {
                        detailsRun.AppendChild(new Text(report.incidentDetails));
                    }



                    // ADDITIONAL STAFF INVOLVED
                    Paragraph staffPara = body.AppendChild(new Paragraph());
                    Run       staffRun  = staffPara.AppendChild(new Run());

                    staffRun.AppendChild(new Text("Additional Staff Involved:"));
                    staffRun.AppendChild(new Break());


                    if (report.staffs.ToList().Any())
                    {
                        foreach (var staff in report.staffs)
                        {
                            staffRun.AppendChild(new Text(staff.staffName));
                            staffRun.AppendChild(new Break());
                        }
                    }
                    else
                    {
                        staffRun.AppendChild(new Text("No additional staff identified."));
                        staffRun.AppendChild(new Break());
                    }



                    // ACTIONS TAKEN
                    Paragraph actionsPara = body.AppendChild(new Paragraph());
                    Run       actionsRun  = actionsPara.AppendChild(new Run(new Text("Actions Taken")));


                    // PATTERNS
                    Paragraph patternsPara = body.AppendChild(new Paragraph());
                    Run       patternsRun  = patternsPara.AppendChild(new Run(new Text("Pattern Behavior/Recommendation")));



                    // PAGE BREAK
                    body.AppendChild(new Paragraph(
                                         new Run(
                                             new Break()
                    {
                        Type = BreakValues.Page
                    })));
                }

                //run.AppendChild(new Text("From Date: " + agenda.fromDate.ToShortDateString() + " to "  + agenda.toDate.ToShortDateString()));
            }


            SessionController session = new SessionController();

            var user = session.Get();

            session.Dispose();

            FileStream documentStream = new FileStream(fileName, FileMode.Open);


            MailMessage msg = new MailMessage();

            msg.To.Add(new MailAddress(user.userEmail));
            //msg.Bcc.Add(new MailAddress("*****@*****.**"));
            msg.From       = new MailAddress("*****@*****.**");
            msg.Subject    = "CFS Incident Reports: Agenda Document";
            msg.IsBodyHtml = true;


            msg.Attachments.Add(new System.Net.Mail.Attachment(documentStream, agenda.agendaTitle + ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"));

            StringBuilder messageBody = new StringBuilder();

            messageBody.Append("<h1>Incident Reports Agenda</h1>");
            messageBody.Append("<p>An agenda document has been created and is attached.</p>");
            messageBody.Append("<p>A copy has been saved <a href=\"\\\\844dc2\\Residential Incidents\\\">here</a>.</p>");

            msg.Body = messageBody.ToString();

            SmtpClient smtp = new SmtpClient("cfs-mailserv");

            smtp.Send(msg);


            smtp.Dispose();
            msg.Dispose();

            documentStream.Close();
            documentStream.Dispose();

            return(fileName);
        }
Ejemplo n.º 9
0
        private static void AddNewTask(MainDocumentPart mdp, string title, User assignee, User assigner)
        {
            mdp.AddNewPart <DocumentTasksPart>();

            DocumentTasksPart taskPart = mdp.DocumentTasksPart;

            taskPart.Tasks = new Tasks();
            Tasks  taskRoot       = taskPart.Tasks;
            string guidEventId    = Guid.NewGuid().ToString();
            string guidTaskId     = Guid.NewGuid().ToString();
            string commonAnchorId = "546836446";

            taskRoot.AppendChild <Task>(
                new Task(
                    new TaskAnchor(
                        new CommentAnchor()
            {
                Id = commonAnchorId
            }),
                    new TaskHistory(
                        new TaskHistoryEvent(
                            new AttributionTaskUser()
            {
                UserId = assigner.UserId, UserProvider = assigner.DirectoryProvider, UserName = assigner.UserName
            },
                            new TaskAnchor(
                                new CommentAnchor()
            {
                Id = commonAnchorId
            }),
                            new TaskCreateEventInfo())
            {
                Id = guidEventId, Time = DateTime.Now
            },
                        new TaskHistoryEvent(
                            new AttributionTaskUser()
            {
                UserId = assigner.UserId, UserProvider = assigner.DirectoryProvider, UserName = assigner.UserName
            },
                            new TaskAnchor(
                                new CommentAnchor()
            {
                Id = commonAnchorId
            }),
                            new AssignTaskUser()
            {
                UserId = assignee.UserId, UserProvider = assignee.DirectoryProvider, UserName = assignee.UserName
            })
            {
                Id = guidEventId, Time = DateTime.Now
            },
                        new TaskHistoryEvent(
                            new AttributionTaskUser()
            {
                UserId = assigner.UserId, UserProvider = assigner.DirectoryProvider, UserName = assigner.UserName
            },
                            new TaskAnchor(
                                new CommentAnchor()
            {
                Id = commonAnchorId
            }),
                            new TaskTitleEventInfo()
            {
                Title = title
            })
            {
                Id = guidEventId, Time = DateTime.Now
            }))
            {
                Id = guidTaskId
            });
        }
Ejemplo n.º 10
0
    public void ProcessRequest(System.Data.DataTable dt, string docFileName)
    {
        {
            using (MemoryStream mem = new MemoryStream())
            {
                using (WordprocessingDocument doc = WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
                {
                    MainDocumentPart     mainPart  = doc.AddMainDocumentPart();
                    StyleDefinitionsPart stylePart = mainPart.AddNewPart <StyleDefinitionsPart>();

                    RunProperties rPrNormal = new RunProperties();
                    RunFonts      rFont1    = new RunFonts();
                    rPrNormal.Append(new DocumentFormat.OpenXml.Wordprocessing.FontSize()
                    {
                        Val = "24"
                    });
                    DocumentFormat.OpenXml.Wordprocessing.Style style1 = new DocumentFormat.OpenXml.Wordprocessing.Style();
                    style1.StyleId = "myText";
                    style1.Append(new Name()
                    {
                        Val = "text"
                    });
                    style1.Append(rPrNormal);
                    stylePart.Styles = new Styles();
                    stylePart.Styles.Append(style1);

                    RunProperties rPr   = new RunProperties();
                    Color         color = new Color()
                    {
                        Val = "FF0000"
                    };
                    RunFonts rFont = new RunFonts();
                    //rFont.Ascii = "Times New Roman";
                    //rPr.Append(color);
                    //rPr.Append(rFont);
                    rPr.Append(new Bold());
                    rPr.Append(new DocumentFormat.OpenXml.Wordprocessing.FontSize()
                    {
                        Val = "24"
                    });
                    DocumentFormat.OpenXml.Wordprocessing.Style style = new DocumentFormat.OpenXml.Wordprocessing.Style();
                    style.StyleId = "myHeading1";
                    style.Append(new Name()
                    {
                        Val = "My Heading 1"
                    });
                    style.Append(new NextParagraphStyle()
                    {
                        Val = "Normal"
                    });
                    style.Append(rPr);
                    stylePart.Styles = new Styles();
                    stylePart.Styles.Append(style);
                    stylePart.Styles.Save();

                    mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();

                    Body body = mainPart.Document.AppendChild(new Body());


                    ParagraphProperties pptemp        = new ParagraphProperties();
                    Paragraph           template      = body.AppendChild(new Paragraph());
                    Justification       templatealign = new Justification()
                    {
                        Val = JustificationValues.Center
                    };
                    pptemp.Append(templatealign);
                    template.Append(pptemp);
                    Run runtemp = template.AppendChild(new Run());
                    if (dt.Rows[0][17].ToString() == "Annual")
                    {
                        runtemp.AppendChild(new Text("Template B"));
                    }
                    else if (dt.Rows[0][17].ToString() == "Upfront Payment")
                    {
                        runtemp.AppendChild(new Text("Template A"));
                    }
                    else if (dt.Rows[0][17].ToString() == "Royalty" && dt.Rows[0][8].ToString() != "&nbsp;")
                    {
                        runtemp.AppendChild(new Text("Template D2"));
                    }
                    else if (dt.Rows[0][17].ToString() == "Royalty" && dt.Rows[0][8].ToString() == "&nbsp;")
                    {
                        runtemp.AppendChild(new Text("Template D1"));
                    }

                    ParagraphProperties ppDate    = new ParagraphProperties();
                    Paragraph           paraDate  = body.AppendChild(new Paragraph());
                    Justification       dateAlign = new Justification()
                    {
                        Val = JustificationValues.Right
                    };
                    ppDate.Append(dateAlign);
                    paraDate.Append(ppDate);
                    Run runDate = paraDate.AppendChild(new Run());
                    runDate.AppendChild(new Text("Date : " + DateTime.Now.ToShortDateString()));

                    ParagraphProperties Normal_pPr = new ParagraphProperties(new ParagraphStyleId()
                    {
                        Val = "myText"
                    });

                    Paragraph paraTo = body.AppendChild(new Paragraph());
                    Run       runTo  = paraTo.AppendChild(new Run());
                    runTo.AppendChild(new Text("To"));
                    runTo.AppendChild(new Break());
                    runTo.AppendChild(new Break());
                    if (dt.Rows[0][8].ToString() != "&nbsp;")
                    {
                        runTo.AppendChild(new Text("Project Accounts"));
                        runTo.AppendChild(new Break());
                        runTo.AppendChild(new Text("ICSR"));
                    }
                    else
                    {
                        //Paragraph tocustdet = body.AppendChild(new Paragraph());
                        //Run runtodetails = tocustdet.AppendChild(new Run());
                        //Justification center1 = new Justification() { Val = JustificationValues.Center };
                        //runtodetails.AppendChild(center1);
                        runTo.AppendChild(new Text(dt.Rows[0][10].ToString()));
                        runTo.AppendChild(new Break());
                        runTo.AppendChild(new Text(dt.Rows[0][11].ToString()));
                        runTo.AppendChild(new Break());
                        runTo.AppendChild(new Text(dt.Rows[0][12].ToString()));
                        runTo.AppendChild(new Break());
                        runTo.AppendChild(new Text(dt.Rows[0][13].ToString()));
                        runTo.AppendChild(new Break());
                        runTo.AppendChild(new Text(dt.Rows[0][14].ToString()));
                        runTo.AppendChild(new Break());
                        runTo.AppendChild(new Text(dt.Rows[0][15].ToString()));
                        runTo.AppendChild(new Break());
                        runTo.AppendChild(new Text(dt.Rows[0][16].ToString()));
                    }
                    runTo.AppendChild(new Break());

                    Paragraph           paraTitle   = body.AppendChild(new Paragraph());
                    ParagraphProperties heading_pPr = new ParagraphProperties();
                    heading_pPr.ParagraphStyleId = new ParagraphStyleId()
                    {
                        Val = "myHeading1"
                    };
                    paraTitle.Append(heading_pPr);
                    Run           runTitle = paraTitle.AppendChild(new Run());
                    RunProperties rpTitle  = new RunProperties(new Underline()
                    {
                        Val = UnderlineValues.Single
                    });
                    runTitle.Append(rpTitle);
                    if ((dt.Rows[0][17].ToString() == "Upfront Payment" || dt.Rows[0][17].ToString() == "Annual") && dt.Rows[0][8].ToString() != "&nbsp;")
                    {
                        runTitle.AppendChild(new Text("Sub : Raising of Invoice"));
                    }
                    else if (dt.Rows[0][17].ToString() == "Royalty" && dt.Rows[0][8].ToString() == "&nbsp;")
                    {
                        runTitle.AppendChild(new Text("Sub : Royalty Dues : Declaration"));
                        Paragraph subdetail    = body.AppendChild(new Paragraph());
                        Run       runsubdetail = subdetail.AppendChild(new Run());
                        runsubdetail.AppendChild(new Text("Dear Sir / Madam,"));
                        runsubdetail.AppendChild(new Text("Reference Agreement as per details below a royalty payment is due."));
                    }
                    else if (dt.Rows[0][17].ToString() == "Royalty" && dt.Rows[0][8].ToString() != "&nbsp;")
                    {
                        runTitle.AppendChild(new Text("Sub : Raising of Invoice [Royalty Payments]"));
                    }
                    else if (dt.Rows[0][17].ToString() == "Reimbursement" && dt.Rows[0][8].ToString() != "&nbsp;")
                    {
                        runTitle.AppendChild(new Text("Sub:Raising of Invoice [Reimbursement of costs]"));
                    }
                    else if (dt.Rows[0][17].ToString() == "Reimbursement" && dt.Rows[0][8].ToString() == "&nbsp;")
                    {
                        runTitle.AppendChild(new Text("Sub : Reimbursements of costs"));
                        Paragraph subdetail    = body.AppendChild(new Paragraph());
                        Run       runsubdetail = subdetail.AppendChild(new Run());
                        runsubdetail.AppendChild(new Text("Dear Sir / Madam,"));
                        runsubdetail.AppendChild(new Text("Reference Agreement as per details below,reimbursement of costs are due."));
                    }

                    // Create an empty table.
                    Table table = new Table();

                    // Create a TableProperties object and specify its border information.
                    TableProperties tblProp = new TableProperties(
                        new TableBorders(
                            new TopBorder()
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 10
                    },
                            new BottomBorder()
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 10
                    },
                            new LeftBorder()
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 10
                    },
                            new RightBorder()
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 10
                    },
                            new InsideHorizontalBorder()
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 10
                    },
                            new InsideVerticalBorder()
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 10
                    }
                            )
                        );

                    // Append the TableProperties object to the empty table.
                    table.AppendChild <TableProperties>(tblProp);
                    table.Append(new TableProperties(new TableWidth()
                    {
                        Type = TableWidthUnitValues.Pct, Width = "100%"
                    }));

                    TableRow tr = new TableRow();
                    //tr.Append(new TableRowProperties(new TableWidth() { Type = TableWidthUnitValues.Pct, Width = "100%" }));
                    TableCell tc1 = new TableCell();
                    // Specify the width property of the table cell.
                    //tc1.Append(new TableCellProperties(
                    //    new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
                    // Specify the table cell content.
                    tc1.Append(new Paragraph(new Run(new Text(dt.Rows[0][0].ToString()))));
                    // Append the table cell to the table row.
                    tr.Append(tc1);
                    TableCell tc2 = new TableCell();
                    tc2.Append(new Paragraph(new Run(new Text("Agreement No: " + dt.Rows[0][1]))));
                    tr.Append(tc2);
                    TableCell tc3 = new TableCell();
                    tc3.Append(new Paragraph(new Run(new Text("TT A/c: " + dt.Rows[0][2]))));
                    tr.Append(tc3);

                    TableCellProperties tcp    = new TableCellProperties();
                    HorizontalMerge     vMerge = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Restart
                    };
                    tcp.Append(vMerge);

                    TableCellProperties tcp1    = new TableCellProperties();
                    HorizontalMerge     vMerge1 = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Continue
                    };
                    tcp1.Append(vMerge1);

                    TableRow  tr1  = new TableRow();
                    TableCell tcr1 = new TableCell();
                    tcr1.Append(new Paragraph(new Run(new Text("Title:" + dt.Rows[0][3]))));
                    tcr1.Append(tcp);
                    tr1.Append(tcr1);

                    TableCell tc2r1 = new TableCell();
                    tc2r1.Append(new Paragraph());
                    tc2r1.Append(tcp1);
                    tr1.Append(tc2r1);
                    TableCell tc3r1 = new TableCell();
                    tc3r1.Append(new Paragraph());
                    TableProperties mergeend = new TableProperties();
                    HorizontalMerge hm1      = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Continue
                    };
                    mergeend.Append(hm1);
                    tc3r1.Append(mergeend);
                    tr1.Append(tc3r1);

                    TableCellProperties tcp2   = new TableCellProperties();
                    HorizontalMerge     hMerge = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Restart
                    };
                    tcp2.Append(hMerge);
                    TableCellProperties tcp3    = new TableCellProperties();
                    HorizontalMerge     hMerge1 = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Continue
                    };
                    tcp3.Append(hMerge1);

                    TableRow  tr2  = new TableRow();
                    TableCell tcr2 = new TableCell();
                    tcr2.Append(new Paragraph(new Run(new Text("Scope: " + dt.Rows[0][4]))));
                    tcr2.Append(tcp2);
                    tr2.Append(tcr2);
                    TableCell tc2r2 = new TableCell();
                    tc2r2.Append(new Paragraph());
                    tc2r2.Append(tcp3);
                    tr2.Append(tc2r2);
                    TableCell tc3r2 = new TableCell();
                    tc3r2.Append(new Paragraph());
                    TableProperties mergeend1 = new TableProperties();
                    HorizontalMerge hm3       = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Continue
                    };
                    mergeend1.Append(hm3);
                    tc3r2.Append(mergeend1);
                    tr2.Append(tc3r2);

                    TableCellProperties tcp4    = new TableCellProperties();
                    HorizontalMerge     hMerge2 = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Restart
                    };
                    tcp4.Append(hMerge2);
                    TableCellProperties tcp5    = new TableCellProperties();
                    HorizontalMerge     hMerge3 = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Continue
                    };
                    tcp5.Append(hMerge3);

                    TableRow  tr3  = new TableRow();
                    TableCell tcr3 = new TableCell();
                    tcr3.Append(new Paragraph(new Run(new Text("Coordinating Person: " + dt.Rows[0][5]))));
                    tcr3.Append(tcp4);
                    tr3.Append(tcr3);
                    TableCell tc2r3 = new TableCell();
                    tc2r3.Append(new Paragraph());
                    tc2r3.Append(tcp5);
                    tr3.Append(tc2r3);
                    TableCell tc3r3 = new TableCell();
                    tc3r3.Append(new Paragraph());
                    TableProperties mergeend2 = new TableProperties();
                    HorizontalMerge hm5       = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Continue
                    };
                    mergeend2.Append(hm5);
                    tc3r3.Append(mergeend2);
                    tr3.Append(tc3r3);

                    TableCellProperties tcp6    = new TableCellProperties();
                    HorizontalMerge     hMerge4 = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Restart
                    };
                    tcp6.Append(hMerge4);
                    TableCellProperties tcp7    = new TableCellProperties();
                    HorizontalMerge     hMerge5 = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Continue
                    };
                    tcp7.Append(hMerge5);

                    TableRow  tr4   = new TableRow();
                    TableCell tc1r4 = new TableCell();
                    tc1r4.Append(new Paragraph(new Run(new Text("Type: " + dt.Rows[0][6]))));
                    tc1r4.Append(tcp6);
                    tr4.Append(tc1r4);
                    TableCell tc2r4 = new TableCell();
                    tc2r4.Append(new Paragraph());
                    tc2r4.Append(tcp7);
                    tr4.Append(tc2r4);
                    TableCell tc3r4 = new TableCell();
                    tc3r4.Append(new Paragraph(new Run(new Text("Dept: " + dt.Rows[0][6]))));
                    tr4.Append(tc3r4);

                    TableCellProperties tcp8    = new TableCellProperties();
                    HorizontalMerge     hMerge6 = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Restart
                    };
                    tcp8.Append(hMerge6);
                    TableCellProperties tcp9    = new TableCellProperties();
                    HorizontalMerge     hMerge7 = new HorizontalMerge()
                    {
                        Val = MergedCellValues.Continue
                    };
                    tcp9.Append(hMerge7);

                    TableRow  tr5   = new TableRow();
                    TableCell tc1r5 = new TableCell();
                    tc1r5.Append(new Paragraph(new Run(new Text("Due Date: " + dt.Rows[0][9]))));
                    tc1r5.Append(tcp8);
                    tr5.Append(tc1r5);
                    TableCell tc2r5 = new TableCell();
                    tc2r5.Append(new Paragraph());
                    tc2r5.Append(tcp9);
                    tr5.Append(tc2r5);
                    TableCell tc3r5 = new TableCell();
                    tc3r5.Append(new Paragraph(new Run(new Text("Amount: " + dt.Rows[0][8]))));
                    tr5.Append(tc3r5);

                    // Append the table row to the table.
                    table.Append(tr);
                    table.Append(tr1);
                    table.Append(tr2);
                    table.Append(tr3);
                    table.Append(tr4);
                    table.Append(tr5);
                    // Append the table to the document.
                    doc.MainDocumentPart.Document.Body.Append(table);

                    if (dt.Rows[0][8].ToString() != "&nbsp;")
                    {
                        Paragraph     customer    = body.AppendChild(new Paragraph());
                        Run           runcustomer = customer.AppendChild(new Run());
                        RunProperties cusprp      = new RunProperties(new Bold(), new Underline()
                        {
                            Val = UnderlineValues.Single
                        });
                        //cusprp.Bold = new Bold();
                        //cusprp.Underline = new Underline();
                        runcustomer.Append(new Break());
                        runcustomer.Append(cusprp);
                        runcustomer.AppendChild(new Text("Customer"));

                        Paragraph     custdet    = body.AppendChild(new Paragraph());
                        Run           rundetails = custdet.AppendChild(new Run());
                        Justification center     = new Justification()
                        {
                            Val = JustificationValues.Center
                        };
                        rundetails.AppendChild(center);
                        rundetails.AppendChild(new Text(dt.Rows[0][10].ToString()));
                        rundetails.AppendChild(new Break());
                        rundetails.AppendChild(new Text(dt.Rows[0][11].ToString()));
                        rundetails.AppendChild(new Break());
                        rundetails.AppendChild(new Text(dt.Rows[0][12].ToString()));
                        rundetails.AppendChild(new Break());
                        rundetails.AppendChild(new Text(dt.Rows[0][13].ToString()));
                        rundetails.AppendChild(new Break());
                        rundetails.AppendChild(new Text(dt.Rows[0][14].ToString()));
                        rundetails.AppendChild(new Break());
                        rundetails.AppendChild(new Text(dt.Rows[0][15].ToString()));
                        rundetails.AppendChild(new Break());
                        rundetails.AppendChild(new Text(dt.Rows[0][16].ToString()));
                    }
                    Paragraph extra    = body.AppendChild(new Paragraph());
                    Run       runextra = extra.AppendChild(new Run());
                    runextra.AppendChild(new Break());
                    if ((dt.Rows[0][17].ToString() == "Upfront Payment" || dt.Rows[0][17].ToString() == "Annual") && dt.Rows[0][8] != null)
                    {
                        runextra.AppendChild(new Text("Other available details are attached. The invoice may be raised for the above."));
                    }
                    else if (dt.Rows[0][17].ToString() == "Royalty" && dt.Rows[0][8].ToString() != "&nbsp;")
                    {
                        runextra.AppendChild(new Text("The declaration of dues and workings has been verified by us. Same is enclosed."));
                        runextra.AppendChild(new Break());
                        runextra.AppendChild(new Text("The invoice may be raised for the above"));
                    }
                    else if (dt.Rows[0][17].ToString() == "Royalty" && dt.Rows[0][8].ToString() == "&nbsp;")
                    {
                        runextra.AppendChild(new Text("Request you to send a declaration along with workings. After verification and confirmation we will raise the invoice"));
                        //runextra.AppendChild(new Text("Working sheets of the dues is enclosed. Request you to verify and confirm"));
                        //runextra.AppendChild(new Break());
                        //runextra.AppendChild(new Text("Invoice will be sent on receipt of confirmation"));
                    }
                    else if (dt.Rows[0][17].ToString() == "Reimbursement" && dt.Rows[0][8].ToString() == "&nbsp;")
                    {
                        runextra.AppendChild(new Text("Working sheet of the dues is enclosed. Request you to verify and confirm."));
                        runextra.AppendChild(new Break());
                        runextra.AppendChild(new Text("Invoice will be sent on receipt of confimation"));
                    }
                    else if (dt.Rows[0][17].ToString() == "Reimbursement" && dt.Rows[0][8].ToString() != "&nbsp;")
                    {
                        runextra.AppendChild(new Text("Working sheet along with customer's confirmation is enclosed"));
                        runextra.AppendChild(new Break());
                        runextra.AppendChild(new Text("The invoice may be raised for the above"));
                    }
                    runextra.AppendChild(new Break());
                    runextra.AppendChild(new Break());
                    runextra.AppendChild(new Text("Thanking You"));
                    runextra.AppendChild(new Break());

                    Paragraph support = body.AppendChild(new Paragraph());
                    Run       runsup  = support.AppendChild(new Run());

                    if (dt.Rows[0][17].ToString() == "Upfront Payment" && dt.Rows[0][8].ToString() != "&nbsp;")
                    {
                        runsup.AppendChild(new Text("Supporting Documents:"));
                        runsup.AppendChild(new Break());
                        runsup.AppendChild(new Text("1. PDF of Agreement -" + dt.Rows[0][0]));
                        runsup.AppendChild(new Break());
                        runsup.AppendChild(new Text("2. Customer Tax & Bank details"));
                    }
                    else if (dt.Rows[0][17].ToString() == "Annual" && dt.Rows[0][8].ToString() != "&nbsp;")
                    {
                        runsup.AppendChild(new Text("Supporting Documents:"));
                        runsup.AppendChild(new Break());
                        runsup.AppendChild(new Text(" 1. Agreement " + dt.Rows[0][0] + " already forwarded"));
                        runsup.AppendChild(new Break());
                        runsup.AppendChild(new Text(" 2. Customer Tax & Bank details are same /change as per enclosure"));
                    }
                    else if (dt.Rows[0][17].ToString() == "Royalty" && dt.Rows[0][8].ToString() != "&nbsp;")
                    {
                        runsup.AppendChild(new Text("Supporting Documents:"));
                        runsup.AppendChild(new Break());
                        runsup.AppendChild(new Text("1. Verified declaration of dues"));
                        runsup.AppendChild(new Break());
                        runsup.AppendChild(new Text("2. Working sheets of the customer"));
                    }
                    else if (dt.Rows[0][17].ToString() == "Reimbursement" && dt.Rows[0][8].ToString() != "&nbsp;")
                    {
                        runsup.AppendChild(new Text("Supporting Documents:"));
                        runsup.AppendChild(new Break());
                        runsup.AppendChild(new Text("1. Confirmation from the customer"));
                        runsup.AppendChild(new Break());
                        runsup.AppendChild(new Text("2. Detailed workings"));
                    }
                    else if (dt.Rows[0][17].ToString() == "Reimbursement" && dt.Rows[0][8].ToString() == "&nbsp;")
                    {
                        runsup.AppendChild(new Text("Enclosure:"));
                        runsup.AppendChild(new Break());
                        runsup.AppendChild(new Text("1. Working document on dues"));
                        runsup.AppendChild(new Break());
                        runsup.AppendChild(new Text("2. Copies of payment invoices"));
                    }
                    runsup.AppendChild(new Break());
                    doc.MainDocumentPart.Document.Save();
                }
                System.Web.HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + docFileName);
                mem.Seek(0, SeekOrigin.Begin);
                mem.WriteTo(System.Web.HttpContext.Current.Response.OutputStream);
                System.Web.HttpContext.Current.Response.Flush();
                System.Web.HttpContext.Current.Response.End();
            }
        }
    }
Ejemplo n.º 11
0
        private static void AddMentionComment(MainDocumentPart mdp, string strCommentId, string mention, string commentText, User mentioner, User mentionee)
        {
            mdp.AddNewPart <WordprocessingCommentsPart>();
            mdp.WordprocessingCommentsPart.Comments = new Comments();
            Comments comments = mdp.WordprocessingCommentsPart.Comments;

            comments.AppendChild <Comment>(
                new Comment(
                    new Paragraph(
                        new Run(
                            new RunProperties(
                                new Color()
            {
                Val = "2B579A"
            },
                                new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "E6E6E6"
            }),
                            new FieldChar()
            {
                FieldCharType = FieldCharValues.Begin
            }),
                        new Run(
                            new FieldCode(" HYPERLINK \"mailto:" + mentionee.Email + "\"")
            {
                Space = SpaceProcessingModeValues.Preserve
            }),
                        new BookmarkStart()
            {
                Id = "2", Name = "_@_0FD9AD1E39C946AB9F9E1352162C9910Z"
            },
                        new Run(
                            new RunProperties(
                                new Color()
            {
                Val = "2B579A"
            },
                                new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "E6E6E6"
            }),
                            new FieldChar()
            {
                FieldCharType = FieldCharValues.Separate
            }),
                        new BookmarkEnd()
            {
                Id = "2"
            },
                        new Run(
                            new RunProperties(
                                new RunStyle()
            {
                Val = "Mention"
            },
                                new NoProof()),
                            new Text(mention)),
                        new Run(
                            new RunProperties(
                                new Color()
            {
                Val = "2B579A"
            },
                                new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "E6E6E6"
            }),
                            new FieldChar()
            {
                FieldCharType = FieldCharValues.End
            }),
                        new Run(
                            new Text(commentText)
            {
                Space = SpaceProcessingModeValues.Preserve
            }),
                        new Run(
                            new AnnotationReferenceMark()))

                    // These ids MUST be unique in the document.
            {
                TextId = "FFFFFF04"
            })

                // This id MUST be unique in the comments part.
            {
                Id = strCommentId, Author = mentioner.UserName, Date = DateTime.Now, Initials = mentioner.UserName.Substring(0, 1) + mentioner.UserName.Substring(mentioner.UserName.IndexOf(" ") + 1, 1)
            });
        }
Ejemplo n.º 12
0
 // Add a StylesDefinitionsPart to the document.  Returns a reference to it.
 private void AddStylesPartToPackage()
 {
     m_StylesPart = m_DocumentPart.AddNewPart <StyleDefinitionsPart>();
     m_Styles     = new Styles();
     m_Styles.Save(m_StylesPart);
 }
Ejemplo n.º 13
0
        public static void ProcessTranslate(WordprocessingDocument wordprocessingDocument, MainDocumentPart m)
        {
            int begintag  = 0;
            int endtag    = 0;
            int listcount = 1;

            while (begintag < txtPatentlist.Count())
            {
                endtag = GetInterval(begintag);

                if (txtPatentlist[begintag][0] == "img")
                {
                    InsertAPicture(wordprocessingDocument, m, txtPatentlist[begintag][1]);
                }

                //else if (txtPatentlist[begintag][0] == "br")
                //{
                //    WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true);
                //    Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
                //    Paragraph para = new Paragraph();
                //    Run run = para.AppendChild(new Run());
                //    run.Append(new Break());
                //    body.AppendChild(para);
                //    wordprocessingDocument.MainDocumentPart.Document.Save();

                //    wordprocessingDocument.Close();
                //}

                else if (txtPatentlist[begintag].Contains("table"))
                {
                    int trindex  = txtPatentlist[begintag].IndexOf("tr") + 1;
                    int colcount = Int32.Parse(txtPatentlist[begintag][trindex]);
                    int rowcount = (endtag - begintag) / colcount;
                    CreateTable(wordprocessingDocument, colcount, rowcount, begintag);
                }

                else if (txtPatentlist[begintag].Contains("ul"))
                {
                    //WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true);
                    //MainDocumentPart m = wordprocessingDocument.MainDocumentPart;
                    //Body body = m.Document.Body;

                    NumberingDefinitionsPart numberingPart = m.NumberingDefinitionsPart;
                    if (numberingPart == null)
                    {
                        numberingPart = m.AddNewPart <NumberingDefinitionsPart>();
                    }

                    Numbering element =
                        new Numbering(
                            new AbstractNum(
                                new MultiLevelType()
                    {
                        Val = MultiLevelValues.Multilevel
                    },
                                new Level(

                                    new NumberingFormat()
                    {
                        Val = NumberFormatValues.Bullet
                    },
                                    new LevelText()
                    {
                        Val = "●"
                    }
                                    )
                    {
                        LevelIndex = 0
                    },

                                new Level(

                                    new NumberingFormat()
                    {
                        Val = NumberFormatValues.Bullet
                    },
                                    new LevelText()
                    {
                        Val = "o"
                    }
                                    )
                    {
                        LevelIndex = 1
                    },

                                new Level(

                                    new NumberingFormat()
                    {
                        Val = NumberFormatValues.Bullet
                    },
                                    new LevelText()
                    {
                        Val = "■"
                    }
                                    )
                    {
                        LevelIndex = 2
                    }
                                )
                    {
                        AbstractNumberId = 1
                    },
                            new NumberingInstance(
                                new AbstractNumId()
                    {
                        Val = 1
                    }
                                )
                    {
                        NumberID = 1
                    }
                            );

                    element.Save(numberingPart);



                    bool isenter = false;

                    for (; begintag < endtag; begintag++)
                    {
                        if (txtPatentlist[begintag][0] == "br")
                        {
                            begintag++;
                            isenter = true;
                        }
                        int    level   = -1;
                        string content = txtPatentlist[begintag][0];
                        foreach (string s in txtPatentlist[begintag])
                        {
                            if (s == "ul")
                            {
                                level += 1;
                            }
                        }
                        AppendListItem(wordprocessingDocument, content, level, listcount, 0, isenter);
                        wordprocessingDocument.MainDocumentPart.Document.Save();
                        isenter = false;
                    }
                    listcount++;
                    //wordprocessingDocument.Close();
                }

                else if (txtPatentlist[begintag].Contains("pre"))
                {
                    //WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true);

                    //Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
                    Paragraph para = new Paragraph();

                    ParagraphProperties paraProperties = new ParagraphProperties();
                    ParagraphBorders    paraBorders    = new ParagraphBorders();
                    TopBorder           top            = new TopBorder()
                    {
                        Val = BorderValues.Single, Color = "auto", Size = (UInt32Value)9U, Space = (UInt32Value)5U
                    };
                    BottomBorder bottom = new BottomBorder()
                    {
                        Val = BorderValues.Single, Color = "auto", Size = (UInt32Value)9U, Space = (UInt32Value)5U
                    };
                    LeftBorder left = new LeftBorder()
                    {
                        Val = BorderValues.Single, Color = "auto", Size = (UInt32Value)9U, Space = (UInt32Value)5U
                    };
                    RightBorder right = new RightBorder()
                    {
                        Val = BorderValues.Single, Color = "auto", Size = (UInt32Value)9U, Space = (UInt32Value)5U
                    };
                    paraBorders.Append(bottom);
                    paraBorders.Append(top);
                    paraBorders.Append(left);
                    paraBorders.Append(right);
                    paraProperties.Append(paraBorders);
                    para.Append(paraProperties);

                    Run      run = para.AppendChild(new Run());
                    string   t   = txtPatentlist[begintag][0];
                    string[] s   = t.Split('\n');
                    foreach (string str in s)
                    {
                        if (str.Contains("  "))
                        {
                            run.Append(new TabChar());
                        }
                        run.AppendChild(new Text(str));
                        run.Append(new Break());
                    }


                    body.AppendChild(para);
                    wordprocessingDocument.MainDocumentPart.Document.Save();

                    //wordprocessingDocument.Close();
                }

                else if (txtPatentlist[begintag].Contains("h1"))
                {
                    SetTitle(begintag, endtag, 1.ToString(), wordprocessingDocument);
                    //string path = @"demo.docx";
                    //CreateWordDocumentUsingMSWordStyles(begintag, endtag, path, "E:\\Microsoft Office\\Office16\\2052\\QuickStyles\\Default.dotx");
                }

                else if (txtPatentlist[begintag].Contains("h2"))
                {
                    SetTitle2(begintag, endtag, 2.ToString(), wordprocessingDocument);
                }

                else if (txtPatentlist[begintag].Contains("h3"))
                {
                    SetTitle3(begintag, endtag, 3.ToString(), wordprocessingDocument);
                }

                else
                {
                    //WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true);
                    //Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
                    Paragraph para = body.AppendChild(new Paragraph());

                    for (; begintag < endtag; begintag++)
                    {
                        Run run = para.AppendChild(new Run());
                        if (txtPatentlist[begintag][0] == "br")
                        {
                            run.Append(new Break());
                            begintag++;
                        }
                        if (txtPatentlist[begintag][0] != "endtag")
                        {
                            Text t = new Text(ToHexString(txtPatentlist[begintag][0]));
                            t.Space = t.Space = new EnumValue <SpaceProcessingModeValues>(SpaceProcessingModeValues.Preserve);

                            run.AppendChild(t);
                        }

                        foreach (string tag in txtPatentlist[begintag])
                        {
                            switch (tag)
                            {
                            case "b":
                                SetBoldFont(run, wordprocessingDocument);
                                break;

                            case "u":
                                SetItalic(run, wordprocessingDocument);
                                break;

                            case "strong":
                                SetBoldFont(run, wordprocessingDocument);
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    //wordprocessingDocument.Close();
                }

                begintag = endtag + 1;
            }
            m.Document.Body = body;
            wordprocessingDocument.MainDocumentPart.Document.Save();
            wordprocessingDocument.Close();
        }
Ejemplo n.º 14
0
        private static void AddStyles(MainDocumentPart mainPart)
        {
            var part = mainPart.StyleDefinitionsPart;

            if (part == null)
            {
                part = mainPart.AddNewPart <StyleDefinitionsPart>();
                new Styles().Save(part);
            }

            var latent = new LatentStyles(
                new LatentStyleExceptionInfo
            {
                Name = "Normal", UiPriority = 0, PrimaryStyle = OnOffValue.FromBoolean(true)
            },
                new LatentStyleExceptionInfo
            {
                Name           = "No List", SemiHidden = OnOffValue.FromBoolean(true),
                UnhideWhenUsed = OnOffValue.FromBoolean(true)
            },
                new LatentStyleExceptionInfo
            {
                Name = "List Paragraph", UiPriority = 34, PrimaryStyle = OnOffValue.FromBoolean(true)
            })
            {
                DefaultLockedState    = OnOffValue.FromBoolean(false),
                DefaultUiPriority     = 99,
                DefaultSemiHidden     = OnOffValue.FromBoolean(false),
                DefaultUnhideWhenUsed = OnOffValue.FromBoolean(false),
                DefaultPrimaryStyle   = OnOffValue.FromBoolean(false)
            };

            var normalStyle = new Style(
                new PrimaryStyle()
                )
            {
                StyleId   = "Normal",
                StyleName = new StyleName {
                    Val = "Normal"
                }
            };

            var numbering = new Style(
                new StyleName {
                Val = "No List"
            },
                new UIPriority {
                Val = 99
            },
                new SemiHidden(),
                new UnhideWhenUsed()
                )
            {
                Type    = StyleValues.Numbering,
                Default = OnOffValue.FromBoolean(true),
                StyleId = "NoList"
            };


            var listParagraphStyle = new Style(
                new PrimaryStyle(),
                new ParagraphProperties(
                    new Indentation {
                Left = new Unit(0.25, UnitType.inch)
            },
                    new ContextualSpacing()
                    ))
            {
                Type      = StyleValues.Paragraph,
                StyleId   = "ListParagraph",
                StyleName = new StyleName {
                    Val = "List Paragraph"
                },
                BasedOn = new BasedOn {
                    Val = "Normal"
                },
                UIPriority = new UIPriority {
                    Val = 34
                }
            };

            part.Styles.Append(latent, numbering, normalStyle, listParagraphStyle);

            part.Styles.Save();
        }
Ejemplo n.º 15
0
        public void Build(GeneralTree <INode> features)
        {
            string filename = string.IsNullOrEmpty(this.configuration.SystemUnderTestName)
                ? "features.docx"
                : this.configuration.SystemUnderTestName + ".docx";
            string documentFileName = this.fileSystem.Path.Combine(this.configuration.OutputFolder.FullName, filename);

            if (this.fileSystem.File.Exists(documentFileName))
            {
                try
                {
                    this.fileSystem.File.Delete(documentFileName);
                }
                catch (System.IO.IOException ex)
                {
                    Log.Error("Cannot delete Word file. Is it still open in Word?", ex);
                    return;
                }
            }

            using (
                WordprocessingDocument wordProcessingDocument = WordprocessingDocument.Create(
                    documentFileName,
                    WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainDocumentPart = wordProcessingDocument.AddMainDocumentPart();
                this.wordStyleApplicator.AddStylesPartToPackage(wordProcessingDocument);
                this.wordStyleApplicator.AddStylesWithEffectsPartToPackage(wordProcessingDocument);
                this.wordFontApplicator.AddFontTablePartToPackage(wordProcessingDocument);
                var documentSettingsPart = mainDocumentPart.AddNewPart <DocumentSettingsPart>();
                documentSettingsPart.Settings = new Settings();
                this.wordHeaderFooterFormatter.ApplyHeaderAndFooter(wordProcessingDocument);

                var document = new Document();
                var body     = new Body();
                document.Append(body);

                var actionVisitor = new ActionVisitor <INode>(node =>
                {
                    var featureDirectoryTreeNode =
                        node as FeatureNode;
                    if (featureDirectoryTreeNode != null)
                    {
                        this.wordFeatureFormatter.Format(body, featureDirectoryTreeNode);
                    }
                });

                features.AcceptVisitor(actionVisitor);

                mainDocumentPart.Document = document;
                mainDocumentPart.Document.Save();
            }

            // HACK - Add the table of contents
            using (WordprocessingDocument wordProcessingDocument = WordprocessingDocument.Open(documentFileName, true))
            {
                XElement firstPara = wordProcessingDocument
                                     .MainDocumentPart
                                     .GetXDocument()
                                     .Descendants(W.p)
                                     .FirstOrDefault();

                TocAdder.AddToc(wordProcessingDocument, firstPara, @"TOC \o '1-2' \h \z \u", null, 4);
            }
        }
Ejemplo n.º 16
0
        private static void AddNumberingStyles(MainDocumentPart mainPart)
        {
            var part = mainPart.NumberingDefinitionsPart;

            if (part == null)
            {
                part = mainPart.AddNewPart <NumberingDefinitionsPart>();
                new Numbering().Save(part);
            }

            var abstractNumberId =
                (part.Numbering.Elements <AbstractNum>().Max(x => x.AbstractNumberId?.Value) ?? 0) + 1;

            var abstractLevel = new Level(
                new StartNumberingValue {
                Val = 1
            },
                new NumberingFormat {
                Val = NumberFormatValues.Bullet
            },
                new LevelText {
                Val = ""
            },
                new LevelJustification {
                Val = LevelJustificationValues.Left
            },
                new ParagraphProperties
            {
                Indentation = new Indentation
                {
                    Left    = new Unit(0.25, UnitType.inch),
                    Hanging = new Unit(0.125, UnitType.inch)
                }
            },
                new ParagraphMarkRunProperties(
                    new RunFonts
            {
                Ascii    = "Symbol",
                HighAnsi = "Symbol",
                Hint     = FontTypeHintValues.Default
            }
                    )
                )
            {
                LevelIndex = 0
            };

            var abstractNum1 = new AbstractNum(abstractLevel)
            {
                AbstractNumberId = abstractNumberId,
                MultiLevelType   = new MultiLevelType {
                    Val = MultiLevelValues.HybridMultilevel
                }
            };

            part.Numbering.AppendChild(abstractNum1);

            part.Numbering.AppendChild(
                new NumberingInstance
            {
                NumberID      = abstractNumberId,
                AbstractNumId = new AbstractNumId
                {
                    Val = abstractNumberId
                }
            }
                );

            part.Numbering.Save();
        }
Ejemplo n.º 17
0
    public void ProcessRequest(System.Data.DataTable dt, string docFileName)
    { 

        using (MemoryStream mem = new MemoryStream())
        {
            // Create Document
            using (WordprocessingDocument wordDocument =
            WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
            {
                // Add a main document part. 
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
                StyleDefinitionsPart stylePart= mainPart.AddNewPart<StyleDefinitionsPart>();

                RunProperties rPrNormal = new RunProperties();
                RunFonts rFont1 = new RunFonts();
                //rFont1.Ascii = "Times New Roman";
                //rPrNormal.Append(rFont1);
                rPrNormal.Append(new DocumentFormat.OpenXml.Wordprocessing.FontSize() { Val = "24" });
                DocumentFormat.OpenXml.Wordprocessing.Style style1 = new DocumentFormat.OpenXml.Wordprocessing.Style();
                style1.StyleId = "myText";
                style1.Append(new Name() { Val = "text" });
                style1.Append(rPrNormal);
                stylePart.Styles = new Styles();
                stylePart.Styles.Append(style1);
                
                RunProperties rPr = new RunProperties();
                Color color = new Color() { Val = "FF0000" };
                RunFonts rFont = new RunFonts();
                //rFont.Ascii = "Times New Roman";
                //rPr.Append(color);
                //rPr.Append(rFont);
                rPr.Append(new Bold());
                rPr.Append(new DocumentFormat.OpenXml.Wordprocessing.FontSize() { Val = "24" });
                DocumentFormat.OpenXml.Wordprocessing.Style style= new DocumentFormat.OpenXml.Wordprocessing.Style();
                style.StyleId = "myHeading1";
                style.Append(new Name() {Val="My Heading 1"});
                style.Append(new NextParagraphStyle() { Val = "Normal" });
                style.Append(rPr);
                stylePart.Styles = new Styles();
                stylePart.Styles.Append(style);
                stylePart.Styles.Save();

                // Create the document structure and add some text.
                mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                
                Body body = mainPart.Document.AppendChild(new Body());
                ParagraphProperties Normal_pPr = new ParagraphProperties(new ParagraphStyleId() { Val = "myText" });

                foreach (DataRow row in dt.Rows)
                {
                    Paragraph paraTo = body.AppendChild(new Paragraph());
                    Run runHead = paraTo.AppendChild(new Run());
                    RunProperties rpHead = new RunProperties();
                    rpHead.Append(new Bold());
                    runHead.Append(rpHead);
                    runHead.AppendChild(new Text("Mr.Ateet P"));
                    runHead.AppendChild(new Break());
                    runHead.AppendChild(new Text("Marketing Manager"));
                    runHead.AppendChild(new Break());
                    runHead.AppendChild(new Text("IPM Cell"));
                    runHead.AppendChild(new Break());
                    Run runTo = paraTo.AppendChild(new Run());                    
                    runTo.AppendChild(new Text("To"));
                    runTo.AppendChild(new Break());
                    runTo.AppendChild(new Text("" + row["ContactName"]));
                    runTo.AppendChild(new Break());
                    runTo.AppendChild(new Text(""+row["Address1"]));
                    runTo.AppendChild(new Break());
                    runTo.AppendChild(new Text("" + row["Address2"]));                                                            
                    Paragraph paraDate = body.AppendChild(new Paragraph());
                    ParagraphProperties ppDate = new ParagraphProperties();
                    Justification dateAlign = new Justification() { Val = JustificationValues.Right };
                    ppDate.Append(dateAlign);
                    paraDate.Append(ppDate);
                    Run runDate = paraDate.AppendChild(new Run());
                    runDate.AppendChild(new Text("Date : " + DateTime.Now.ToShortDateString()));                    
                    Paragraph paraTitle = body.AppendChild(new Paragraph());
                    ParagraphProperties heading_pPr = new ParagraphProperties();
                    heading_pPr.ParagraphStyleId = new ParagraphStyleId() { Val = "myHeading1" };
                    Justification centerHeading = new Justification() { Val = JustificationValues.Center };
                    heading_pPr.Append(centerHeading);
                    paraTitle.Append(heading_pPr);
                    Run runTitle = paraTitle.AppendChild(new Run());
                    runTitle.AppendChild(new Text("SUB : TECHNOLOGY TRANSFER - IP Licensing, Collaboration"));
                    Paragraph para = body.AppendChild(new Paragraph());
                    Run run = para.AppendChild(new Run());
                    run.AppendChild(new Text("Dear Sir / Madam,"));
                    Paragraph para1 = body.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines() { After = "120" })));
                    Run run1 = para1.AppendChild(new Run());
                    run1.AppendChild(new Text("Greetings from IIT Madras!"));
                    Paragraph para2 = body.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines() { After = "120" })));
                    Run run2 = para2.AppendChild(new Run());
                    Text para21Text = new Text() { Text = "Indian Institute of Technology Madras, is a leading Institute for Technology Research and Education. Further details are available at ",Space=SpaceProcessingModeValues.Preserve};
                    run2.AppendChild(para21Text);
                    RunProperties rpBold = new RunProperties();
                    Bold bold = new Bold();
                    rpBold.Append(bold);
                    Text para22Text = new Text() { Text = "https://www.iitm.ac.in" };
                    run2.AppendChild(rpBold);
                    run2.AppendChild(para22Text);
                    Paragraph para3 = body.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines() { After = "120" })));                    
                    Run run3 = para3.AppendChild(new Run());
                    run3.AppendChild(new Text("Researchers at the institute have developed following technology with potential application in your industry. Details are as follows:"));
                    Paragraph para4 = body.AppendChild(new Paragraph(new ParagraphProperties(new Indentation() { Left = "500" }, new SpacingBetweenLines() { After = "120" })));
                    Run run4 = para4.AppendChild(new Run());
                    Text para41Text = new Text() { Text = "IP Type :     ", Space = SpaceProcessingModeValues.Preserve };
                    RunProperties rpBold4 = new RunProperties();
                    rpBold4.Append(new Bold());
                    run4.AppendChild(rpBold4);
                    rpBold4.Append(para41Text);
                    Run run41 = para4.AppendChild(new Run());
                    Text para42Text = new Text() { Text = "" + row["PType"]};
                    run41.Append(para42Text);
                    Paragraph para5 = body.AppendChild(new Paragraph(new ParagraphProperties(new Indentation() { Left = "500" }, new Justification() { Val = JustificationValues.Both }, new SpacingBetweenLines() { After = "120" })));
                    Run run5 = para5.AppendChild(new Run());
                    RunProperties rprun5 = new RunProperties();
                    rprun5.Append(new Bold());
                    run5.Append(rprun5);
                    Text para51Text = new Text() { Text = "Title :     ", Space = SpaceProcessingModeValues.Preserve };
                    run5.Append(para51Text);
                    Run run51 = para5.AppendChild(new Run());
                    run51.AppendChild(new Text("" + row["Title"]));
                    Paragraph para6 = body.AppendChild(new Paragraph(new ParagraphProperties(new Indentation() { Left = "500" }, new SpacingBetweenLines() { After = "120" })));
                    Run run6 = para6.AppendChild(new Run());
                    RunProperties rp6 = new RunProperties();
                    rp6.Append(new Bold());
                    run6.Append(rp6);
                    Text para61Text = new Text() {Text="Reference :     ", Space=SpaceProcessingModeValues.Preserve};
                    run6.Append(para61Text);
                    Run run61 = para6.AppendChild(new Run());
                    run61.Append( new Text ("Application Number : " + row["ApplicationNo"] + "            Filing Date : " + row["FilingDt"]));
                    Paragraph para7 = body.AppendChild(new Paragraph(new ParagraphProperties(new Indentation() { Left = "500" }, new Justification() { Val = JustificationValues.Both }, new SpacingBetweenLines() { After = "120" })));
                    Run run7 = para7.AppendChild(new Run());
                    RunProperties rp7 = new RunProperties();
                    rp7.Append(new Bold());
                    run7.Append(rp7);
                    Text para71Text = new Text() { Text = "Abstract :     ", Space = SpaceProcessingModeValues.Preserve };
                    run7.Append(para71Text);
                    Run run71 = para7.AppendChild(new Run());
                    run71.AppendChild(new Text("" + row["Specification"]));
                    Paragraph para8 = body.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines() { After = "120" })));
                    Run run8 = para8.AppendChild(new Run());
                    Text para81Text= new Text () {Text="We are writing to check your interest in the technology for Licensing, or further development. Other related technologies may be accessed at ", Space= SpaceProcessingModeValues.Preserve};
                    run8.Append(para81Text);
                    Text para82Text = new Text() { Text = "https://icsris.iitm.ac.in/ipr" };
                    RunProperties rp8 = new RunProperties();
                    rp8.Append(new Bold());
                    run8.Append(rp8);
                    run8.Append(para82Text);
                    Paragraph para10 = body.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines() { After = "120" })));
                    Run run10 = para10.AppendChild(new Run());
                    run10.AppendChild(new Text("We are looking forward to your interest and feedback."));
                    Paragraph para11 = body.AppendChild(new Paragraph());
                    Run run11 = para11.AppendChild(new Run());
                    run11.AppendChild(new Text("Yours sincerely,"));
                    Paragraph para12 = body.AppendChild(new Paragraph());
                    ParagraphProperties Design_pPr = new ParagraphProperties();
                    Design_pPr.ParagraphStyleId = new ParagraphStyleId() { Val = "myHeading1" };
                    para12.Append(Design_pPr);                    
                    Run run12 = para12.AppendChild(new Run());
                    run12.AppendChild(new Break());
                    run12.AppendChild(new Text("Marketing Manager"));
                    Paragraph tt1 = new Paragraph(new Run(new Break() { Type = BreakValues.Page }));
                    body.Append(tt1);
                }
                //Paragraph p232= new Paragraph();
               // ParagraphProperties pp220 = new ParagraphProperties();
                //SectionProperties sp1 = new SectionProperties();
                
                
                //.PrependChild<RunProperties>(rPrNormal);
                mainPart.Document.Save();
            }
            System.Web.HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + docFileName);
            mem.Seek(0, SeekOrigin.Begin);
            mem.WriteTo(System.Web.HttpContext.Current.Response.OutputStream);
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();           
        }
    }
Ejemplo n.º 18
0
 /// <summary>
 /// Add a new part in the document
 /// </summary>
 /// <typeparam name="T">Type of the object</typeparam>
 /// <returns>created part</returns>
 public T AddNewPart <T>() where T : OpenXmlPart, IFixedContentTypePart
 {
     return(wdMainDocumentPart.AddNewPart <T>());
 }
        // Create Chart in Word document
        public void CreateChart(List <ChartSubArea> chartList)
        {
            // Get MainDocumentPart of Document
            MainDocumentPart mainPart = document.AddMainDocumentPart();

            mainPart.Document = new Document(new Body());

            // Create ChartPart object in Word Document
            ChartPart chartPart = mainPart.AddNewPart <ChartPart>("rId110");

            // the root element of chartPart
            dc.ChartSpace chartSpace = new dc.ChartSpace();
            chartSpace.Append(new dc.EditingLanguage()
            {
                Val = "en-us"
            });

            // Create Chart
            dc.Chart chart = new dc.Chart();
            chart.Append(new dc.AutoTitleDeleted()
            {
                Val = true
            });

            // Define the 3D view
            dc.View3D view3D = new dc.View3D();
            view3D.Append(new dc.RotateX()
            {
                Val = 30
            });
            view3D.Append(new dc.RotateY()
            {
                Val = 0
            });

            // Intiliazes a new instance of the PlotArea class
            dc.PlotArea plotArea = new dc.PlotArea();
            plotArea.Append(new dc.Layout());

            // the type of Chart
            dc.Pie3DChart pie3DChart = new dc.Pie3DChart();
            pie3DChart.Append(new dc.VaryColors()
            {
                Val = true
            });
            dc.PieChartSeries pieChartSers = new dc.PieChartSeries();
            pieChartSers.Append(new dc.Index()
            {
                Val = 0U
            });
            pieChartSers.Append(new dc.Order()
            {
                Val = 0U
            });
            dc.SeriesText seriesText = new dc.SeriesText();
            seriesText.Append(new dc.NumericValue()
            {
                Text = "Series"
            });

            uint   rowcount = 0;
            uint   count    = UInt32.Parse(chartList.Count.ToString());
            string endCell  = (count + 1).ToString();

            dc.ChartShapeProperties chartShapePros = new dc.ChartShapeProperties();

            // Define cell for lable information
            dc.CategoryAxisData cateAxisData = new dc.CategoryAxisData();
            dc.StringReference  stringRef    = new dc.StringReference();
            stringRef.Append(new dc.Formula()
            {
                Text = "Main!$A$2:$A$" + endCell
            });
            dc.StringCache stringCache = new dc.StringCache();
            stringCache.Append(new dc.PointCount()
            {
                Val = count
            });

            // Define cells for value information
            dc.Values          values = new dc.Values();
            dc.NumberReference numRef = new dc.NumberReference();
            numRef.Append(new dc.Formula()
            {
                Text = "Main!$B$2:$B$" + endCell
            });

            dc.NumberingCache numCache = new dc.NumberingCache();
            numCache.Append(new dc.FormatCode()
            {
                Text = "General"
            });
            numCache.Append(new dc.PointCount()
            {
                Val = count
            });

            // Fill data for chart
            foreach (var item in chartList)
            {
                if (count == 0)
                {
                    chartShapePros.Append(new d.SolidFill(new d.SchemeColor()
                    {
                        Val = item.Color
                    }));
                    pieChartSers.Append(chartShapePros);
                }
                else
                {
                    dc.DataPoint dataPoint = new dc.DataPoint();
                    dataPoint.Append(new dc.Index()
                    {
                        Val = rowcount
                    });
                    chartShapePros = new dc.ChartShapeProperties();
                    chartShapePros.Append(new d.SolidFill(new d.SchemeColor()
                    {
                        Val = item.Color
                    }));
                    dataPoint.Append(chartShapePros);
                    pieChartSers.Append(dataPoint);
                }

                dc.StringPoint stringPoint = new dc.StringPoint()
                {
                    Index = rowcount
                };
                stringPoint.Append(new dc.NumericValue()
                {
                    Text = item.Label
                });
                stringCache.Append(stringPoint);

                dc.NumericPoint numericPoint = new dc.NumericPoint()
                {
                    Index = rowcount
                };
                numericPoint.Append(new dc.NumericValue()
                {
                    Text = item.Value
                });
                numCache.Append(numericPoint);
                rowcount++;
            }

            // Create c:cat and c:val element
            stringRef.Append(stringCache);
            cateAxisData.Append(stringRef);
            numRef.Append(numCache);
            values.Append(numRef);

            // Append c:cat and c:val to the end of c:ser element
            pieChartSers.Append(cateAxisData);
            pieChartSers.Append(values);

            // Append c:ser to the end of c:pie3DChart element
            pie3DChart.Append(pieChartSers);

            // Append c:pie3DChart to the end of s:plotArea element
            plotArea.Append(pie3DChart);

            // create child elements of the c:legend element
            dc.Legend legend = new dc.Legend();
            legend.Append(new dc.LegendPosition()
            {
                Val = LegendPositionValues.Right
            });
            dc.Overlay overlay = new dc.Overlay()
            {
                Val = false
            };
            legend.Append(overlay);

            dc.TextProperties textPros = new TextProperties();
            textPros.Append(new d.BodyProperties());
            textPros.Append(new d.ListStyle());

            d.Paragraph                  paragraph       = new d.Paragraph();
            d.ParagraphProperties        paraPros        = new d.ParagraphProperties();
            d.DefaultParagraphProperties defaultParaPros = new d.DefaultParagraphProperties();
            defaultParaPros.Append(new d.LatinFont()
            {
                Typeface = "Arial", PitchFamily = 34, CharacterSet = 0
            });
            defaultParaPros.Append(new d.ComplexScriptFont()
            {
                Typeface = "Arial", PitchFamily = 34, CharacterSet = 0
            });
            paraPros.Append(defaultParaPros);
            paragraph.Append(paraPros);
            paragraph.Append(new d.EndParagraphRunProperties()
            {
                Language = "en-Us"
            });

            textPros.Append(paragraph);
            legend.Append(textPros);

            // Append c:view3D, c:plotArea and c:legend elements to the end of c:chart element
            chart.Append(view3D);
            chart.Append(plotArea);
            chart.Append(legend);

            // Append the c:chart element to the end of c:chartSpace element
            chartSpace.Append(chart);

            // Create c:spPr Elements and fill the child elements of it
            chartShapePros = new dc.ChartShapeProperties();
            d.Outline outline = new d.Outline();
            outline.Append(new d.NoFill());
            chartShapePros.Append(outline);

            // Append c:spPr element to the end of c:chartSpace element
            chartSpace.Append(chartShapePros);

            chartPart.ChartSpace = chartSpace;

            // Generate content of the MainDocumentPart
            GeneratePartContent(mainPart);
        }
Ejemplo n.º 20
0
        public static void Test_Header_01(bool header = false, bool footer = false, bool pageNumber = false)
        {
            SetDirectory();
            string file = "test_header_01.docx";

            Trace.WriteLine("create docx \"{0}\" using OXmlDoc", file);

            using (WordprocessingDocument doc = WordprocessingDocument.Create(zPath.Combine(_directory, file), WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = doc.AddMainDocumentPart();

                if (header || footer)
                {
                    // activate even and odd headers
                    DocumentSettingsPart documentSettingsPart = mainPart.AddNewPart <DocumentSettingsPart>();
                    Settings             settings             = new Settings();
                    // <w:evenAndOddHeaders />
                    settings.AppendChild(new EvenAndOddHeaders());
                    documentSettingsPart.Settings = settings;
                }

                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());


                Styles styles = Test_OpenXml_Creator.CreateStyles(mainPart);
                //styles.DocDefaults = Test_OXmlCreator.CreateDocDefaults();

                string headerStyleId = null;
                if (header)
                {
                    headerStyleId = "Header";
                    styles.Append(Test_OpenXml_Creator.CreateHeaderFooterStyle(headerStyleId));
                }

                string footerStyleId = null;
                if (footer)
                {
                    footerStyleId = "Footer";
                    styles.Append(Test_OpenXml_Creator.CreateHeaderFooterStyle(footerStyleId));
                }

                string defaultHeaderPartId = null;
                string firstHeaderPartId   = null;
                string evenHeaderPartId    = null;
                if (header)
                {
                    defaultHeaderPartId = Test_OpenXml_Creator.CreateHeader(mainPart, Test_OpenXml_Creator.CreateParagraph_01(headerStyleId, "Default header", tab: 1));
                    firstHeaderPartId   = Test_OpenXml_Creator.CreateHeader(mainPart, Test_OpenXml_Creator.CreateParagraph_01(headerStyleId, "First header", tab: 1));
                    evenHeaderPartId    = Test_OpenXml_Creator.CreateHeader(mainPart, Test_OpenXml_Creator.CreateParagraph_01(headerStyleId, "Even header", tab: 1));
                }

                string defaultFooterPartId = null;
                string firstFooterPartId   = null;
                string evenFooterPartId    = null;
                if (footer)
                {
                    OpenXmlCompositeElement element;
                    if (pageNumber)
                    {
                        element = Test_OpenXml_Creator.CreateParagraph_PageNumber(footerStyleId, "Default footer");
                    }
                    else
                    {
                        element = Test_OpenXml_Creator.CreateParagraph_01(footerStyleId, "Default footer", tab: 1);
                    }
                    defaultFooterPartId = Test_OpenXml_Creator.CreateFooter(mainPart, element);

                    if (pageNumber)
                    {
                        element = Test_OpenXml_Creator.CreateParagraph_PageNumber(footerStyleId, "First footer");
                    }
                    else
                    {
                        element = Test_OpenXml_Creator.CreateParagraph_01(footerStyleId, "First footer", tab: 1);
                    }
                    firstFooterPartId = Test_OpenXml_Creator.CreateFooter(mainPart, element);

                    if (pageNumber)
                    {
                        element = Test_OpenXml_Creator.CreateParagraph_PageNumber(footerStyleId, "Even footer");
                    }
                    else
                    {
                        element = Test_OpenXml_Creator.CreateParagraph_01(footerStyleId, "Even footer", tab: 1);
                    }
                    evenFooterPartId = Test_OpenXml_Creator.CreateFooter(mainPart, element);
                }


                // for SectionProperties
                mainPart.Document.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
                //AddSection(body, defaultHeaderPartId, defaultFooterPartId, firstHeaderPartId, firstFooterPartId);
                SectionProperties sectionProperties = body.AppendChild(new SectionProperties());
                Test_OpenXml_Creator.SetSectionPage(sectionProperties);
                Test_OpenXml_Creator.SetSectionHeaders(sectionProperties, defaultHeaderPartId, defaultFooterPartId, firstHeaderPartId, firstFooterPartId, evenHeaderPartId, evenFooterPartId);
                //Test_OXmlCreator.SetSectionPageNumberType(sectionProperties, start: 1);

                //AddText(body, 200);
                body.Append(Test_OpenXml_Creator.CreateText_02(200));
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Adds the custom XML part to the main document part.
        /// </summary>
        /// <param name="document">The main document part.</param>
        /// <param name="customXml">The custom XML.</param>
        /// <returns>The <see cref="CustomXmlPart" />.</returns>
        public static void AddCustomXmlPart(this MainDocumentPart document, XDocument customXml)
        {
            CustomXmlPart customXmlPart = document.AddNewPart <CustomXmlPart>();

            customXmlPart.PutXDocument(customXml);
        }
Ejemplo n.º 22
0
        public string Save(ITest test, string path)
        {
            try
            {
                using (WordprocessingDocument doc = WordprocessingDocument.Create(
                           path, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
                {
                    //Doc structure
                    mainPart          = doc.AddMainDocumentPart();
                    mainPart.Document = new Document();
                    body = mainPart.Document.AppendChild(new Body());

                    NumberingDefinitionsPart numberingPart =
                        mainPart.AddNewPart <NumberingDefinitionsPart>("numberpart1");
                    Numbering element =
                        new Numbering(
                            new AbstractNum(
                                new Level(
                                    new NumberingFormat()
                    {
                        Val = NumberFormatValues.Bullet
                    },
                                    new LevelText()
                    {
                        Val = "·"
                    })
                    {
                        LevelIndex = 0
                    })
                    {
                        AbstractNumberId = 1
                    },
                            new NumberingInstance(
                                new AbstractNumId()
                    {
                        Val = 1
                    })
                    {
                        NumberID = 1
                    });
                    element.Save(numberingPart);

                    foreach (var question in test.Questions)
                    {
                        Paragraph para = body.AppendChild(new Paragraph());
                        var       info = new StringBuilder(question.QuestionAnswer.GetQuestionTaskInfo());
                        info.Append(" (");
                        info.Append(question.QuestionAnswer.QuestionScore);
                        info.Append(" баллов)");

                        Run run = para.AppendChild(new Run());
                        run.PrependChild(GetStyle(true));
                        run.AppendChild(new Text(info.ToString()));

                        run = para.AppendChild(new Run());
                        run.PrependChild(GetStyle(false));
                        run.AppendChild(new Break());
                        run.AppendChild(new Text(question.QuestionInfo.GetShortDescription()));

                        question.QuestionAnswer.ToWord(this as IWordAnswerPrinter);
                    }
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }
            return(null);
        }
Ejemplo n.º 23
0
        private static void ApplyHeader(WordprocessingDocument doc, CommitteeVM data)
        {
            // Get the main document part.
            MainDocumentPart mainDocPart = doc.MainDocumentPart;

            HeaderPart headerPart1 = mainDocPart.AddNewPart <HeaderPart>("r97");

            Header header1 = new Header();

            Table table = new Table();

            TableProperties props = new TableProperties(
                new TableWidth()
            {
                Width = "100%", Type = TableWidthUnitValues.Auto
            });

            props.BiDiVisual = new BiDiVisual();

            table.AppendChild <TableProperties>(props);
            var tr = new TableRow();
            //cell 1
            var tc = new TableCell();

            tc.Append(CreateParagraph(""));
            tc.Append(CreateParagraph("وزارة التربية و التعليم والتعليم الفني  الادارة العامة للامتحانات", JustificationValues.Center));
            tc.Append(CreateParagraph($"لجنة الإدارة لامتحان  دبلوم  المدارس الثانوية الصناعية نظام السنوات الثلاث قطاع {data.Sector}", JustificationValues.Center));
            var tableWidth = new TableCellWidth
            {
                Type  = TableWidthUnitValues.Auto,
                Width = "28%"
            };

            tc.Append(new TableCellProperties(tableWidth));

            //cell 2
            var tc2 = new TableCell();

            tc2.Append(CreateParagraph("كشـف ", JustificationValues.Center));
            tc2.Append(CreateParagraph("أسماء السادة أعضاء لجنة سير الامتحان ", JustificationValues.Center, "", "12pt", true));

            var table2 = new Table();

            table2.AppendChild <TableProperties>(new TableProperties
            {
                TableWidth = new TableWidth()
                {
                    Width = "90%", Type = TableWidthUnitValues.Auto
                },
                BiDiVisual = new BiDiVisual(),
                TablePositionProperties = new TablePositionProperties {
                    TablePositionXAlignment = HorizontalAlignmentValues.Center
                }
            });
            var row1 = new TableRow();

            row1.Append(CreateTableCell("الدور", "", JustificationValues.Left, "50%", "", "10pt", true));
            row1.Append(CreateTableCell(data.Term, "", JustificationValues.Left, "50%", "", "10pt"));
            var row2 = new TableRow();

            row2.Append(CreateTableCell("أسم اللجنة", "", JustificationValues.Left, "50%", "", "10pt", true));
            row2.Append(CreateTableCell(data.Name, "", JustificationValues.Left, "50%", "", "10pt"));
            var row3 = new TableRow();

            row3.Append(CreateTableCell("مديرية / إدارة", "", JustificationValues.Left, "50%", "", "10pt", true));
            row3.Append(CreateTableCell(data.LearningManagement, "", JustificationValues.Left, "50%", "", "10pt"));
            var row4 = new TableRow();

            row4.Append(CreateTableCell("عنــوان اللجنة", "", JustificationValues.Left, "50%", "", "10pt", true));
            row4.Append(CreateTableCell(data.Address, "", JustificationValues.Left, "50%", "", "10pt"));

            table2.Append(row1);
            table2.Append(row2);
            table2.Append(row3);
            table2.Append(row4);

            tc2.Append(table2);
            tc2.Append(CreateParagraph(""));

            var tableWidth2 = new TableCellWidth
            {
                Type  = TableWidthUnitValues.Auto,
                Width = "47%"
            };

            tc2.Append(new TableCellProperties(tableWidth2));
            //cell 3
            var tc3 = new TableCell();

            tc3.Append(CreateParagraph(" استمارة رقم  13 د ", JustificationValues.Right, "", "12pt"));
            var table3 = new Table();

            table3.AppendChild <TableProperties>(new TableProperties
            {
                TableWidth = new TableWidth()
                {
                    Width = "90%", Type = TableWidthUnitValues.Auto
                },
                BiDiVisual = new BiDiVisual(),
                TablePositionProperties = new TablePositionProperties {
                    TablePositionXAlignment = HorizontalAlignmentValues.Center
                }
            });

            var row5 = new TableRow();

            row5.Append(CreateTableCell("رقم اللجنة", "", JustificationValues.Left, "50%", "", "10pt", true));
            row5.Append(CreateTableCell(data.Number.ToString(), "", JustificationValues.Left, "50%", "", "10pt"));
            var row6 = new TableRow();

            row6.Append(CreateTableCell("نوع اللجنة", "", JustificationValues.Left, "50%", "", "10pt", true));
            row6.Append(CreateTableCell(data.CommitteType, "", JustificationValues.Left, "50%", "", "10pt"));
            var row7 = new TableRow();

            row7.Append(CreateTableCell("عدد الطلبة", "", JustificationValues.Left, "50%", "", "10pt", true));
            row7.Append(CreateTableCell(data.StudentCount.ToString(), "", JustificationValues.Left, "50%", "", "10pt"));
            table3.Append(row5);
            table3.Append(row6);
            table3.Append(row7);

            tc3.Append(table3);
            tc3.Append(CreateParagraph(""));

            var tableWidth3 = new TableCellWidth
            {
                Type  = TableWidthUnitValues.Auto,
                Width = "25%"
            };

            tc3.Append(new TableCellProperties(tableWidth3));


            tr.Append(tc);
            tr.Append(tc2);
            tr.Append(tc3);
            table.Append(tr);

            header1.Append(table);

            headerPart1.Header = header1;



            SectionProperties sectionProperties1 = mainDocPart.Document.Body.Descendants <SectionProperties>().FirstOrDefault();

            if (sectionProperties1 == null)
            {
                sectionProperties1 = new SectionProperties()
                {
                };
                mainDocPart.Document.Body.Append(sectionProperties1);
            }
            HeaderReference headerReference1 = new HeaderReference()
            {
                Type = HeaderFooterValues.Default, Id = "r97"
            };


            sectionProperties1.InsertAt(headerReference1, 0);
        }
Ejemplo n.º 24
0
        public static void ApplyHeader(WordprocessingDocument doc)
        {
            // Get the main document part.
            MainDocumentPart mainDocPart = doc.MainDocumentPart;

            HeaderPart headerPart1 = mainDocPart.AddNewPart <HeaderPart>("r97");

            Header header1 = new Header();

            Table table = new Table();

            TableProperties props = new TableProperties(
                new TableWidth()
            {
                Width = "100%", Type = TableWidthUnitValues.Auto
            });

            props.BiDiVisual = new BiDiVisual();

            table.AppendChild <TableProperties>(props);
            var tr = new TableRow();
            //cell 1
            var tc = new TableCell();

            tc.Append(CreateParagraph("وزارة التربية و التعليم والتعليم الفني  الادارة العامة للامتحانات", JustificationValues.Center));
            tc.Append(CreateParagraph("لجنة الإدارة لامتحان  دبلوم  المدارس الثانوية الصناعية نظام السنوات الثلاث قطاع القاهرة", JustificationValues.Center));
            var tableWidth = new TableCellWidth
            {
                Type  = TableWidthUnitValues.Auto,
                Width = "28%"
            };

            tc.Append(new TableCellProperties(tableWidth));

            //cell 2
            var tc2 = new TableCell();

            tc2.Append(CreateParagraph("كشـف ", JustificationValues.Center));
            tc2.Append(CreateParagraph("أسماء السادة أعضاء لجنة سير الامتحان ", JustificationValues.Center, "", "26", true));

            var tableWidth2 = new TableCellWidth
            {
                Type  = TableWidthUnitValues.Auto,
                Width = "47%"
            };

            tc2.Append(new TableCellProperties(tableWidth2));
            //cell 3
            var tc3 = new TableCell();

            tc3.Append(CreateParagraph(" استمارة رقم  13 د ", JustificationValues.Right));
            tc3.Append(CreateParagraph("رقم اللجنة: " + 25, JustificationValues.Left));
            tc3.Append(CreateParagraph("نوع اللجنة:  صناعي ", JustificationValues.Left));
            tc3.Append(CreateParagraph("عدد الطلبة: " + 98, JustificationValues.Left));

            var tableWidth3 = new TableCellWidth
            {
                Type  = TableWidthUnitValues.Auto,
                Width = "25%"
            };

            tc3.Append(new TableCellProperties(tableWidth3));


            tr.Append(tc);
            tr.Append(tc2);
            tr.Append(tc3);
            table.Append(tr);

            header1.Append(table);

            headerPart1.Header = header1;



            SectionProperties sectionProperties1 = mainDocPart.Document.Body.Descendants <SectionProperties>().FirstOrDefault();

            if (sectionProperties1 == null)
            {
                sectionProperties1 = new SectionProperties()
                {
                };
                mainDocPart.Document.Body.Append(sectionProperties1);
            }
            HeaderReference headerReference1 = new HeaderReference()
            {
                Type = HeaderFooterValues.Default, Id = "r97"
            };


            sectionProperties1.InsertAt(headerReference1, 0);
        }
        public int CreateBulletList()
        {
            NumberingDefinitionsPart numberingPart = wdMainDocumentPart.NumberingDefinitionsPart;

            if (numberingPart == null)
            {
                numberingPart = wdMainDocumentPart.AddNewPart <NumberingDefinitionsPart>();
                Numbering element = new Numbering();
                element.Save(numberingPart);
            }

            // Insert an AbstractNum into the numbering part numbering list.  The order seems to matter or it will not pass the
            // Open XML SDK Productity Tools validation test.  AbstractNum comes first and then NumberingInstance and we want to
            // insert this AFTER the last AbstractNum and BEFORE the first NumberingInstance or we will get a validation error.
            var abstractNumberId = numberingPart.Numbering.Elements <AbstractNum>().Count() + 1;
            var lvls             = new List <Level>();

            for (int i = 0; i < 6; i++)
            {
                var abstractLevel = new Level(new NumberingFormat()
                {
                    Val = NumberFormatValues.Bullet
                }, new LevelText()
                {
                    Val = ""
                }, new ParagraphProperties()
                {
                    Indentation = new Indentation()
                    {
                        Left = (720 * (i + 1)).ToString(), Hanging = "360"
                    }
                }, new RunProperties()
                {
                    RunFonts = new RunFonts()
                    {
                        Ascii = "Symbol", HighAnsi = "Symbol"
                    }
                })
                {
                    LevelIndex = i
                };
                lvls.Add(abstractLevel);
            }
            var abstractNum1 = new AbstractNum(lvls)
            {
                AbstractNumberId = abstractNumberId
            };

            if (abstractNumberId == 1)
            {
                numberingPart.Numbering.Append(abstractNum1);
            }
            else
            {
                AbstractNum lastAbstractNum = numberingPart.Numbering.Elements <AbstractNum>().Last();
                numberingPart.Numbering.InsertAfter(abstractNum1, lastAbstractNum);
            }

            // Insert an NumberingInstance into the numbering part numbering list.  The order seems to matter or it will not pass the
            // Open XML SDK Productity Tools validation test.  AbstractNum comes first and then NumberingInstance and we want to
            // insert this AFTER the last NumberingInstance and AFTER all the AbstractNum entries or we will get a validation error.
            var numberId = numberingPart.Numbering.Elements <NumberingInstance>().Count() + 1;
            NumberingInstance numberingInstance1 = new NumberingInstance()
            {
                NumberID = numberId
            };
            AbstractNumId abstractNumId1 = new AbstractNumId()
            {
                Val = abstractNumberId
            };

            numberingInstance1.Append(abstractNumId1);

            if (numberId == 1)
            {
                numberingPart.Numbering.Append(numberingInstance1);
            }
            else
            {
                var lastNumberingInstance = numberingPart.Numbering.Elements <NumberingInstance>().Last();
                numberingPart.Numbering.InsertAfter(numberingInstance1, lastNumberingInstance);
            }

            return(numberId);
        }
Ejemplo n.º 26
0
        public static void ApplyFooter(WordprocessingDocument doc)
        {
            // Get the main document part.
            MainDocumentPart mainDocPart = doc.MainDocumentPart;

            FooterPart footerPart1 = mainDocPart.AddNewPart <FooterPart>("r98");



            Footer footer1 = new Footer();

            Table table = new Table();

            TableProperties props = new TableProperties(
                new TableWidth()
            {
                Width = "100%", Type = TableWidthUnitValues.Auto
            });

            props.BiDiVisual = new BiDiVisual();

            table.AppendChild <TableProperties>(props);
            var tr = new TableRow();
            //cell 1
            var tc = new TableCell();

            tc.Append(CreateParagraph("أملاه:	"));
            tc.Append(CreateParagraph("كتبه :	"));
            var tableWidth = new TableCellWidth
            {
                Type  = TableWidthUnitValues.Auto,
                Width = "50%"
            };

            tc.Append(new TableCellProperties(tableWidth));

            //cell 2
            var tc2 = new TableCell();

            tc2.Append(CreateParagraph(" راجع الأمـلاء  :  "));
            tc2.Append(CreateParagraph("راجع الكتابة   : "));
            tc2.Append(CreateParagraph("رئيس لجنة الإدارة         : "));

            var tableWidth2 = new TableCellWidth
            {
                Type  = TableWidthUnitValues.Auto,
                Width = "50%"
            };

            tc2.Append(new TableCellProperties(tableWidth2));


            tr.Append(tc);
            tr.Append(tc2);
            table.Append(tr);

            footer1.Append(table);


            footerPart1.Footer = footer1;



            SectionProperties sectionProperties1 = mainDocPart.Document.Body.Descendants <SectionProperties>().FirstOrDefault();

            if (sectionProperties1 == null)
            {
                sectionProperties1 = new SectionProperties()
                {
                };
                mainDocPart.Document.Body.Append(sectionProperties1);
            }
            FooterReference footerReference1 = new FooterReference()
            {
                Type = DocumentFormat.OpenXml.Wordprocessing.HeaderFooterValues.Default, Id = "r98"
            };


            sectionProperties1.InsertAt(footerReference1, 0);
        }
        private void InitNumberingIds()
        {
            NumberingDefinitionsPart numberingPart = mainPart.NumberingDefinitionsPart;
            int absNumIdRef = 0;

            // Ensure the numbering.xml file exists or any numbering or bullets list will results
            // in simple numbering list (1.   2.   3...)
            if (numberingPart == null)
            {
                numberingPart = numberingPart = mainPart.AddNewPart <NumberingDefinitionsPart>();
            }

            if (mainPart.NumberingDefinitionsPart.Numbering == null)
            {
                new Numbering().Save(numberingPart);
            }
            else
            {
                // The absNumIdRef Id is a required field and should be unique. We will loop through the existing Numbering definition
                // to retrieve the highest Id and reconstruct our own list definition template.
                foreach (var abs in numberingPart.Numbering.Elements <AbstractNum>())
                {
                    if (abs.AbstractNumberId.HasValue && abs.AbstractNumberId > absNumIdRef)
                    {
                        absNumIdRef = abs.AbstractNumberId;
                    }
                }
                absNumIdRef++;
            }

            // This minimal numbering definition has been inspired by the documentation OfficeXMLMarkupExplained_en.docx
            // http://www.microsoft.com/downloads/details.aspx?FamilyID=6f264d0b-23e8-43fe-9f82-9ab627e5eaa3&displaylang=en

            AbstractNum[] absNumChildren = new [] {
                //8 kinds of abstractnum + 1 multi-level.
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    StartNumberingValue = new StartNumberingValue()
                    {
                        Val = 1
                    },
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.Decimal
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "%1."
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef, AbstractNumDefinitionName = new AbstractNumDefinitionName()
                    {
                        Val = "decimal"
                    }
                },
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.Bullet
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "•"
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef + 1, AbstractNumDefinitionName = new AbstractNumDefinitionName()
                    {
                        Val = "disc"
                    }
                },
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.Bullet
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "▪"
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef + 2, AbstractNumDefinitionName = new AbstractNumDefinitionName()
                    {
                        Val = "square"
                    }
                },
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.Bullet
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "o"
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef + 3, AbstractNumDefinitionName = new AbstractNumDefinitionName()
                    {
                        Val = "circle"
                    }
                },
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    StartNumberingValue = new StartNumberingValue()
                    {
                        Val = 1
                    },
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.UpperLetter
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "%1."
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef + 4, AbstractNumDefinitionName = new AbstractNumDefinitionName()
                    {
                        Val = "upper-alpha"
                    }
                },
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    StartNumberingValue = new StartNumberingValue()
                    {
                        Val = 1
                    },
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.LowerLetter
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "%1."
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef + 5, AbstractNumDefinitionName = new AbstractNumDefinitionName()
                    {
                        Val = "lower-alpha"
                    }
                },
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    StartNumberingValue = new StartNumberingValue()
                    {
                        Val = 1
                    },
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.UpperRoman
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "%1."
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef + 6, AbstractNumDefinitionName = new AbstractNumDefinitionName()
                    {
                        Val = "upper-roman"
                    }
                },
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    StartNumberingValue = new StartNumberingValue()
                    {
                        Val = 1
                    },
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.LowerRoman
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "%1."
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef + 7, AbstractNumDefinitionName = new AbstractNumDefinitionName()
                    {
                        Val = "lower-roman"
                    }
                },
                // decimal-heading-multi
                // WARNING: only use this for headings
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    StartNumberingValue = new StartNumberingValue()
                    {
                        Val = 1
                    },
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.Decimal
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "%1."
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef + 8, AbstractNumDefinitionName = new AbstractNumDefinitionName()
                    {
                        Val = HEADING_NUMBERING_NAME
                    }
                }
            };

            // Check if we have already initialized our abstract nums
            // if that is the case, we should not add them again.
            // This supports a use-case where the HtmlConverter is called multiple times
            // on document generation, and needs to continue existing lists
            bool addNewAbstractNums = false;
            IEnumerable <AbstractNum> existingAbstractNums = numberingPart.Numbering.ChildElements.Where(e => e != null && e is AbstractNum).Cast <AbstractNum>();

            if (existingAbstractNums.Count() >= absNumChildren.Length)             // means we might have added our own already
            {
                foreach (var abstractNum in absNumChildren)
                {
                    // Check if we can find this in the existing document
                    addNewAbstractNums = addNewAbstractNums ||
                                         !existingAbstractNums.Any(a => a.AbstractNumDefinitionName != null && a.AbstractNumDefinitionName.Val.Value == abstractNum.AbstractNumDefinitionName.Val.Value);
                }
            }
            else
            {
                addNewAbstractNums = true;
            }

            if (addNewAbstractNums)
            {
                // this is not documented but MS Word needs that all the AbstractNum are stored consecutively.
                // Otherwise, it will apply the "NoList" style to the existing ListInstances.
                // This is the reason why I insert all the items after the last AbstractNum.
                int lastAbsNumIndex = 0;
                if (absNumIdRef > 0)
                {
                    lastAbsNumIndex = numberingPart.Numbering.ChildElements.Count - 1;
                    for (; lastAbsNumIndex >= 0; lastAbsNumIndex--)
                    {
                        if (numberingPart.Numbering.ChildElements[lastAbsNumIndex] is AbstractNum)
                        {
                            break;
                        }
                    }
                }

                for (int i = 0; i < absNumChildren.Length; i++)
                {
                    numberingPart.Numbering.InsertAt(absNumChildren[i], i + lastAbsNumIndex);
                }

                knownAbsNumIds = absNumChildren
                                 .ToDictionary(a => a.AbstractNumDefinitionName.Val.Value, a => a.AbstractNumberId.Value);
            }
            else
            {
                knownAbsNumIds = existingAbstractNums
                                 .Where(a => a.AbstractNumDefinitionName != null && a.AbstractNumDefinitionName.Val != null)
                                 .ToDictionary(a => a.AbstractNumDefinitionName.Val.Value, a => a.AbstractNumberId.Value);
            }

            // compute the next list instance ID seed. We start at 1 because 0 has a special meaning:
            // The w:numId can contain a value of 0, which is a special value that indicates that numbering was removed
            // at this level of the style hierarchy. While processing this markup, if the w:val='0',
            // the paragraph does not have a list item (http://msdn.microsoft.com/en-us/library/ee922775(office.14).aspx)
            nextInstanceID = 1;
            foreach (NumberingInstance inst in numberingPart.Numbering.Elements <NumberingInstance>())
            {
                if (inst.NumberID.Value > nextInstanceID)
                {
                    nextInstanceID = inst.NumberID;
                }
            }
            numInstances.Push(new KeyValuePair <int, int>(nextInstanceID, -1));

            numberingPart.Numbering.Save();
        }
Ejemplo n.º 28
0
        private void InitNumberingIds()
        {
            NumberingDefinitionsPart numberingPart = mainPart.NumberingDefinitionsPart;
            int absNumIdRef = 0;

            // Ensure the numbering.xml file exists or any numbering or bullets list will results
            // in simple numbering list (1.   2.   3...)
            if (numberingPart == null)
            {
                numberingPart = numberingPart = mainPart.AddNewPart <NumberingDefinitionsPart>();
            }

            if (mainPart.NumberingDefinitionsPart.Numbering == null)
            {
                new Numbering().Save(numberingPart);
            }
            else
            {
                // The absNumIdRef Id is a required field and should be unique. We will loop through the existing Numbering definition
                // to retrieve the highest Id and reconstruct our own list definition template.
                foreach (var abs in numberingPart.Numbering.Elements <AbstractNum>())
                {
                    if (abs.AbstractNumberId.HasValue && abs.AbstractNumberId > absNumIdRef)
                    {
                        absNumIdRef = abs.AbstractNumberId;
                    }
                }
                absNumIdRef++;
            }

            // This minimal numbering definition has been inspired by the documentation OfficeXMLMarkupExplained_en.docx
            // http://www.microsoft.com/downloads/details.aspx?FamilyID=6f264d0b-23e8-43fe-9f82-9ab627e5eaa3&displaylang=en

            DocumentFormat.OpenXml.OpenXmlElement[] absNumChildren = new [] {
                //8 kinds of abstractnum + 1 multi-level.
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    StartNumberingValue = new StartNumberingValue()
                    {
                        Val = 1
                    },
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.Decimal
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "%1."
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef
                },
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.Bullet
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "•"
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef + 1
                },
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.Bullet
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "▪"
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef + 2
                },
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.Bullet
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "o"
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef + 3
                },
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    StartNumberingValue = new StartNumberingValue()
                    {
                        Val = 1
                    },
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.UpperLetter
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "%1."
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef + 4
                },
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    StartNumberingValue = new StartNumberingValue()
                    {
                        Val = 1
                    },
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.LowerLetter
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "%1."
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef + 5
                },
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    StartNumberingValue = new StartNumberingValue()
                    {
                        Val = 1
                    },
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.UpperRoman
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "%1."
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef + 6
                },
                new AbstractNum(
                    new MultiLevelType()
                {
                    Val = MultiLevelValues.SingleLevel
                },
                    new Level {
                    StartNumberingValue = new StartNumberingValue()
                    {
                        Val = 1
                    },
                    NumberingFormat = new NumberingFormat()
                    {
                        Val = NumberFormatValues.LowerRoman
                    },
                    LevelIndex = 0,
                    LevelText  = new LevelText()
                    {
                        Val = "%1."
                    },
                    PreviousParagraphProperties = new PreviousParagraphProperties {
                        Indentation = new Indentation()
                        {
                            Left = "420", Hanging = "360"
                        }
                    }
                }
                    )
                {
                    AbstractNumberId = absNumIdRef + 7
                }
            };

            // this is not documented but MS Word needs that all the AbstractNum are stored consecutively.
            // Otherwise, it will apply the "NoList" style to the existing ListInstances.
            // This is the reason why I insert all the items after the last AbstractNum.
            int lastAbsNumIndex = 0;

            if (absNumIdRef > 0)
            {
                lastAbsNumIndex = numberingPart.Numbering.ChildElements.Count - 1;
                for (; lastAbsNumIndex >= 0; lastAbsNumIndex--)
                {
                    if (numberingPart.Numbering.ChildElements[lastAbsNumIndex] is AbstractNum)
                    {
                        break;
                    }
                }
            }

            for (int i = 0; i < absNumChildren.Length; i++)
            {
                numberingPart.Numbering.InsertAt(absNumChildren[i], i + lastAbsNumIndex);
            }

            // initializes the lookup
            knonwAbsNumIds = new Dictionary <String, Int32>()
            {
                { "disc", absNumIdRef + 1 }, { "square", absNumIdRef + 2 }, { "circle", absNumIdRef + 3 },
                { "upper-alpha", absNumIdRef + 4 }, { "lower-alpha", absNumIdRef + 5 },
                { "upper-roman", absNumIdRef + 6 }, { "lower-roman", absNumIdRef + 7 },
                { "decimal", absNumIdRef }
            };

            // compute the next list instance ID seed. We start at 1 because 0 has a special meaning:
            // The w:numId can contain a value of 0, which is a special value that indicates that numbering was removed
            // at this level of the style hierarchy. While processing this markup, if the w:val='0',
            // the paragraph does not have a list item (http://msdn.microsoft.com/en-us/library/ee922775(office.14).aspx)
            nextInstanceID = 1;
            foreach (NumberingInstance inst in numberingPart.Numbering.Elements <NumberingInstance>())
            {
                if (inst.NumberID.Value > nextInstanceID)
                {
                    nextInstanceID = inst.NumberID;
                }
            }
            numInstances.Push(nextInstanceID);

            numberingPart.Numbering.Save();
        }
Ejemplo n.º 29
0
        public static void AddStyle(MainDocumentPart mainPart, string styleId, string styleName, string colore, string font, int fontSize, bool isBold, bool isItalic, bool isUnderlined)
        {
            //Set the properties
            RunProperties rPr   = new RunProperties();
            Color         color = new Color()
            {
                Val = colore
            };
            RunFonts rFont = new RunFonts();

            rFont.Ascii = font /*"Arial"*/; // the font is Arial
            rPr.Append(color);
            rPr.Append(rFont);
            rPr.Append(new FontSize()
            {
                Val = (fontSize * 2).ToString()
            });
            if (isBold)
            {
                rPr.Append(new Bold());         // it is Bold
            }
            if (isItalic)
            {
                rPr.Append(new Italic());
            }
            if (isUnderlined)
            {
                rPr.Append(new Underline()
                {
                    Val = UnderlineValues.Single
                });
            }

            Style style = new Style();

            style.StyleId = styleId; //this is the ID of the style
            if (styleName == null || styleName.Length == 0)
            {
                styleName = styleId;
            }
            style.Append(new Name()
            {
                Val = styleName
            });                //this is the name of the new style
            style.Append(rPr); //we are adding properties previously defined

            // we have to add style that we have created to the StylePart
            StyleDefinitionsPart stylePart;

            if (mainPart.StyleDefinitionsPart == null)
            {
                stylePart        = mainPart.AddNewPart <StyleDefinitionsPart>();
                stylePart.Styles = new Styles();
            }
            else
            {
                stylePart = mainPart.StyleDefinitionsPart;
            }

            stylePart.Styles.Append(style);
            stylePart.Styles.Save(); // we save the style part
        }