Esempio n. 1
0
        private static void FillInEmptyFootnotesEndnotes(WordprocessingDocument wDoc)
        {
            XElement emptyFootnote = XElement.Parse(
                @"<w:p xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
  <w:pPr>
    <w:pStyle w:val='FootnoteText'/>
  </w:pPr>
  <w:r>
    <w:rPr>
      <w:rStyle w:val='FootnoteReference'/>
    </w:rPr>
    <w:footnoteRef/>
  </w:r>
</w:p>");

            XElement emptyEndnote = XElement.Parse(
                @"<w:p xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
  <w:pPr>
    <w:pStyle w:val='EndnoteText'/>
  </w:pPr>
  <w:r>
    <w:rPr>
      <w:rStyle w:val='EndnoteReference'/>
    </w:rPr>
    <w:endnoteRef/>
  </w:r>
</w:p>");

            FootnotesPart footnotePart = wDoc.MainDocumentPart.FootnotesPart;

            if (footnotePart != null)
            {
                XElement fnRoot = footnotePart.GetXDocument().Root ?? throw new ArgumentException();
                foreach (XElement fn in fnRoot.Elements(W.footnote))
                {
                    if (!fn.HasElements)
                    {
                        fn.Add(emptyFootnote);
                    }
                }

                footnotePart.PutXDocument();
            }

            EndnotesPart endnotePart = wDoc.MainDocumentPart.EndnotesPart;

            if (endnotePart != null)
            {
                XElement fnRoot = endnotePart.GetXDocument().Root ?? throw new ArgumentException();
                foreach (XElement fn in fnRoot.Elements(W.endnote))
                {
                    if (!fn.HasElements)
                    {
                        fn.Add(emptyEndnote);
                    }
                }

                endnotePart.PutXDocument();
            }
        }
        /// <summary>
        /// delete the footnotes in a file
        /// </summary>
        /// <param name="docName"></param>
        /// <returns></returns>
        public static bool RemoveFootnotes(string docName)
        {
            fWorked = false;

            using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(docName, true))
            {
                FootnotesPart fnp = wdDoc.MainDocumentPart.FootnotesPart;
                if (fnp != null)
                {
                    var footnotes  = fnp.Footnotes.Elements <Footnote>();
                    var references = wdDoc.MainDocumentPart.Document.Body.Descendants <FootnoteReference>().ToArray();

                    foreach (var reference in references)
                    {
                        reference.Remove();
                    }

                    foreach (var footnote in footnotes)
                    {
                        footnote.Remove();
                    }
                }

                wdDoc.MainDocumentPart.Document.Save();
                fWorked = true;
            }

            return(fWorked);
        }
Esempio n. 3
0
        private static void ChangeFootnoteEndnoteReferencesToUniqueRange(
            WordprocessingDocument wDoc,
            int startingIdForFootnotesEndnotes)
        {
            MainDocumentPart mainDocPart   = wDoc.MainDocumentPart;
            FootnotesPart    footnotesPart = wDoc.MainDocumentPart.FootnotesPart;
            EndnotesPart     endnotesPart  = wDoc.MainDocumentPart.EndnotesPart;

            XElement document =
                mainDocPart.GetXDocument().Root ?? throw new OpenXmlPowerToolsException("Invalid document.");

            XElement footnotes = footnotesPart?.GetXDocument().Root;
            XElement endnotes  = endnotesPart?.GetXDocument().Root;

            IEnumerable <XElement> references = document
                                                .Descendants()
                                                .Where(d => d.Name == W.footnoteReference || d.Name == W.endnoteReference);

            foreach (XElement r in references)
            {
                var    oldId = (string)r.Attribute(W.id);
                string newId = startingIdForFootnotesEndnotes.ToString();
                startingIdForFootnotesEndnotes++;
                r.SetAttributeValue(W.id, newId);
                if (r.Name == W.footnoteReference)
                {
                    XElement fn = footnotes?
                                  .Elements()
                                  .FirstOrDefault(e => (string)e.Attribute(W.id) == oldId);

                    if (fn == null)
                    {
                        throw new OpenXmlPowerToolsException("Invalid document");
                    }

                    fn.SetAttributeValue(W.id, newId);
                }
                else
                {
                    XElement en = endnotes?
                                  .Elements()
                                  .FirstOrDefault(e => (string)e.Attribute(W.id) == oldId);

                    if (en == null)
                    {
                        throw new OpenXmlPowerToolsException("Invalid document");
                    }

                    en.SetAttributeValue(W.id, newId);
                }
            }

            mainDocPart.PutXDocument();
            footnotesPart?.PutXDocument();
            endnotesPart?.PutXDocument();
        }
Esempio n. 4
0
        private static void RemoveExistingPowerToolsMarkup(WordprocessingDocument wDoc)
        {
            wDoc.MainDocumentPart
            .GetXDocument()
            .Root?
            .Descendants()
            .Attributes()
            .Where(a => a.Name.Namespace == PtOpenXml.pt)
            .Where(a => a.Name != PtOpenXml.Unid)
            .Remove();

            wDoc.MainDocumentPart.PutXDocument();

            FootnotesPart fnPart = wDoc.MainDocumentPart.FootnotesPart;

            if (fnPart != null)
            {
                XDocument fnXDoc = fnPart.GetXDocument();
                fnXDoc
                .Root?
                .Descendants()
                .Attributes()
                .Where(a => a.Name.Namespace == PtOpenXml.pt)
                .Where(a => a.Name != PtOpenXml.Unid)
                .Remove();

                fnPart.PutXDocument();
            }

            EndnotesPart enPart = wDoc.MainDocumentPart.EndnotesPart;

            if (enPart != null)
            {
                XDocument enXDoc = enPart.GetXDocument();
                enXDoc
                .Root?
                .Descendants()
                .Attributes()
                .Where(a => a.Name.Namespace == PtOpenXml.pt)
                .Where(a => a.Name != PtOpenXml.Unid)
                .Remove();

                enPart.PutXDocument();
            }
        }
Esempio n. 5
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);
        }
Esempio n. 6
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>
        protected 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);
        }
Esempio 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("FootnoteText", StyleValues.Paragraph)
                }
            },
                        markerRun = new Run(
                            new RunProperties {
                RunStyle = new RunStyle()
                {
                    Val = htmlStyles.GetStyle("FootnoteReference", 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("Hyperlink", StyleValues.Character)
                    }
                },
                             new Text(description)));
                p.Append(h);
            }
            else
            {
                p.Append(new Run(
                             new Text(description)
                {
                    Space = SpaceProcessingModeValues.Preserve
                }));
            }

            fpart.Footnotes.Save();

            return(footnotesRef);
        }
Esempio n. 8
0
        private void SetupStyles()
        {
            WordprocessingCommentsPart commentsPart        = AddTemplatePart <WordprocessingCommentsPart>(this.document, CommentsStyleResource);
            EndnotesPart             endNotesPart          = AddTemplatePart <EndnotesPart>(this.document, EndNotesStyleResource);
            FontTablePart            fontTablePart         = AddTemplatePart <FontTablePart>(this.document, FontsTableStyleResource);
            FootnotesPart            footnotesPart         = AddTemplatePart <FootnotesPart>(this.document, FootNotesStyleResource);
            HeaderPart               headerPart            = AddTemplatePart <HeaderPart>(this.document, HeaderStyleResource);
            DocumentSettingsPart     settingsPart          = AddTemplatePart <DocumentSettingsPart>(this.document, SettingsStyleResource);
            StyleDefinitionsPart     styles                = AddTemplatePart <StyleDefinitionsPart>(this.document, StylesStyleResource);
            StylesWithEffectsPart    stylesWithEffectsPart = AddTemplatePart <StylesWithEffectsPart>(this.document, StylesWithEffectsStyleResource);
            WebSettingsPart          webSettingsPart       = AddTemplatePart <WebSettingsPart>(this.document, WebSettingsStyleResource);
            ThemePart                themePart             = AddTemplatePart <ThemePart>(this.document, ThemeStyleResource);
            NumberingDefinitionsPart numberingPart         = AddTemplatePart <NumberingDefinitionsPart>(this.document, NumberingStyleResource);

            // Initialize the comments manager with the comments part
            this.commentManager = new CommentManager(commentsPart.Comments);

            // Initialize the footer
            string     footerTitle      = this.implementationGuide.GetDisplayName();
            DateTime   footerDate       = this.implementationGuide.PublishDate != null ? this.implementationGuide.PublishDate.Value : DateTime.Now;
            string     footerDateString = footerDate.ToString("m");
            FooterPart newFooterPart    = this.document.MainDocumentPart.AddNewPart <FooterPart>();
            Footer     newFooter        = new Footer();
            Paragraph  pFooter          = new Paragraph(
                new ParagraphProperties(
                    new ParagraphStyleId()
            {
                Val = "Footer"
            }));

            pFooter.Append(
                new Run(
                    new Text(footerTitle)),
                new Run(
                    new TabChar(),
                    new Text(footerDateString)
            {
                Space = SpaceProcessingModeValues.Preserve
            }),
                new Run(
                    new TabChar(),
                    new Text("Page ")
            {
                Space = SpaceProcessingModeValues.Preserve
            }),
                new Run(
                    new FieldChar()
            {
                FieldCharType = FieldCharValues.Begin
            }),
                new Run(
                    new FieldCode(" PAGE ")
            {
                Space = SpaceProcessingModeValues.Preserve
            }),
                new Run(
                    new FieldChar()
            {
                FieldCharType = FieldCharValues.Separate
            }),
                new Run(
                    new RunProperties(
                        new NoProof()),
                    new Text("54")),
                new Run(
                    new FieldChar()
            {
                FieldCharType = FieldCharValues.End
            }));
            newFooter.Append(pFooter);
            newFooterPart.Footer = newFooter;

            // Add numbering for templates
            foreach (Template cTemplate in this.templates)
            {
                NumberingInstance ni = new NumberingInstance(
                    new AbstractNumId()
                {
                    Val = 3
                })
                {
                    NumberID = GenerationConstants.BASE_TEMPLATE_INDEX + (int)cTemplate.Id
                };

                for (int i = 0; i < 9; i++)
                {
                    ni.Append(new LevelOverride(
                                  new StartOverrideNumberingValue()
                    {
                        Val = 1
                    })
                    {
                        LevelIndex = i
                    });
                }

                numberingPart.Numbering.Append(ni);
            }
        }
Esempio n. 9
0
        public static void GenerateFootnotesPart1Content(FootnotesPart footnotesPart1)
        {
            var footnotes1 = new Footnotes {
                MCAttributes = new MarkupCompatibilityAttributes()
                {
                    Ignorable = "w14 w15 w16se w16cid wp14"
                }
            };

            footnotes1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
            footnotes1.AddNamespaceDeclaration("cx", "http://schemas.microsoft.com/office/drawing/2014/chartex");
            footnotes1.AddNamespaceDeclaration("cx1", "http://schemas.microsoft.com/office/drawing/2015/9/8/chartex");
            footnotes1.AddNamespaceDeclaration("cx2", "http://schemas.microsoft.com/office/drawing/2015/10/21/chartex");
            footnotes1.AddNamespaceDeclaration("cx3", "http://schemas.microsoft.com/office/drawing/2016/5/9/chartex");
            footnotes1.AddNamespaceDeclaration("cx4", "http://schemas.microsoft.com/office/drawing/2016/5/10/chartex");
            footnotes1.AddNamespaceDeclaration("cx5", "http://schemas.microsoft.com/office/drawing/2016/5/11/chartex");
            footnotes1.AddNamespaceDeclaration("cx6", "http://schemas.microsoft.com/office/drawing/2016/5/12/chartex");
            footnotes1.AddNamespaceDeclaration("cx7", "http://schemas.microsoft.com/office/drawing/2016/5/13/chartex");
            footnotes1.AddNamespaceDeclaration("cx8", "http://schemas.microsoft.com/office/drawing/2016/5/14/chartex");
            footnotes1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            footnotes1.AddNamespaceDeclaration("aink", "http://schemas.microsoft.com/office/drawing/2016/ink");
            footnotes1.AddNamespaceDeclaration("am3d", "http://schemas.microsoft.com/office/drawing/2017/model3d");
            footnotes1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
            footnotes1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            footnotes1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
            footnotes1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
            footnotes1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
            footnotes1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
            footnotes1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
            footnotes1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
            footnotes1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
            footnotes1.AddNamespaceDeclaration("w15", "http://schemas.microsoft.com/office/word/2012/wordml");
            footnotes1.AddNamespaceDeclaration("w16cid", "http://schemas.microsoft.com/office/word/2016/wordml/cid");
            footnotes1.AddNamespaceDeclaration("w16se", "http://schemas.microsoft.com/office/word/2015/wordml/symex");
            footnotes1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
            footnotes1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
            footnotes1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
            footnotes1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");

            var footnote1 = new Footnote {
                Type = FootnoteEndnoteValues.Separator, Id = -1
            };

            var paragraph274 = new Paragraph {
                RsidParagraphAddition = "003C529E", RsidRunAdditionDefault = "003C529E", ParagraphId = "46435F23", TextId = "77777777"
            };

            var paragraphProperties177 = new ParagraphProperties();
            var spacingBetweenLines173 = new SpacingBetweenLines {
                After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto
            };

            paragraphProperties177.Append(spacingBetweenLines173);

            var run403         = new Run();
            var separatorMark2 = new SeparatorMark();

            run403.Append(separatorMark2);

            paragraph274.Append(paragraphProperties177);
            paragraph274.Append(run403);

            footnote1.Append(paragraph274);

            var footnote2 = new Footnote {
                Type = FootnoteEndnoteValues.ContinuationSeparator, Id = 0
            };

            var paragraph275 = new Paragraph {
                RsidParagraphAddition = "003C529E", RsidRunAdditionDefault = "003C529E", ParagraphId = "69C342F4", TextId = "77777777"
            };

            var paragraphProperties178 = new ParagraphProperties();
            var spacingBetweenLines174 = new SpacingBetweenLines {
                After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto
            };

            paragraphProperties178.Append(spacingBetweenLines174);

            var run404 = new Run();
            var continuationSeparatorMark2 = new ContinuationSeparatorMark();

            run404.Append(continuationSeparatorMark2);

            paragraph275.Append(paragraphProperties178);
            paragraph275.Append(run404);

            footnote2.Append(paragraph275);

            footnotes1.Append(footnote1);
            footnotes1.Append(footnote2);

            footnotesPart1.Footnotes = footnotes1;
        }
Esempio n. 10
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(FootnotesPart fpart, StyleDefinitionsPart stylePart, string description)
        {
            var footnotesRef = 0;

            if (fpart.Footnotes == null)
            {
                // Insert a new Footnotes reference
                new Footnotes(
                    new Footnote(
                        new Paragraph(
                            new ParagraphProperties(
                                new SpacingBetweenLines()
                {
                    After = "0", Before = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto
                }),
                            new Run2(
                                new SeparatorMark())
                            )
                        )
                {
                    Type = FootnoteEndnoteValues.Separator, Id = -1
                },
                    new Footnote(
                        new Paragraph(
                            new ParagraphProperties(
                                new SpacingBetweenLines()
                {
                    Before = "0", After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto
                }),
                            new Run2(
                                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 p in fpart.Footnotes.Elements <Footnote>())
                {
                    if (p.Id.HasValue && p.Id > footnotesRef)
                    {
                        footnotesRef = (int)p.Id.Value;
                    }
                }
                footnotesRef++;
            }

            Run2      markerRun;
            Paragraph footnotePara = new Paragraph(
                new ParagraphProperties(
                    new ParagraphStyleId()
            {
                Val = GetStyleIdFromStyleName(stylePart, "My Footnote Text")
            }),
                markerRun = new Run2(
                    new RunProperties(
                        new RunStyle()
            {
                Val = GetStyleIdFromStyleName(stylePart, "My Footnote Reference")
            }),
                    new FootnoteReferenceMark())
                );

            AddText(footnotePara, description, stylePart);

            fpart.Footnotes.AppendChild(
                new Footnote(
                    footnotePara
                    )
            {
                Id = footnotesRef
            });

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

            return(footnotesRef);
        }
Esempio n. 11
0
        public void ProcessRequest(HttpContext context)
        {
            var surah    = int.Parse(context.Request["surah"] ?? "1");
            var fileName = "Quran_Surah_" + surah + ".docx";

            //context.Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            context.Response.AppendHeader("Content-Type", "application/msword");
            context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
            //context.Response.ContentEncoding = Encoding.UTF8;

            // Open a Wordprocessing document for editing.
            var path = context.Server.MapPath("~/App_Data/" + fileName);

            if (File.Exists(path))
            {
                File.Delete(path);
            }

            File.Copy(context.Server.MapPath("~/App_Data/Template.docx"), path);
            using (WordprocessingDocument package = WordprocessingDocument.Open(path, true))
            {
                MainDocumentPart     main      = package.MainDocumentPart;
                StyleDefinitionsPart stylePart = main.StyleDefinitionsPart;
                FootnotesPart        fpart     = main.FootnotesPart;
                Body body = main.Document.Body;


                //MainDocumentPart main = package.AddMainDocumentPart();
                //StyleDefinitionsPart stylePart = AddStylesPartToPackage(package);
                //CreateDefaultStyles(stylePart);
                //FootnotesPart fpart = main.AddNewPart<FootnotesPart>();

                //main.Document = new Document();
                //Body body = main.Document.AppendChild<Body>(new Body());
                //body.AppendChild(
                //    new SectionProperties(
                //        new FootnoteProperties(
                //            new NumberingFormat() { Val = NumberFormatValues.LowerLetter },
                //            new NumberingRestart() { Val = RestartNumberValues.EachPage })));

                using (var quran = new QuranObjects.QuranContext())
                {
                    var translations  = from mt in quran.MyTranslations where mt.SurahNo == surah select mt;
                    var lastVersePara = new Paragraph();

                    foreach (var translation in translations)
                    {
                        // Emit headings as Heading 2
                        if (translation.Heading.Length > 0)
                        {
                            var headingPara = body.AppendChild <Paragraph>(
                                new Paragraph(new Run2(new Text2(translation.Heading))));
                            ApplyStyleToParagraph(stylePart, GetStyleIdFromStyleName(stylePart, "My Heading 2"), headingPara);

                            if (lastVersePara.ChildElements.OfType <Run>().Count() == 0)
                            {
                                lastVersePara.Remove();
                            }

                            lastVersePara = body.AppendChild <Paragraph>(new Paragraph());
                            ApplyStyleToParagraph(stylePart, GetStyleIdFromStyleName(stylePart, "Verse"), lastVersePara);
                        }

                        // Find all footnotes from the footnote translation
                        var footnotes = new List <string>();
                        var matches   = new Regex(@"(\*+)([^\*]*)").Matches(translation.Footnote);
                        foreach (Match match in matches)
                        {
                            var footnoteText = match.Groups[2].Value;
                            footnotes.Add(footnoteText);
                        }

                        // Generate the verse number
                        var translationAyahNoEnglish = translation.AyahNo.ToString();
                        var banglaVerseNo            = new String(Array.ConvertAll(translationAyahNoEnglish.ToCharArray(), (c) => (char)('০' + (char)(c - '0'))));

                        AddSuperscriptText(lastVersePara, banglaVerseNo);
                        AddText(lastVersePara, " ", stylePart);

                        // Emit the translation while generating the footnote references
                        var translationFootnotes = new Regex(@"([^\*]*)(\*+)([^\*]*)").Matches(translation.Translation);
                        if (translationFootnotes.Count == 0)
                        {
                            AddText(lastVersePara, translation.Translation, stylePart);

                            // If there was no footnote marker in the translation text, then
                            // add the entire footnote at the end of the translation
                            if (translation.Footnote.Trim().Length > 0)
                            {
                                var footnoteId = AddFootnoteReference(fpart, stylePart, translation.Footnote.Replace("*", ""));
                                AddFootnote(lastVersePara, footnoteId, stylePart);
                            }
                        }

                        foreach (Match match in translationFootnotes)
                        {
                            var beforeText     = match.Groups[1].Value;
                            var footnoteMarker = match.Groups[2].Value;
                            var afterText      = match.Groups[3].Value;

                            AddText(lastVersePara, beforeText, stylePart);

                            // Create a footnote first and then add a footnote reference
                            var footnoteId = AddFootnoteReference(fpart, stylePart, footnotes[footnoteMarker.Length - 1]);
                            AddFootnote(lastVersePara, footnoteId, stylePart);
                            AddText(lastVersePara, afterText, stylePart);
                        }

                        if (lastVersePara.Parent == null)
                        {
                            ApplyStyleToParagraph(stylePart, GetStyleIdFromStyleName(stylePart, "Verse"), lastVersePara);
                            body.AppendChild(lastVersePara);
                        }

                        if (translation.NewParaAfterThis)
                        {
                            lastVersePara = body.AppendChild <Paragraph>(new Paragraph());
                            ApplyStyleToParagraph(stylePart, GetStyleIdFromStyleName(stylePart, "Verse"), lastVersePara);
                        }
                        else
                        {
                            AddText(lastVersePara, " ", stylePart);
                        }
                    }

                    if (lastVersePara.Parent == null)
                    {
                        body.AppendChild(lastVersePara);
                    }
                }

                package.MainDocumentPart.Document.Save();


                OpenXmlValidator validator = new OpenXmlValidator();
                int count = 0;
                foreach (ValidationErrorInfo error in
                         validator.Validate(package))
                {
                    count++;
                    Debug.WriteLine("Error " + count);
                    Debug.WriteLine("Description: " + error.Description);
                    Debug.WriteLine("ErrorType: " + error.ErrorType);
                    Debug.WriteLine("Node: " + error.Node);
                    Debug.WriteLine("Path: " + error.Path.XPath);
                    Debug.WriteLine("Part: " + error.Part.Uri);
                    Debug.WriteLine("-------------------------------------------");
                }
            }

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

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

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

#if DEBUG
                //--------DEBUG PROCESSING -------------
                if (false)
                {
                    using (StreamWriter debugoutput = new StreamWriter(outputDocumentFullName + ".debug.txt"))
                    {
                        foreach (var text in texts)
                        {
                            debugoutput.WriteLine(text.Text);
                        }
                        debugoutput.Flush();
                        debugoutput.Close();
                    }
                }
                //--------END DEBUG --------------------
#endif

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

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

                FootnotesPart footnotesPart = doc.MainDocumentPart.FootnotesPart;
                if (footnotesPart != null)
                {
                    var footnotes = footnotesPart.Footnotes.Elements <Footnote>();
                    foreach (var footnote in footnotes)
                    {
                        texts.AddRange(footnote.Descendants <DocumentFormat.OpenXml.Wordprocessing.Text>().Where(text => !string.IsNullOrEmpty(text.Text) && text.Text.Length > 0));
                    }
                }

                EndnotesPart endnotesPart = doc.MainDocumentPart.EndnotesPart;
                if (endnotesPart != null)
                {
                    var endnotes = endnotesPart.Endnotes.Elements <DocumentFormat.OpenXml.Wordprocessing.Endnote>();
                    foreach (var endnote in endnotes)
                    {
                        texts.AddRange(endnote.Descendants <DocumentFormat.OpenXml.Wordprocessing.Text>().Where(text => !string.IsNullOrEmpty(text.Text) && text.Text.Length > 0));
                    }
                }



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

                var exceptions = new ConcurrentQueue <Exception>();

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

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

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

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

                //doc.MainDocumentPart.PutXDocument();
            }
        }