コード例 #1
0
ファイル: _WordBuilder.cs プロジェクト: FerHenrique/Owl
        public void CreateDocument(string filePath)
        {
            var creator = new DocumentCreator();
            this._package = creator.CreatePackage(filePath);

            CreateCommonStyles();
        }
コード例 #2
0
ファイル: InvoiceCreator.cs プロジェクト: CGHill/Hard-To-Find
        // Adds child parts and generates content of the specified part.
        private void CreateParts(WordprocessingDocument document)
        {
            ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3");
            GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1);

            MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart();
            GenerateMainDocumentPart1Content(mainDocumentPart1);

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

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

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

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

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

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

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

            SetPackageProperties(document);
        }
コード例 #3
0
        private static Stream WordprocessingDocumentToStream(WordprocessingDocument wordDoc)
        {
            MemoryStream mem = new MemoryStream();

            using (var resultDoc = WordprocessingDocument.Create(mem, wordDoc.DocumentType))
            {

                // copy parts from source document to new document
                foreach (var part in wordDoc.Parts)
                {
                    OpenXmlPart targetPart = resultDoc.AddPart(part.OpenXmlPart, part.RelationshipId); // that's recursive :-)
                }

                resultDoc.Package.Flush();
            }
            //resultDoc.Package.Close(); // must do this (or using), or the zip won't get created properly

            mem.Position = 0;

            return mem;

            //    byte[] bytes = new byte[mem.Length];
            //    mem.Read(bytes, 0, (int)mem.Length);
            //    mem.Close();

            //    //FileStream file = new FileStream(@"C:\Users\jharrop\Documents\tmp-test-docx\outs.docx", FileMode.Create, System.IO.FileAccess.Write);
            //    //byte[] bytes = new byte[mem.Length];
            //    //mem.Read(bytes, 0, (int)mem.Length);
            //    //file.Write(bytes, 0, bytes.Length);
            //    //file.Close();
            //    //mem.Close();

            //return bytes;

        }
コード例 #4
0
        public static GeneralDataProcessor CreateProcessor(WordprocessingDocument document, DCTDataProperty property)
        {
            if (property is DCTSimpleProperty)
                return new SimplePropertyProcessor(document, (DCTSimpleProperty)property);

            return new ComplexPropertyProcessor(document, (DCTComplexProperty)property);
        }
コード例 #5
0
ファイル: Generateinvoice.cs プロジェクト: vijaypaliwal/locum
        // Adds child parts and generates content of the specified part.
        private void CreateParts(WordprocessingDocument document)
        {
            ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3");
            GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1);

            MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart();
            GenerateMainDocumentPart1Content(mainDocumentPart1);

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

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

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

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

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

            mainDocumentPart1.AddHyperlinkRelationship(new System.Uri("mailto:[email protected]", System.UriKind.Absolute), true, "rId7");
            mainDocumentPart1.AddHyperlinkRelationship(new System.Uri("http://www.shivam.com", System.UriKind.Absolute), true, "rId6");
            mainDocumentPart1.AddHyperlinkRelationship(new System.Uri("mailto:[email protected]", System.UriKind.Absolute), true, "rId5");
            mainDocumentPart1.AddHyperlinkRelationship(new System.Uri("http://www.google.com", System.UriKind.Absolute), true, "rId4");
            SetPackageProperties(document);
        }
コード例 #6
0
ファイル: DocxParser.cs プロジェクト: sashaMilka/MultiReader
        public DocxParser(string fileName)
        {
            path = Path.GetTempPath() + Path.DirectorySeparatorChar + "tmp-" + DateTime.Now.Ticks.ToString();
            File.Copy(fileName, path);

            doc = WordprocessingDocument.Open(path, true);

            parsedFile = new ContentFile()
            {
                contentRaw = doc.MainDocumentPart.Document.InnerXml,
                contentText = ParseFileContent(XElement.Parse(doc.MainDocumentPart.Document.InnerXml))
            };

            SetMetadata(MetadataType.Author, doc.PackageProperties.Creator);
            SetMetadata(MetadataType.Description, doc.PackageProperties.Description);
            SetMetadata(MetadataType.Language, doc.PackageProperties.Language);
            SetMetadata(MetadataType.Subject, doc.PackageProperties.Subject);
            SetMetadata(MetadataType.Title, doc.PackageProperties.Title);
            SetMetadata(MetadataType.Type, doc.PackageProperties.ContentType);

            if (doc.PackageProperties.Created.HasValue)
                SetMetadata(MetadataType.PublishDate, doc.PackageProperties.Created.Value.ToString());

            LoadAllMetadata();
        }
コード例 #7
0
ファイル: WordFontApplicator.cs プロジェクト: Jaykul/pickles
 public FontTablePart AddFontTablePartToPackage(WordprocessingDocument doc)
 {
     var part = doc.MainDocumentPart.AddNewPart<FontTablePart>();
     var root = new Fonts();
     root.Save(part);
     return part;
 }
コード例 #8
0
        public string GetText(string docFilePath)
        {
            try
            {
                this.package = WordprocessingDocument.Open(docFilePath, true);

                StringBuilder sb = new StringBuilder();
                OpenXmlElement element = package.MainDocumentPart.Document.Body;
                if (element == null)
                {
                    return string.Empty;
                }

                sb.Append(GetPlainText(element));
                return sb.ToString(); 
            }
            catch (Exception e)
            {

                throw;
            }
            finally
            {
                GC.Collect();
            }
        }
コード例 #9
0
ファイル: TableCreator.cs プロジェクト: FerHenrique/Owl
        public void AddTable(WordprocessingDocument package, DataTable table, TableStyle tableStyle)
        {
            Body body = package.MainDocumentPart.Document.Body;

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

            // Set table width
            SetTableWidth(tableStyle, tbl);

            // Create a TableProperties object and specify its border information.
            TableProperties tblProp = CreateTableProperties();

            // Set table alignment
            SetTableAlignment(tableStyle.Alignment, tblProp);

            // Append the TableProperties object to the empty table.
            tbl.AppendChild<TableProperties>(tblProp);

            if (tableStyle.ShowTitle) {
                AddTitleRow(table, tableStyle, tbl);
            }

            if (tableStyle.ShowHeader) {
                AddHeaderRow(table, tbl, tableStyle);
            }

            AddRows(table, tableStyle, tbl, tblProp);

            // Append the final table to the document body
            body.Append(tbl);
        }
コード例 #10
0
ファイル: EmployerAddress.cs プロジェクト: stevesloka/bvcms
		// Adds child parts and generates content of the specified part.
		private void CreateParts(WordprocessingDocument document)
		{
			ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3");
			GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1);

			MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart();
			GenerateMainDocumentPart1Content(mainDocumentPart1);

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

			StylesWithEffectsPart stylesWithEffectsPart1 = mainDocumentPart1.AddNewPart<StylesWithEffectsPart>("rId2");
			GenerateStylesWithEffectsPart1Content(stylesWithEffectsPart1);

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

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

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

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

		}
コード例 #11
0
 /// <summary>
 /// Constructor for creating a new document.
 /// </summary>
 /// <param name="filePath">Path to where the new file should be created.</param>
 public OpenXmlHelper(string filePath)
 {
     _filePath = filePath;
     if (File.Exists(filePath))
     {
         _package = WordprocessingDocument.Open(filePath, true);
         //TODO: ADD SEPERATOR TO OPENED DOCUMENT BEFORE APPENDING
         Debug.WriteLine("Opened existing file {0}", filePath);
         _document = _package.MainDocumentPart.Document;
     }
     else
     {
         _package = WordprocessingDocument.Create(_filePath, WordprocessingDocumentType.Document);
         if (File.Exists(_filePath))
         {
             MainDocumentPart main = _package.AddMainDocumentPart();
             main.Document = new Document();
             Document document = main.Document;
             Body body = document.AppendChild(new Body());
             _document = _package.MainDocumentPart.Document;
             _document.Save();
         }
         else
         {
             Debug.WriteLine("Failed to create the file: {0}", filePath);
         }
     }
 }
コード例 #12
0
        public WordDocumentImageManipulator(WordprocessingDocument doc)
        {

            // Open the document as editable.
            Document = doc;

        }
コード例 #13
0
        /// <summary>
        /// Initialize the WordDocumentImageManipulator instance.
        /// </summary>
        /// <param name="path">
        /// The document file path.
        /// </param>
        public WordDocumentImageManipulator(FileInfo path)
        {

            // Open the document as editable.
            Document = WordprocessingDocument.Open(path.FullName, true);

        }
コード例 #14
0
ファイル: DocBuilder.cs プロジェクト: silmarion/WPDHelper
        public void GenerateWordDocument(string docName, SessionData sessionObjects, AdditionalData additionalObjects)
        {
            _sessionObjects = sessionObjects;
            _additionalObjects = additionalObjects;
            //var openS = new OpenSettings();
            //openS.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(
            //    MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2007);
            //using (_wordDocument = WordprocessingDocument.Open(docName, true, openS))
            using (_wordDocument = WordprocessingDocument.Create(docName, WordprocessingDocumentType.Document))
            {
                InitilizeDocument();

                GenerateTitlePage();
                GeneratePageTwo();
                GenerateChapterOne();
                GenerateChapterTwo();
                GenerateChapterThree();
                GenerateChapterFour();
                GenerateChapterFive();
                GenerateChapterSix();
                GenerateChapterSeven();
                GenerateChapterEight();
                GenerateChapterNine();
                GenerateChapterTen();
                var numberingDefinitionsPart = _mainPart.AddNewPart<NumberingDefinitionsPart>();
                numberingDefinitionsPart.Numbering = _numbering;
            }
        }
コード例 #15
0
 public static void SimplifyMarkup(WordprocessingDocument doc,
     SimplifyMarkupSettings settings)
 {
     SimplifyMarkupForPart(doc.MainDocumentPart, settings);
     SimplifyMarkupForPart(doc.MainDocumentPart.StyleDefinitionsPart, settings);
     SimplifyMarkupForPart(doc.MainDocumentPart.StylesWithEffectsPart, settings);
 }
コード例 #16
0
        internal DocxDocumentTableSchemeBuilder(WordprocessingDocument document, TableProperties contextTableProperties)
            : base(document)
        {
            table = new Table();

            if (contextTableProperties == null)
            {
                var borderType = new EnumValue<BorderValues>(BorderValues.Thick);
                var tblProp = new TableProperties(
                    new TableBorders(
                        new TopBorder {Val = borderType, Size = 1},
                        new BottomBorder {Val = borderType, Size = 1},
                        new LeftBorder {Val = borderType, Size = 1},
                        new RightBorder {Val = borderType, Size = 1},
                        new InsideHorizontalBorder {Val = borderType, Size = 1},
                        new InsideVerticalBorder {Val = borderType, Size = 1}
                        )
                    );
                table.AppendChild(tblProp);
            }
            else
                table.AppendChild(contextTableProperties);

            headerRow = new TableRow();
            table.AppendChild(headerRow);
            Aggregation.Add(table);
        }
コード例 #17
0
 public static string RetrieveListItem(WordprocessingDocument wordDoc,
     XElement paragraph, string bulletReplacementString)
 {
     string pt = paragraph.Elements(W.r).Elements(W.t).Select(e => e.Value)
         .StringConcatenate();
     NumberingDefinitionsPart numberingDefinitionsPart =
         wordDoc.MainDocumentPart.NumberingDefinitionsPart;
     if (numberingDefinitionsPart == null)
         return null;
     StyleDefinitionsPart styleDefinitionsPart = wordDoc.MainDocumentPart
         .StyleDefinitionsPart;
     if (styleDefinitionsPart == null)
         return null;
     XDocument numbering = numberingDefinitionsPart.GetXDocument();
     XDocument styles = styleDefinitionsPart.GetXDocument();
     ListItemInfo listItemInfo = GetListItemInfo(numbering, styles, paragraph);
     if (listItemInfo.IsListItem)
     {
         string lvlText = (string)listItemInfo.Lvl.Elements(W.lvlText)
             .Attributes(W.val).FirstOrDefault();
         int[] levelNumbers = GetLevelNumbers(numbering, styles, paragraph);
         paragraph.AddAnnotation(new LevelNumbers()
         {
             LevelNumbersArray = levelNumbers
         });
         string listItem = FormatListItem(listItemInfo.Lvl, levelNumbers, lvlText,
             bulletReplacementString);
         return listItem;
     }
     return null;
 }
コード例 #18
0
ファイル: BookmarkReplacer.cs プロジェクト: FerHenrique/Owl
        public void ReplaceBookmark(WordprocessingDocument package, string bookmark, string content)
        {
            IDictionary<String, BookmarkStart> bookmarkMap = new Dictionary<String, BookmarkStart>();

            foreach (BookmarkStart bookmarkStart in package.MainDocumentPart.RootElement.Descendants<BookmarkStart>()) {
                bookmarkMap[bookmarkStart.Name] = bookmarkStart;
            }

            foreach (BookmarkStart bookmarkStart in bookmarkMap.Values) {

                if (bookmarkStart.Name == bookmark) {

                    Run bookmarkText = bookmarkStart.NextSibling<Run>();
                    if (bookmarkText != null) {
                        bookmarkText.GetFirstChild<Text>().Text = content;
                    }
                    else {
                        var textElement = new Text(content);
                        var runElement = new Run(textElement);

                        bookmarkStart.InsertAfterSelf(runElement);
                    }
                }
            }
        }
コード例 #19
0
ファイル: FamilyDir.cs プロジェクト: stevesloka/bvcms
        // Adds child parts and generates content of the specified part.
        private void CreateParts(WordprocessingDocument document)
        {
            ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3");
            GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1);

            MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart();
            GenerateMainDocumentPart1Content(mainDocumentPart1);

            StylesWithEffectsPart stylesWithEffectsPart1 = mainDocumentPart1.AddNewPart<StylesWithEffectsPart>("rId3");
            GenerateStylesWithEffectsPart1Content(stylesWithEffectsPart1);

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

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

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

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

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

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

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

            documentSettingsPart1.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new System.Uri("file:///D:\\Downloads\\FamilyMergeDoc%20(2).dotx", System.UriKind.Absolute), "rId1");
        }
コード例 #20
0
        // todo
        // we want overload for this that takes WmlDocument, or whatever new class is.
        // also want ability to specify multiple options - a settings object - compare headers, footers, etc.
        //
        // Returns true if docs are the same, otherwise false.
        public static bool CompareDocuments(WordprocessingDocument doc1, WordprocessingDocument doc2)
        {
            XDocument doc1XDoc = doc1.MainDocumentPart.GetXDocument();
            XDocument doc2XDoc = doc2.MainDocumentPart.GetXDocument();
            if (CompareOpenXmlElements(doc1XDoc.Root, doc2XDoc.Root) == false)
                return false;

            // for the current use of this class, only need to compare the main document parts.
            #if false
            if (doc1.MainDocumentPart.HeaderParts.Count() != doc2.MainDocumentPart.HeaderParts.Count())
                return false;
            foreach (var pair in doc1
                .MainDocumentPart
                .HeaderParts
                .Zip(doc2.MainDocumentPart.HeaderParts, (d1, d2) =>
                    new
                    {
                        Doc1Header = d1,
                        Doc2Header = d2,
                    }))
            {
                if (CompareOpenXmlElements(pair.Doc1Header.GetXDocument().Root,
                    pair.Doc2Header.GetXDocument().Root) == false)
                    return false;
            }
            if (doc1.MainDocumentPart.FooterParts.Count() != doc2.MainDocumentPart.FooterParts.Count())
                return false;
            foreach (var pair in doc1
                .MainDocumentPart
                .FooterParts
                .Zip(doc2.MainDocumentPart.FooterParts, (d1, d2) =>
                    new
                    {
                        Doc1Footer = d1,
                        Doc2Footer = d2,
                    }))
            {
                if (CompareOpenXmlElements(pair.Doc1Footer.GetXDocument().Root,
                    pair.Doc2Footer.GetXDocument().Root) == false)
                    return false;
            }
            if ((doc1.MainDocumentPart.FootnotesPart == null) != (doc2.MainDocumentPart.FootnotesPart == null))
                return false;
            if (doc1.MainDocumentPart.FootnotesPart != null)
            {
                if (CompareOpenXmlElements(doc1.MainDocumentPart.FootnotesPart.GetXDocument().Root,
                    doc2.MainDocumentPart.FootnotesPart.GetXDocument().Root) == false)
                    return false;
            }
            if ((doc1.MainDocumentPart.EndnotesPart == null) != (doc2.MainDocumentPart.EndnotesPart == null))
                return false;
            if (doc1.MainDocumentPart.EndnotesPart != null)
            {
                if (CompareOpenXmlElements(doc1.MainDocumentPart.EndnotesPart.GetXDocument().Root,
                    doc2.MainDocumentPart.EndnotesPart.GetXDocument().Root) == false)
                    return false;
            }
            #endif
            return true;
        }
コード例 #21
0
ファイル: GenerateWord.ashx.cs プロジェクト: cometofsky/Quran
 // Add a StylesDefinitionsPart to the document.  Returns a reference to it.
 public static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument doc)
 {
     StyleDefinitionsPart part;
     part = doc.MainDocumentPart.AddNewPart<StyleDefinitionsPart>();
     Styles root = new Styles();
     root.Save(part);
     return part;
 }
コード例 #22
0
        public void ApplyHeaderAndFooter(WordprocessingDocument wordProcessingDocument)
        {
            var headerPart = wordProcessingDocument.MainDocumentPart.AddNewPart<HeaderPart>();
            this.ApplyHeader(headerPart);

            var footerPart = wordProcessingDocument.MainDocumentPart.AddNewPart<FooterPart>();
            this.ApplyFooter(footerPart);
        }
コード例 #23
0
ファイル: OxmlDocument.cs プロジェクト: cthiange/eagle
 public OxmlDocument(string oxml)
 {
     Stream packageStream = OpcHelper.GetPackageStreamFromOXML(oxml);
     this._wpDoc = WordprocessingDocument.Open(packageStream, true);
     this._paragraphs = this._wpDoc.MainDocumentPart
                                   .Document.Body.OfType<Paragraph>().ToList();
     this.UpdateMaxBookmarkID();
 }
コード例 #24
0
 /// <summary>
 /// Adds a set of styles in the styles.xml file
 /// </summary>
 /// <param name="xmlStyleDefinitions">Collection of style definitions</param>
 public static void AddStyleDefinition(WordprocessingDocument document, IEnumerable<XElement> xmlStyleDefinitions)
 {
     XDocument stylesPart = GetStylesDocument(document);
     foreach (XElement xmlStyleDefinition in xmlStyleDefinitions)
     {
         stylesPart.Root.Add(xmlStyleDefinition);
     }
 }
コード例 #25
0
 internal WordprocessingDocument CreateDocument(String fileName)
 {
     docxFile = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document);
     mainPart = docxFile.AddMainDocumentPart();
     docxFile.MainDocumentPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(new Body());
     body = docxFile.MainDocumentPart.Document.Body;
     return docxFile;
 }
コード例 #26
0
 /// <summary>
 /// Adds a displayBackgroundShape element to the settings file
 /// </summary>
 public static void AddBackgroundShapeElement(WordprocessingDocument document)
 {
     XDocument settingsDocument = document.MainDocumentPart.DocumentSettingsPart.GetXDocument();
     settingsDocument.Root.Add(
         new XElement(ns + "displayBackgroundShape")
     );
     document.MainDocumentPart.DocumentSettingsPart.PutXDocument();
 }
コード例 #27
0
        /// <summary>
        /// Open an Word XML document 
        /// </summary>
        /// <param name="docname">name of the document to be opened</param>
        public void OpenTheDocuemnt(string docname)
        {
            // open the word docx
            wordProcessingDocument = WordprocessingDocument.Open(docname, true);

            // get the Main Document part
            mainDocPart = wordProcessingDocument.MainDocumentPart;
        }
コード例 #28
0
 public WordTemplateRenderer(WordprocessingDocument document, QueryDescription queryDescription, Entity entity, CultureInfo culture, ISystemWordTemplate systemWordTemplate)
 {
     this.document = document;
     this.entity = entity;
     this.culture = culture;
     this.systemWordTemplate = systemWordTemplate;
     this.queryDescription = queryDescription;
 }
コード例 #29
0
        public DocxDocumentTagContextBuilder(WordprocessingDocument document, string tagName)
            : base(document)
        {
            _documentTags = DocumentTag.Get(document, tagName);

            foreach (DocumentTag documentTag in _documentTags)
                ClearBetweenElements(documentTag.Opening, documentTag.Closing);
            SaveDocument();
        }
コード例 #30
0
        public Document(String fileName)
        {
            this.FileName = fileName;
            docFileName = fileName + ".docx";

            packager = DocumentPackager.GetInstance();
            docxFile = packager.CreateDocument(docFileName);
            body = packager.GetBody();
        }
コード例 #31
0
    static void Main(string[] args)
    {
        var n      = DateTime.Now;
        var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second));

        tempDi.Create();

        DirectoryInfo di2 = new DirectoryInfo("../../");

        foreach (var file in di2.GetFiles("*.docx"))
        {
            file.CopyTo(Path.Combine(tempDi.FullName, file.Name));
        }

        List <string> filesToProcess = new List <string>();

        // Inserts a basic TOC before the first paragraph of the document
        using (WordprocessingDocument wdoc =
                   WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test01.docx"), true))
        {
            ReferenceAdder.AddToc(wdoc, "/w:document/w:body/w:p[1]",
                                  @"TOC \o '1-3' \h \z \u", null, null);
        }

        // Inserts a TOC after the title of the document
        using (WordprocessingDocument wdoc =
                   WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test02.docx"), true))
        {
            ReferenceAdder.AddToc(wdoc, "/w:document/w:body/w:p[2]",
                                  @"TOC \o '1-3' \h \z \u", null, null);
        }

        // Inserts a TOC with a different title
        using (WordprocessingDocument wdoc =
                   WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test03.docx"), true))
        {
            ReferenceAdder.AddToc(wdoc, "/w:document/w:body/w:p[1]",
                                  @"TOC \o '1-3' \h \z \u", "Table of Contents", null);
        }

        // Inserts a TOC that includes headings through level 4
        using (WordprocessingDocument wdoc =
                   WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test04.docx"), true))
        {
            ReferenceAdder.AddToc(wdoc, "/w:document/w:body/w:p[1]",
                                  @"TOC \o '1-4' \h \z \u", null, null);
        }

        // Inserts a table of figures
        using (WordprocessingDocument wdoc =
                   WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test05.docx"), true))
        {
            ReferenceAdder.AddTof(wdoc, "/w:document/w:body/w:p[2]",
                                  @"TOC \h \z \c ""Figure""", null);
        }

        // Inserts a basic TOC before the first paragraph of the document.
        // Test06.docx does not include a StylesWithEffects part.
        using (WordprocessingDocument wdoc =
                   WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test06.docx"), true))
        {
            ReferenceAdder.AddToc(wdoc, "/w:document/w:body/w:p[1]",
                                  @"TOC \o '1-3' \h \z \u", null, null);
        }

        // Inserts a TOA before the first paragraph of the document.
        using (WordprocessingDocument wdoc =
                   WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test07.docx"), true))
        {
            ReferenceAdder.AddToa(wdoc, "/w:document/w:body/w:p[2]",
                                  @"TOA \h \c ""1"" \p", null);
        }
    }
コード例 #32
0
ファイル: DocX2Epub.cs プロジェクト: Kiradien/EpubGenerate
        public override string ConvertToHtml(FileInfo file, EpubWriter writer)
        {
            this.LastStatus = $"Processing File: {file.Name}";
            byte[] byteArray = File.ReadAllBytes(file.FullName);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                memoryStream.Write(byteArray, 0, byteArray.Length);
                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(memoryStream, true))
                {
                    var pageTitle = file.FullName;
                    var part      = wDoc.CoreFilePropertiesPart;
                    if (part != null)
                    {
                        pageTitle = (string)part.GetXDocument().Descendants(DC.title).FirstOrDefault() ?? file.FullName;
                    }

                    HtmlConverterSettings settings = new HtmlConverterSettings()
                    {
                        AdditionalCss                       = "body { margin: 1cm auto; max-width: 20cm; padding: 0; }",
                        PageTitle                           = pageTitle,
                        FabricateCssClasses                 = true,
                        CssClassPrefix                      = "pt-",
                        RestrictToSupportedLanguages        = false,
                        RestrictToSupportedNumberingFormats = false,
                        ImageHandler                        = imageInfo =>
                        {
                            string             extension   = imageInfo.ContentType.Split('/')[1].ToLower();
                            SysImg.ImageFormat imageFormat = null;
                            if (extension == "png")
                            {
                                imageFormat = SysImg.ImageFormat.Png;
                            }
                            else if (extension == "gif")
                            {
                                imageFormat = SysImg.ImageFormat.Gif;
                            }
                            else if (extension == "bmp")
                            {
                                imageFormat = SysImg.ImageFormat.Bmp;
                            }
                            else if (extension == "jpeg")
                            {
                                imageFormat = SysImg.ImageFormat.Jpeg;
                            }
                            else if (extension == "tiff")
                            {
                                // Convert tiff to gif.
                                extension   = "gif";
                                imageFormat = SysImg.ImageFormat.Gif;
                            }
                            else if (extension == "x-wmf")
                            {
                                extension   = "wmf";
                                imageFormat = SysImg.ImageFormat.Wmf;
                            }

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

                            string fileName = $"{Guid.NewGuid()}.{extension}";
                            string filePath = $"images/{fileName}";

                            using (var ms = new MemoryStream())
                            {
                                imageInfo.Bitmap.Save(ms, SysImg.ImageFormat.Png);
                                writer.AddFile(filePath, ms.ToArray(), EpubSharp.Format.EpubContentType.ImagePng);
                            }

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

                    var html = new XDocument(
                        new XDocumentType("html", null, null, null),
                        htmlElement);


                    var htmlString = html.ToString(SaveOptions.DisableFormatting);
                    return(htmlString);
                }
            }
        }
コード例 #33
0
        public static MemoryStream CreateOverTimeWorkApplication(OverTimeManagement overTimeManagement)
        {
            MemoryStream ms = new MemoryStream();

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                string templateFileName = "OverTimeWorkApplicationTemplate.docx";
                string tempFolderPath   = SPUtility.GetVersionedGenericSetupPath(@"TEMPLATE\LAYOUTS\RBVH.Stada.Intranet.ReportTemplates\OverTimeWorkApplication", 15);
                Directory.CreateDirectory(tempFolderPath);
                RemoveOldFiles(tempFolderPath, 1);

                string destFilePath = "";
                string newFileName  = string.Format("{0}-{1}.docx", "OverTimeWorkApplication", DateTime.Now.Ticks);
                destFilePath        = DownloadFile(SPContext.Current.Site.RootWeb.Url, "Shared Documents", templateFileName, tempFolderPath, newFileName);

                try
                {
                    using (WordprocessingDocument wordProcessingDoc = WordprocessingDocument.Open(destFilePath, true))
                    {
                        List <SdtContentCell> requestedby1 = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("requestedby");
                        requestedby1[0].FillTextBox(!string.IsNullOrEmpty(overTimeManagement.Requester.LookupValue) ? overTimeManagement.Requester.LookupValue : " ");

                        List <SdtBlock> requestedby2 = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByName("requestedby");
                        requestedby2[0].FillTextBox(!string.IsNullOrEmpty(overTimeManagement.Requester.LookupValue) ? overTimeManagement.Requester.LookupValue : " ");

                        List <SdtContentCell> department = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("department");
                        department[0].FillTextBox(!string.IsNullOrEmpty(overTimeManagement.CommonDepartment1066.LookupValue) ? overTimeManagement.CommonDepartment1066.LookupValue : " ");

                        var fromDate = overTimeManagement.OverTimeManagementDetailList.Min(x => x.OvertimeFrom).ToString("dd/MM/yyyy");
                        List <SdtContentCell> from = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("from");
                        from[0].FillTextBox(!string.IsNullOrEmpty(fromDate) ? fromDate : " ");

                        var toDate = overTimeManagement.OverTimeManagementDetailList.Max(x => x.OvertimeTo).ToString("dd/MM/yyyy");
                        List <SdtContentCell> to = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("to");
                        to[0].FillTextBox(!string.IsNullOrEmpty(toDate) ? toDate : " ");

                        List <SdtContentCell> place = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("place");
                        place[0].FillTextBox(!string.IsNullOrEmpty(overTimeManagement.Place) ? overTimeManagement.Place : " ");

                        List <SdtContentCell> quantity = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("quantity");
                        quantity[0].FillTextBox(overTimeManagement.SumOfEmployee + " ");

                        List <SdtContentCell> serving = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("serving");
                        serving[0].FillTextBox(overTimeManagement.SumOfMeal + " ");
                        List <SdtContentCell> others = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByNameFromTable("others");
                        others[0].FillTextBox(!string.IsNullOrEmpty(overTimeManagement.OtherRequirements) ? overTimeManagement.OtherRequirements : " ");

                        List <SdtBlock> tables = wordProcessingDoc.MainDocumentPart.Document.GetTextBoxByName("table1");
                        if (tables != null && tables.Count() > 0)
                        {
                            string templateStr = File.ReadAllText(Path.Combine(SPUtility.GetVersionedGenericSetupPath(@"TEMPLATE\LAYOUTS\RBVH.Stada.Intranet.ReportTemplates\XML", 15), "overtimetabletemplate.xml"));
                            Table newTable     = new Table(templateStr);

                            TableRow rowTemplate       = newTable.Descendants <TableRow>().Last();
                            List <string> propertyList = new List <string>()
                            {
                            };
                            for (int i = 0; i < overTimeManagement.OverTimeManagementDetailList.Count; i++)
                            {
                                var detail = overTimeManagement.OverTimeManagementDetailList[i];

                                TableRow newTableRow           = new TableRow();
                                newTableRow.TableRowProperties = new TableRowProperties(rowTemplate.TableRowProperties.OuterXml);

                                TableCell cellTemplate1 = rowTemplate.Descendants <TableCell>().ElementAt(0);
                                TableCell newTableCell1 = new TableCell(cellTemplate1.OuterXml);
                                newTableCell1.Descendants <Text>().First().Text = (i + 1).ToString();
                                newTableRow.Append(newTableCell1);

                                TableCell cellTemplate2 = rowTemplate.Descendants <TableCell>().ElementAt(1);
                                TableCell newTableCell2 = new TableCell(cellTemplate2.OuterXml);
                                newTableCell2.Descendants <Text>().First().Text = detail.Employee.LookupValue;
                                newTableRow.Append(newTableCell2);

                                TableCell cellTemplate3 = rowTemplate.Descendants <TableCell>().ElementAt(2);
                                TableCell newTableCell3 = new TableCell(cellTemplate3.OuterXml);
                                newTableCell3.Descendants <Text>().First().Text = detail.EmployeeID.LookupValue;
                                newTableRow.Append(newTableCell3);

                                TableCell cellTemplate4 = rowTemplate.Descendants <TableCell>().ElementAt(3);
                                TableCell newTableCell4 = new TableCell(cellTemplate4.OuterXml);
                                newTableCell4.Descendants <Text>().First().Text = WORKING_HOUR_IN_PDF;
                                newTableRow.Append(newTableCell4);

                                TableCell cellTemplate5 = rowTemplate.Descendants <TableCell>().ElementAt(4);
                                TableCell newTableCell5 = new TableCell(cellTemplate5.OuterXml);
                                newTableCell5.Descendants <Text>().First().Text = detail.OvertimeHours;
                                newTableRow.Append(newTableCell5);

                                TableCell cellTemplate6 = rowTemplate.Descendants <TableCell>().ElementAt(5);
                                TableCell newTableCell6 = new TableCell(cellTemplate6.OuterXml);
                                newTableCell6.Descendants <Text>().First().Text = detail.Task == null ? "" : detail.Task;
                                newTableRow.Append(newTableCell6);

                                TableCell cellTemplate7 = rowTemplate.Descendants <TableCell>().ElementAt(6);
                                TableCell newTableCell7 = new TableCell(cellTemplate7.OuterXml);
                                newTableCell7.Descendants <Text>().First().Text = detail.CompanyTransport;
                                newTableRow.Append(newTableCell7);

                                TableCell cellTemplate8 = rowTemplate.Descendants <TableCell>().ElementAt(7);
                                TableCell newTableCell8 = new TableCell(cellTemplate8.OuterXml);
                                newTableCell8.Descendants <Text>().First().Text = "";
                                newTableRow.Append(newTableCell8);

                                newTable.Append(newTableRow);
                            }

                            newTable.Descendants <TableRow>().ElementAt(1).Remove();
                            tables[0].Parent.InsertAfter(newTable, tables[0]);
                            tables[0].Remove();
                        }

                        wordProcessingDoc.MainDocumentPart.Document.Save();
                    }

                    using (FileStream file = new FileStream(destFilePath, FileMode.Open, FileAccess.Read))
                    {
                        byte[] bytes = new byte[file.Length];
                        file.Read(bytes, 0, (int)file.Length);
                        ms.Write(bytes, 0, (int)file.Length);
                    }
                }
                catch { }
            });

            return(ms);
        }
コード例 #34
0
        private void RemoveComments(string author)
        {
            // Get an existing Wordprocessing document.
            using (WordprocessingDocument document =
                       WordprocessingDocument.Open(MyDir + "Comments.docx", true))
            {
                WordprocessingCommentsPart commentPart =
                    document.MainDocumentPart.WordprocessingCommentsPart;

                // If no "WordprocessingCommentsPart" exists, there can be no comments.
                // Stop execution and return from the method.
                if (commentPart == null)
                {
                    return;
                }

                // Create a list of comments by the specified author.
                // If the author name is empty, then list all authors.
                List <Comment> commentsToDelete =
                    commentPart.Comments.Elements <Comment>().ToList();

                if (!String.IsNullOrEmpty(author))
                {
                    commentsToDelete = commentsToDelete.Where(c => c.Author == author).ToList();
                }

                IEnumerable <string> commentIds =
                    commentsToDelete.Select(r => r.Id.Value);

                foreach (Comment c in commentsToDelete)
                {
                    c.Remove();
                }

                // Save changes to the comments part.
                commentPart.Comments.Save();

                Document doc = document.MainDocumentPart.Document;

                // Delete the "CommentRangeStart" for each deleted comment in the main document.
                List <CommentRangeStart> commentRangeStartToDelete =
                    doc.Descendants <CommentRangeStart>().Where(c => commentIds.Contains(c.Id.Value)).ToList();

                foreach (CommentRangeStart c in commentRangeStartToDelete)
                {
                    c.Remove();
                }

                // Delete the "CommentRangeEnd" for each deleted comment in the main document.
                List <CommentRangeEnd> commentRangeEndToDelete =
                    doc.Descendants <CommentRangeEnd>().Where(c => commentIds.Contains(c.Id.Value)).ToList();

                foreach (CommentRangeEnd c in commentRangeEndToDelete)
                {
                    c.Remove();
                }

                // Delete the "CommentReference" for each deleted comment in the main document.
                List <CommentReference> commentRangeReferenceToDelete =
                    doc.Descendants <CommentReference>().Where(c => commentIds.Contains(c.Id.Value)).ToList();

                foreach (CommentReference c in commentRangeReferenceToDelete)
                {
                    c.Remove();
                }

                using (Stream stream = File.Open(ArtifactsDir + "Remove comments - OpenXML.docx", FileMode.CreateNew))
                {
                    doc.Save(stream);
                }
            }
        }
コード例 #35
0
ファイル: OutputToODT.cs プロジェクト: MagmaWorks/SCaFFOLD
        public static void WriteToODT(List <ICalc> calculations, bool includeInputs, bool includeBody, bool includeOutputs, string filePath)
        {
            try
            {
                var libraryPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Libraries";
                File.Copy(libraryPath + @"\Calculation_Template.docx", filePath, true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Oops..." + Environment.NewLine + ex.Message);
                return;
            }

            using (WordprocessingDocument wordDocument =
                       WordprocessingDocument.Open(filePath, true))
            {
                var  mainPart = wordDocument.MainDocumentPart;
                Body body     = mainPart.Document.AppendChild(new Body());

                var headerPart = mainPart.HeaderParts.First();
                //var line1 = new Paragraph(new Run(new Text(calculation.TypeName + " - " + calculation.InstanceName)));
                //line1.PrependChild<ParagraphProperties>(new ParagraphProperties() { ParagraphStyleId = new ParagraphStyleId() { Val = "NoSpacing" } });
                var line2 = new Paragraph(new Run(new Text("By: " + Environment.UserName + " on " + DateTime.Today.ToLongDateString())));
                line2.PrependChild <ParagraphProperties>(new ParagraphProperties()
                {
                    ParagraphStyleId = new ParagraphStyleId()
                    {
                        Val = "NoSpacing"
                    }
                });
                var line3 = new Paragraph(new Run(new Text("Checked by : ")));
                line3.PrependChild <ParagraphProperties>(new ParagraphProperties()
                {
                    ParagraphStyleId = new ParagraphStyleId()
                    {
                        Val = "NoSpacing"
                    }
                });
                var line4 = new Paragraph(new Run(new Text("")));
                line4.PrependChild <ParagraphProperties>(new ParagraphProperties()
                {
                    ParagraphStyleId = new ParagraphStyleId()
                    {
                        Val = "NoSpacing"
                    }
                });
                headerPart.RootElement.Append(
                    /*line1,*/
                    line2,
                    line3,
                    line4);

                bool firstCalc = true;
                foreach (var calculation in calculations)
                {
                    if (!firstCalc)
                    {
                        body.Append(new Paragraph(new Run(new Break()
                        {
                            Type = BreakValues.Page
                        })));
                    }

                    Paragraph para      = new Paragraph(new Run(new Text(calculation.TypeName + " - " + calculation.InstanceName)));
                    var       paraProps = para.PrependChild <ParagraphProperties>(new ParagraphProperties());
                    paraProps.ParagraphStyleId = new ParagraphStyleId()
                    {
                        Val = "Heading1"
                    };
                    body.Append(para);

                    if (includeInputs)
                    {
                        para      = new Paragraph(new Run(new Text("Inputs")));
                        paraProps = para.PrependChild <ParagraphProperties>(new ParagraphProperties());
                        paraProps.ParagraphStyleId = new ParagraphStyleId()
                        {
                            Val = "Heading2"
                        };
                        body.Append(para);
                        para      = new Paragraph(new Run(new Text("Input values for calculation.")));
                        paraProps = para.PrependChild <ParagraphProperties>(new ParagraphProperties());
                        paraProps.ParagraphStyleId = new ParagraphStyleId()
                        {
                            Val = "Normal"
                        };
                        body.Append(para);
                        var tableOfInputs = genTable(calculation.GetInputs(), mainPart);
                        body.Append(tableOfInputs);
                    }

                    if (includeBody)
                    {
                        para      = new Paragraph(new Run(new Text("Body")));
                        paraProps = para.PrependChild <ParagraphProperties>(new ParagraphProperties());
                        paraProps.ParagraphStyleId = new ParagraphStyleId()
                        {
                            Val = "Heading2"
                        };
                        body.Append(para);

                        para      = new Paragraph(new Run(new Text("Main calculation including diagrams, working, narrative and conclusions.")));
                        paraProps = para.PrependChild <ParagraphProperties>(new ParagraphProperties());
                        paraProps.ParagraphStyleId = new ParagraphStyleId()
                        {
                            Val = "Normal"
                        };
                        body.Append(para);


                        var FormulaeTable = genFormulaeTable(calculation.GetFormulae(), mainPart);
                        body.AppendChild(FormulaeTable);
                    }

                    if (includeOutputs)
                    {
                        para      = new Paragraph(new Run(new Text("Calculated values")));
                        paraProps = para.PrependChild <ParagraphProperties>(new ParagraphProperties());
                        paraProps.ParagraphStyleId = new ParagraphStyleId()
                        {
                            Val = "Heading2"
                        };
                        body.Append(para);

                        para      = new Paragraph(new Run(new Text("List of calculated values.")));
                        paraProps = para.PrependChild <ParagraphProperties>(new ParagraphProperties());
                        paraProps.ParagraphStyleId = new ParagraphStyleId()
                        {
                            Val = "Normal"
                        };
                        body.Append(para);

                        var tableOfOutputs = genTable(calculation.GetOutputs(), mainPart);
                        body.Append(tableOfOutputs);
                    }
                    firstCalc = false;
                }
            }
        }
コード例 #36
0
ファイル: OxPtHelpers.cs プロジェクト: zinda2000/EasyOffice
        public static WmlDocument AppendParagraphToDocument(
            WmlDocument wmlDoc,
            string strParagraph,
            bool isBold,
            bool isItalic,
            bool isUnderline,
            string foreColor,
            string backColor,
            string styleName)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(wmlDoc))
            {
                using (WordprocessingDocument wDoc = streamDoc.GetWordprocessingDocument())
                {
                    StyleDefinitionsPart part = wDoc.MainDocumentPart.StyleDefinitionsPart;

                    Body body = wDoc.MainDocumentPart.Document.Body;

                    SectionProperties sectionProperties = body.Elements <SectionProperties>().FirstOrDefault();

                    Paragraph     paragraph     = new Paragraph();
                    Run           run           = paragraph.AppendChild(new Run());
                    RunProperties runProperties = new RunProperties();

                    if (isBold)
                    {
                        runProperties.AppendChild(new Bold());
                    }

                    if (isItalic)
                    {
                        runProperties.AppendChild(new Italic());
                    }


                    if (!string.IsNullOrEmpty(foreColor))
                    {
                        int colorValue = System.Drawing.Color.FromName(foreColor).ToArgb();
                        if (colorValue == 0)
                        {
                            throw new OpenXmlPowerToolsException(String.Format("Add-DocxText: The specified color {0} is unsupported, Please specify the valid color. Ex, Red, Green", foreColor));
                        }

                        string ColorHex = string.Format("{0:x6}", colorValue);
                        runProperties.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Color()
                        {
                            Val = ColorHex.Substring(2)
                        });
                    }

                    if (isUnderline)
                    {
                        runProperties.AppendChild(new Underline()
                        {
                            Val = UnderlineValues.Single
                        });
                    }

                    if (!string.IsNullOrEmpty(backColor))
                    {
                        int colorShade = System.Drawing.Color.FromName(backColor).ToArgb();
                        if (colorShade == 0)
                        {
                            throw new OpenXmlPowerToolsException(String.Format("Add-DocxText: The specified color {0} is unsupported, Please specify the valid color. Ex, Red, Green", foreColor));
                        }

                        string ColorShadeHex = string.Format("{0:x6}", colorShade);
                        runProperties.AppendChild(new Shading()
                        {
                            Fill = ColorShadeHex.Substring(2), Val = ShadingPatternValues.Clear
                        });
                    }

                    if (!string.IsNullOrEmpty(styleName))
                    {
                        Style style = part.Styles.Elements <Style>().Where(s => s.StyleId == styleName).FirstOrDefault();
                        //if the specified style is not present in word document add it
                        if (style == null)
                        {
                            using (MemoryStream memoryStream = new MemoryStream())
                            {
                                #region Default.dotx Template has been used to get all the paragraph styles
                                string base64 =
                                    @"UEsDBBQABgAIAAAAIQDTMB8uXgEAACAFAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbLSUy27CMBBF
95X6D5G3VWLooqoqAos+li1S6QcYewJW/ZI9vP6+EwKoqiCRCmwiJTP33jNWxoPR2ppsCTF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1VWT1+ldfJ6VZXX18sXn+OtuMFVH/w9QSwECLQAUAAYACAAAACEA0zAfLl4BAAAgBQAA
EwAAAAAAAAAAAAAAAAAAAAAAW0NvbnRlbnRfVHlwZXNdLnhtbFBLAQItABQABgAIAAAAIQAekRq3
7wAAAE4CAAALAAAAAAAAAAAAAAAAAI8BAABfcmVscy8ucmVsc1BLAQItABQABgAIANFqBkH8XP18
1gEAAAsDAAAQAAAAAAAAAAAAAAAAAKcCAABkb2NQcm9wcy9hcHAueG1sUEsBAi0AFAAGAAgA0WoG
QVLD/UK6AQAAbwIAABEAAAAAAAAAAAAAAAAAqwQAAGRvY1Byb3BzL2NvcmUueG1sUEsBAi0AFAAG
AAgAAAAhANZks1H0AAAAMQMAABwAAAAAAAAAAAAAAAAAlAYAAHdvcmQvX3JlbHMvZG9jdW1lbnQu
eG1sLnJlbHNQSwECLQAUAAYACADRagZBeuUzdzMCAACQBQAAEQAAAAAAAAAAAAAAAADCBwAAd29y
ZC9kb2N1bWVudC54bWxQSwECLQAUAAYACADRagZB3iZxVZoCAAAzBwAAEgAAAAAAAAAAAAAAAAAk
CgAAd29yZC9mb250VGFibGUueG1sUEsBAi0AFAAEAAgA0WoGQYaCXUkdBAAAeQkAABEAAAAAAAAA
AAAAAAAA7gwAAHdvcmQvc2V0dGluZ3MueG1sUEsBAi0AFAAEAAgA0WoGQSv37OFTEgAAFa0AAA8A
AAAAAAAAAAAAAAAAOhEAAHdvcmQvc3R5bGVzLnhtbFBLAQItABQABgAIANFqBkEJ28MF3QYAAFAb
AAAVAAAAAAAAAAAAAAAAALojAAB3b3JkL3RoZW1lL3RoZW1lMS54bWxQSwECLQAUAAYACADRagZB
joxzCXABAAD0AQAAFAAAAAAAAAAAAAAAAADKKgAAd29yZC93ZWJTZXR0aW5ncy54bWxQSwUGAAAA
AAsACwDBAgAAbCwAAAAA";
                                #endregion

                                char[] base64CharArray = base64.Where(c => c != '\r' && c != '\n').ToArray();
                                byte[] byteArray       = System.Convert.FromBase64CharArray(base64CharArray, 0, base64CharArray.Length);
                                memoryStream.Write(byteArray, 0, byteArray.Length);

                                using (WordprocessingDocument defaultDotx = WordprocessingDocument.Open(memoryStream, true))
                                {
                                    //Get the specified style from Default.dotx template for paragraph
                                    Style templateStyle = defaultDotx.MainDocumentPart.StyleDefinitionsPart.Styles.Elements <Style>().Where(s => s.StyleId == styleName && s.Type == StyleValues.Paragraph).FirstOrDefault();

                                    //Check if the style is proper style. Ex, Heading1, Heading2
                                    if (templateStyle == null)
                                    {
                                        throw new OpenXmlPowerToolsException(String.Format("Add-DocxText: The specified style name {0} is unsupported, Please specify the valid style. Ex, Heading1, Heading2, Title", styleName));
                                    }
                                    else
                                    {
                                        part.Styles.Append((templateStyle.CloneNode(true)));
                                    }
                                }
                            }
                        }

                        paragraph.ParagraphProperties = new ParagraphProperties(new ParagraphStyleId()
                        {
                            Val = styleName
                        });
                    }

                    run.AppendChild(runProperties);
                    run.AppendChild(new Text(strParagraph));

                    if (sectionProperties != null)
                    {
                        body.InsertBefore(paragraph, sectionProperties);
                    }
                    else
                    {
                        body.AppendChild(paragraph);
                    }
                }
                return(streamDoc.GetModifiedWmlDocument());
            }
        }
コード例 #37
0
ファイル: Program.cs プロジェクト: Infarh/MathCore.OpenXML
        private static void CreateDocument(string FileName)
        {
            if (FileName is null)
            {
                throw new ArgumentNullException(nameof(FileName));
            }
            if (File.Exists(FileName))
            {
                File.Delete(FileName);
            }

            using (var word_document = WordprocessingDocument.Create(FileName, WordprocessingDocumentType.Document))
            {
                var main_part = word_document.AddMainDocumentPart();

                var header_part = main_part.AddNewPart <HeaderPart>();
                header_part.Header = new()
                {
                    new Paragraph {
                        "Test header!"
                    }.Bold().AlignCenter()
                };
                var header_id = main_part.GetIdOfPart(header_part);

                var footer_part = main_part.AddNewPart <FooterPart>();
                footer_part.Footer = new()
                {
                    new Paragraph {
                        "Test footer!"
                    }
                    .Bold()
                    .AlignRight()
                };
                var footer_id = main_part.GetIdOfPart(footer_part);

                var document = main_part.Document = new();
                document.Body = new()
                {
                    //new Paragraph(
                    //        new Run(new Text("111"))
                    //           .Bold()
                    //           .Color("FF0000"))
                    //   .Justification(JustificationValues.Center),
                    //new Paragraph(new Run(new Text("QWE")).Italic()),
                    //new Paragraph(new Run(new Text("ASD")).Underline()),
                    //new Paragraph { "QQQ" },
                    //table,
                    new Table
                    {
                        new TableRow
                        {
                            new TableCell {
                                "123"
                            }.Width(4672)
                            .Justification(JustificationValues.Center)
                            .Color("red")
                            .Border(6, 0, 6, 6)
                            .VerticalAlignment(TableVerticalAlignmentValues.Center),
                            new TableCell {
                                "qwe"
                            }.Width(4672)
                            .Justification(JustificationValues.Center)
                            .Bold(),
                        }.Height(1009)
                    },
                    new SectionProperties()
                    .HeaderRef(header_id)
                    .FooterRef(footer_id)
                };
                word_document.Save();
            }

            Process.Start(new ProcessStartInfo(FileName)
            {
                UseShellExecute = true
            });
        }
    }
}
コード例 #38
0
        private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
        {
            // Define the reference of the image.
            var element =
                new Drawing(
                    new DW.Inline(
                        new DW.Extent()
            {
                Cx = 990000L, Cy = 792000L
            },
                        new DW.EffectExtent()
            {
                LeftEdge   = 0L,
                TopEdge    = 0L,
                RightEdge  = 0L,
                BottomEdge = 0L
            },
                        new DW.DocProperties()
            {
                Id   = (UInt32Value)1U,
                Name = "Picture 1"
            },
                        new DW.NonVisualGraphicFrameDrawingProperties(
                            new A.GraphicFrameLocks()
            {
                NoChangeAspect = true
            }),
                        new A.Graphic(
                            new A.GraphicData(
                                new PIC.Picture(
                                    new PIC.NonVisualPictureProperties(
                                        new PIC.NonVisualDrawingProperties()
            {
                Id   = (UInt32Value)0U,
                Name = "New Bitmap Image.jpg"
            },
                                        new PIC.NonVisualPictureDrawingProperties()),
                                    new PIC.BlipFill(
                                        new A.Blip(
                                            new A.BlipExtensionList(
                                                new A.BlipExtension()
            {
                Uri =
                    "{28A0092B-C50C-407E-A947-70E740481C1C}"
            })
                                            )
            {
                Embed            = relationshipId,
                CompressionState =
                    A.BlipCompressionValues.Print
            },
                                        new A.Stretch(
                                            new A.FillRectangle())),
                                    new PIC.ShapeProperties(
                                        new A.Transform2D(
                                            new A.Offset()
            {
                X = 0L, Y = 0L
            },
                                            new A.Extents()
            {
                Cx = 990000L, Cy = 792000L
            }),
                                        new A.PresetGeometry(
                                            new A.AdjustValueList()
                                            )
            {
                Preset = A.ShapeTypeValues.Rectangle
            }))
                                )
            {
                Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
            })
                        )
            {
                DistanceFromTop    = (UInt32Value)0U,
                DistanceFromBottom = (UInt32Value)0U,
                DistanceFromLeft   = (UInt32Value)0U,
                DistanceFromRight  = (UInt32Value)0U,
                EditId             = "50D07946"
            });

            // Append the reference to body, the element should be in a Run.
            wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
        }
コード例 #39
0
        /// <summary>
        /// Get all the CIW information, create temp csv file then load that and then filter it down to the different objects
        /// </summary>
        /// <param name="fileName"></param>
        public string GetCIWInformation(FileMetadata fmd, out int errorCode)
        {
            string filePath;

            if (string.IsNullOrEmpty(fmd.DecryptedFilePath))
            {
                filePath = fmd.FilePath;
            }
            else
            {
                filePath = fmd.DecryptedFilePath;
            }
            List <CIWData> ciwInformation = new List <CIWData>();

            log.Info(String.Format("Getting information from file {0}", filePath));

            //Check for password protection
            try
            {
                using (WordprocessingDocument wd = WordprocessingDocument.Open(filePath, false))
                {
                    DocumentProtection dp = wd.MainDocumentPart.DocumentSettingsPart.Settings.GetFirstChild <DocumentProtection>();
                }
            }
            catch (FileFormatException e)
            {
                log.Warn(string.Format("Locked Document - {0} with inner exception:{1}", e.Message, e.InnerException));
                sendPasswordProtection(fmd.UploaderPersID, fileNameHelper(fmd.FileName));
                errorCode = (int)ErrorCodes.password_protected;
                log.Warn(string.Format("Inserting error code {0}:{1} into upload table", ErrorCodes.password_protected, (int)ErrorCodes.password_protected));
                return(null);
            }

            //Begin parsing XML from CIW document
            using (var document = WordprocessingDocument.Open(filePath, true))
            {
                XmlDocument      xml     = new XmlDocument();
                MainDocumentPart docPart = document.MainDocumentPart;
                xml.InnerXml = docPart.Document.FirstChild.OuterXml;
                XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(xml.NameTable);
                nameSpaceManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");

                //Get Version number node
                var node = xml.SelectSingleNode(string.Format("w:body/w:tbl/w:tr/w:tc/w:tbl/w:tr/w:tc/w:sdt/w:sdtContent/w:p/w:r/w:t"), nameSpaceManager);

                if (node != null)
                {
                    if (node.InnerText != "V1")
                    {
                        //Begin exiting if wrong version
                        sendWrongVersion(fmd.UploaderPersID, fileNameHelper(fmd.FileName));
                        errorCode = (int)ErrorCodes.wrong_version;
                        log.Warn(string.Format("Inserting error code {0}:{1} into upload table", ErrorCodes.wrong_version, (int)ErrorCodes.wrong_version));
                        return(null);
                    }
                }
                else
                {
                    //Begin exiting if no version on form
                    sendWrongVersion(fmd.UploaderPersID, fileNameHelper(fmd.FileName));
                    errorCode = (int)ErrorCodes.wrong_version;
                    log.Warn(string.Format("Inserting error code {0}:{1} into upload table", ErrorCodes.wrong_version, (int)ErrorCodes.wrong_version));
                    return(null);
                }

                try
                {
                    //Gets all data on the form via tags
                    log.Info(string.Format("Parsing XML."));
                    //docpart.document.firstchild is the entire xml document
                    //if we get the child elements we get a list of first children which should be 9
                    //we select the 3rd child which is the main table that gets filled out
                    var docTable = docPart.Document.FirstChild.ChildElements[2];
                    //the first 2 children of this table are grid settings and properties which we dont care about right now
                    docTable.RemoveAllChildren <TableGrid>();
                    docTable.RemoveAllChildren <TableProperties>();
                    //now we have 29 children of type w:tr which are the rows of the table
                    //select all the table cells inside the current table that arent a section header.
                    //currently headers start with a number so excluded those
                    var tableCells = docTable.Descendants <TableCell>().Except(docTable.Descendants <TableCell>().Where(x => "0123456789".Contains(x.InnerText.Trim().Substring(0, 1))));

                    //Grab the version cell and add it to ciwInformation
                    var versionNode = xml.SelectSingleNode(string.Format("w:body/w:tbl/w:tr/w:tc/w:tbl/w:tr/w:tc"), nameSpaceManager).NextSibling;
                    ciwInformation.Add(new CIWData {
                        InnerText = versionNode.InnerText, TagName = versionNode.ChildNodes[1].ChildNodes[0].ChildNodes[1].Attributes[0].Value
                    });

                    //get pob country name
                    var placeOfBirthCountryNode = xml.FirstChild.ChildNodes[2].ChildNodes[4].ChildNodes[4];
                    var pobTagname = placeOfBirthCountryNode.ChildNodes[2].FirstChild.ChildNodes[1].Attributes[0].Value;
                    ciwInformation.Add(new CIWData {
                        InnerText = placeOfBirthCountryNode.LastChild.InnerText, TagName = pobTagname + "2"
                    });

                    //get home country name
                    var homeCountry = xml.FirstChild.ChildNodes[2].ChildNodes[6].ChildNodes[2].LastChild.InnerText;
                    var homeTag     = xml.FirstChild.ChildNodes[2].ChildNodes[6].ChildNodes[2].ChildNodes[2].FirstChild.ChildNodes[1].Attributes[0].Value;
                    ciwInformation.Add(new CIWData {
                        InnerText = homeCountry, TagName = homeTag + "2"
                    });

                    //get citizenship country
                    var citizenCountry = xml.FirstChild.ChildNodes[2].ChildNodes[9].ChildNodes[4].ChildNodes[2].InnerText;
                    var citizenTag     = xml.FirstChild.ChildNodes[2].ChildNodes[9].ChildNodes[4].ChildNodes[2].FirstChild.ChildNodes[1].Attributes[0].Value;
                    ciwInformation.Add(new CIWData {
                        InnerText = citizenCountry, TagName = citizenTag + "2"
                    });

                    //get all table cells and add them after the version in ciwInformation
                    ciwInformation.AddRange(tableCells
                                            .Select
                                            (
                                                s =>
                                                new CIWData
                    {
                        TagName   = s.ChildElements.OfType <SdtBlock>().FirstOrDefault().GetFirstChild <SdtProperties>().GetFirstChild <Tag>().Val,
                        InnerText = ParseXML(s.ChildElements.OfType <SdtBlock>().FirstOrDefault().InnerText, s.OuterXml),
                    }
                                            ).ToList());
                }
                catch (Exception e)
                {
                    log.Warn(string.Format("XML Parsing Failed - {0} with inner exception: {1}", e.Message, e.InnerException));
                    sendWrongVersion(fmd.UploaderPersID, fileNameHelper(fmd.FileName));


                    errorCode = (int)ErrorCodes.wrong_version;
                    log.Warn(string.Format("Inserting error code {0}:{1} into upload table", ErrorCodes.wrong_version, (int)ErrorCodes.wrong_version));
                    return(null);
                }


                //used in log
                string lastFirst = (ciwInformation.FirstOrDefault(c => c.TagName == "Employee-LastName").InnerText ?? "null") + ", " + (ciwInformation.FirstOrDefault(c => c.TagName == "Employee-FirstName").InnerText ?? "null");

                log.Info(String.Format("CiwInformation obtained for {0}", lastFirst));

                log.Info(String.Format("Creating temp file for {0}", lastFirst));

                //Create a temp csv file of the information within the form
                string tempFile = CreateTempFile(ciwInformation);
                errorCode = (int)ErrorCodes.successfully_processed;

                return(tempFile);
            }
        }
コード例 #40
0
        private void GenerateCreditContractTemplate()
        {
            using (var document = WordprocessingDocument.Create(_templateDocPath, WordprocessingDocumentType.Document, true))
            {
                var mainPart = document.AddMainDocumentPart();
                var doc      = new Document();
                var body     = new Body();
                AddParagraph(body, JustificationValues.Center, SetBoldRunProperties(new RunProperties()), "Кредитный договор");
                AddParagraph(body, JustificationValues.Left, new RunProperties(), string.Empty);

                var runs = new List <Run>
                {
                    GenerateRun(new RunProperties(), "№"),
                    GenerateRun(new RunProperties(), ContractNumberPlace)
                };
                AddParagraph(body, JustificationValues.Left, runs);

                runs = new List <Run>
                {
                    GenerateRun(new RunProperties(), DaymonthPlace),
                    GenerateRun(new RunProperties(), YearPlace)
                };
                AddParagraph(body, JustificationValues.Left, runs);
                AddParagraph(body, JustificationValues.Left, new RunProperties(), string.Empty);

                runs = new List <Run>
                {
                    GenerateRun(new RunProperties(), "Банк \"Три толстяка\", далее именуемый \"Кредитор\", в  лице  Чугаинова Кирилла, действующего(-ей) на основании Устава, с одной стороны, и  "),
                    GenerateRun(new RunProperties(), CustomerPlace),
                    GenerateRun(new RunProperties(), ", далее именуемый(-ая) \"Заемщик\", с другой стороны, заключили настоящий договор о следующем.")
                };
                AddParagraph(body, JustificationValues.Both, runs);

                //1. Предмет договора
                AddParagraph(body, JustificationValues.Left, new RunProperties(), string.Empty);
                AddParagraph(body, JustificationValues.Center, new RunProperties()
                {
                    Italic = new Italic(), Bold = new Bold()
                }, "1. Предмет договора");

                //1.1
                runs = new List <Run>
                {
                    GenerateRun(new RunProperties(), "1.1. Кредитор   предоставляет   Заемщику   в  порядке  и  на  условиях,  предусмотренных   Договором, кредит "),
                    GenerateRun(new RunProperties(), CreditPlace),
                    GenerateRun(new RunProperties(), " (далее  –  кредит) "),
                    GenerateRun(new RunProperties(), "в сумме "),
                    GenerateRun(new RunProperties(), CreditSumPlace),
                    GenerateRun(new RunProperties(), " рублей c "),
                    GenerateRun(new RunProperties(), SincePlace),
                    GenerateRun(new RunProperties(), " по "),
                    GenerateRun(new RunProperties(), UntilPlace),
                    GenerateRun(new RunProperties(), "."),
//                    GenerateRun(new RunProperties(), "на _____________________________________________________________. (целевое использование кредита)")
                };
                AddParagraph(body, JustificationValues.Both, runs);

                //1.2
                runs = new List <Run>
                {
                    GenerateRun(new RunProperties(), "1.2.  Процентная ставка за пользование кредитом устанавливается в размере "),
                    GenerateRun(new RunProperties(), PercentRatePlace),
                    GenerateRun(new RunProperties(), " процентов годовых.")
                };
                AddParagraph(body, JustificationValues.Both, runs);
                //1.3
                AddParagraph(body, JustificationValues.Both, new RunProperties(), "1.3.  Под «задолженностью по Договору» понимаются возникшие в связи " +
                             "с исполнением Договора обязательства  Заемщика(-ов)  по  уплате  Банку: " +
                             " основного  долга  (суммы  кредита),  процентов, штрафов, осуществленных в связи " +
                             "с исполнением/неисполнением Договора. ");
                //2. Порядок и сроки погашения кредита
                AddParagraph(body, JustificationValues.Left, new RunProperties(), string.Empty);
                AddParagraph(body, JustificationValues.Center, new RunProperties()
                {
                    Italic = new Italic(), Bold = new Bold()
                }, "2. Порядок и сроки погашения кредита");

                runs = new List <Run>
                {
                    GenerateRun(new RunProperties(), "2.1. Заемщик обязан погасить полученный им кредит путем совершения ежемесячных платежей. " +
                                "При этом платеж должен быть произведен "),
                    GenerateRun(new RunProperties(), PaymentDayPlace),
                    GenerateRun(new RunProperties(), " числа либо ранее, но не более, чем за 10 дней до даты платежа.")
                };
                AddParagraph(body, JustificationValues.Both, runs);

                AddParagraph(body, JustificationValues.Both, new RunProperties(), "2.2. Сумма произведенного платежа, недостаточная для полного погашения всей " +
                             "задолженности Заемщика, погашает прежде всего издержки Кредитора по " +
                             "принятию исполнения и принудительному взысканию, затем - проценты за " +
                             "пользование кредитными ресурсами, " +
                             "а в оставшейся части - основную сумму долга.");

                doc.AppendChild(body);
                mainPart.Document = doc;
            }
        }
コード例 #41
0
        public void HelloWorld(Int32 SurahNr)
        {
            var    basmala = @"بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ";
            string docName = @"C:\Data\surah-" + SurahNr + ".docx";

            // Create a Wordprocessing document.
            using (WordprocessingDocument mydoc = WordprocessingDocument.Create(docName, WordprocessingDocumentType.Document))
            {
                // Add a new main document part.
                MainDocumentPart mainPart = mydoc.AddMainDocumentPart();
                //Create DOM tree for simple document.
                mainPart.Document = new Document();
                Body                body = new Body();
                Paragraph           p    = new Paragraph();
                ParagraphProperties pp   = p.ChildElements.First <ParagraphProperties>();

                if (pp == null)
                {
                    pp = new ParagraphProperties();
                    p.Append(pp);
                    //p.InsertBefore(pp, p.First());
                }

                BiDi bidi = new BiDi();
                pp.Append(bidi);
                Run   r = new Run();
                Text  t; // = new Text(ayah.AyahText);
                Table table = new Table();
                //Quran ayah;
                using (var context = new DBEntities())
                {
                    TableProperties props = new TableProperties(
                        new TableBorders(
                            new TopBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                            new BottomBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 11
                    },
                            new LeftBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 11
                    },
                            new RightBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 11
                    },
                            new InsideHorizontalBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 11
                    },
                            new InsideVerticalBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 11
                    }));

                    table.AppendChild <TableProperties>(props);

                    //var ayah = context.Qurans.Where(q => q.SuraID == 112 && q.VerseID == 2).FirstOrDefault<Quran>();

                    var ayah = from a in context.Qurans where a.SuraID.Equals(SurahNr) select a;
                    foreach (var a in ayah)
                    {
                        var tr    = new TableRow();
                        var ayahT = a.AyahText;
                        if (a.VerseID == 1)
                        {
                            ayahT = ayahT.Remove(0, basmala.Length);
                        }
                        var tc = new TableCell();
                        tc.Append(new Paragraph(new Run(new Text(ayahT))));

                        //var p2 = new Paragraph();
                        //pp = p2.ChildElements.First<ParagraphProperties>();
                        //if (pp == null)
                        //{
                        //    pp = new ParagraphProperties();
                        //    p.Append(pp);
                        //    //p.InsertBefore(pp, p.First());
                        //}

                        //bidi = new BiDi();
                        //pp.Append(bidi);
                        //r = new Run();
                        //t = new Text(a.AyahText);
                        //tc.Append(p2);
                        //tc.Append(new Paragraph(new Run(new Text(a.VerseID.ToString()))));
                        tr.Append(tc);

                        tc = new TableCell();
                        //tc.Append(new Paragraph(new Run(new Text(a.AyahText))));
                        tc.Append(new Paragraph(new Run(new Text(a.VerseID.ToString()))));

                        //p2 = new Paragraph();
                        //pp = p2.ChildElements.First<ParagraphProperties>();
                        //if (pp == null)
                        //{
                        //    pp = new ParagraphProperties();
                        //    p.Append(pp);
                        //    //p.InsertBefore(pp, p.First());
                        //}

                        //bidi = new BiDi();
                        //pp.Append(bidi);
                        //r = new Run();
                        //t = new Text(a.VerseID.ToString());
                        //tc.Append(p2);


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

                        //t = new Text(a.VerseID + ": " +  a.AyahText);
                        //r.Append(t);
                        //r.AppendChild(new Break());
                    }
                }
                //Append elements appropriately.
                //r.Append(t);
                p.Append(r);
                body.Append(table);
                body.Append(p);
                mainPart.Document.Append(body);
                // Save changes to the main document part.
                mainPart.Document.Save();

                // Save changes to the main document part.
                mydoc.MainDocumentPart.Document.Save();
            }
        }
コード例 #42
0
        private void Htmlconversion(string doc, string destination, string Title)
        {
            try
            {
                FileInfo fileInfo  = new FileInfo(doc);
                byte[]   byteArray = File.ReadAllBytes(fileInfo.FullName);
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    memoryStream.Write(byteArray, 0, byteArray.Length);
                    using (WordprocessingDocument wDoc = WordprocessingDocument.Open(memoryStream, true))
                    {
                        int imageCounter = 0;
                        //var pageTitle = fileInfo.FullName;
                        var pageTitle = Title;
                        var part      = wDoc.CoreFilePropertiesPart;
                        if (part != null)
                        {
                            pageTitle = (string)part.GetXDocument().Descendants(DC.title).FirstOrDefault() ?? Title;
                        }



                        WmlToHtmlConverterSettings settings = new WmlToHtmlConverterSettings()
                        {
                            AdditionalCss                       = "body { margin: 1cm auto; max-width: 20cm; padding: 0; }",
                            PageTitle                           = pageTitle,
                            FabricateCssClasses                 = true,
                            CssClassPrefix                      = "pt-",
                            RestrictToSupportedLanguages        = false,
                            RestrictToSupportedNumberingFormats = false,
                            ImageHandler                        = imageInfo =>
                            {
                                ++imageCounter;
                                string      extension   = imageInfo.ContentType.Split('/')[1].ToLower();
                                ImageFormat imageFormat = null;
                                if (extension == "png")
                                {
                                    imageFormat = ImageFormat.Png;
                                }
                                else if (extension == "gif")
                                {
                                    imageFormat = ImageFormat.Gif;
                                }
                                else if (extension == "bmp")
                                {
                                    imageFormat = ImageFormat.Bmp;
                                }
                                else if (extension == "jpeg")
                                {
                                    imageFormat = ImageFormat.Jpeg;
                                }
                                else if (extension == "tiff")
                                {
                                    extension   = "gif";
                                    imageFormat = ImageFormat.Gif;
                                }
                                else if (extension == "x-wmf")
                                {
                                    extension   = "wmf";
                                    imageFormat = ImageFormat.Wmf;
                                }

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

                                string base64 = null;
                                try
                                {
                                    using (MemoryStream ms = new MemoryStream())
                                    {
                                        imageInfo.Bitmap.Save(ms, imageFormat);
                                        var ba = ms.ToArray();
                                        base64 = System.Convert.ToBase64String(ba);
                                    }
                                }
                                catch (Exception)
                                { }

                                ImageFormat    format = imageInfo.Bitmap.RawFormat;
                                ImageCodecInfo codec  = ImageCodecInfo.GetImageDecoders()
                                                        .First(c => c.FormatID == format.Guid);
                                string mimeType = codec.MimeType;

                                string imageSource =
                                    string.Format("data:{0};base64,{1}", mimeType, base64);

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

                        XElement htmlElement = WmlToHtmlConverter.ConvertToHtml(wDoc, settings);
                        var      html        = new XDocument(new XDocumentType("html", null, null, null), htmlElement);
                        html.Save(destination, SaveOptions.DisableFormatting);
                    }
                }
            }
            catch (Exception ex)
            {
                CreateLog err = new CreateLog();
                CreateLog.CreateLogFiles();
                err.ErrorLog(Server.MapPath("/Logs/ErrorLog.txt"), ex.Source);
            }
        }
コード例 #43
0
        public ActionResult ExportWord()
        {
            ExportRetailModel model = Session["@ExportWord@"] as ExportRetailModel;
            //render view
            const string viewName = "ViewForWord";
            String       html     = RenderStringView(viewName, model);

            try
            {
                const string filename    = "StreamTest.docx";
                const string contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                using (MemoryStream generatedDocument = new MemoryStream())
                {
                    using (WordprocessingDocument package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document))
                    {
                        MainDocumentPart mainPart = package.MainDocumentPart;
                        if (mainPart == null)
                        {
                            mainPart = package.AddMainDocumentPart();
                            new HtmlDocument.Document(new HtmlDocument.Body()).Save(mainPart);
                        }
                        if (Request.Url != null)
                        {
                            HtmlXml.HtmlConverter converter = new HtmlXml.HtmlConverter(mainPart)
                            {
                                BaseImageUrl = new Uri(Request.Url.Scheme + "://" + Request.Url.Authority)
                            };
                            HtmlDocument.Body body = mainPart.Document.Body;
                            var paragraphs         = converter.Parse(html);
                            foreach (OpenXmlCompositeElement t in paragraphs)
                            {
                                body.Append(t);
                            }
                        }
                        mainPart.Document.Save();
                    }
                    byte[] bytesInStream = generatedDocument.ToArray(); // simpler way of converting to array
                    generatedDocument.Close();
                    Response.Clear();
                    Response.ContentType = contentType;
                    Response.AddHeader("content-disposition", "attachment;filename=" + filename);
                    //this will generate problems
                    Response.BinaryWrite(bytesInStream);
                    try
                    {
                        Response.End();
                    }
                    catch (Exception ex)
                    {
                        return(new EmptyResult());
                        //Response.End(); generates an exception. if you don't use it, you get some errors when Word opens the file...
                    }
                    Session.Remove("@ExportWord@");
                    return(new EmptyResult());
                }
            }
            catch (Exception ex)
            {
                return(new EmptyResult());
            }
        }
コード例 #44
0
        public void GenerateDoc(Klienci klient, BindingList <ItemModel> list)
        {
            int    lp = 1;
            string bmName;

            string source     = @"C:\temp\umowa1.docx";
            string destinaton = source.Replace("umowa1", "umowa_" + Guid.NewGuid().ToString());

            File.Copy(source, destinaton);

            using (WordprocessingDocument document = WordprocessingDocument.Open(destinaton, true))
            {
                var mainPart = document.MainDocumentPart;
                bmName = "Tabela";
                var res = from bm in mainPart.Document.Body.Descendants <BookmarkStart>()
                          where bm.Name == bmName
                          select bm;
                var bookmark = res.SingleOrDefault();
                if (bookmark != null)
                {
                    var parent = bookmark.Parent;


                    Run       run          = new Run(new RunProperties(new Bold()));
                    Paragraph newParagraph = new Paragraph(run);

                    parent.InsertBeforeSelf(newParagraph);
                    parent.Remove();

                    Table           table = new Table();
                    TableProperties props = new TableProperties(
                        new TableStyle()
                    {
                        Val = "TableGrid"
                    },
                        new TableWidth()
                    {
                        Width = new StringValue("0"), Type = TableWidthUnitValues.Auto
                    },
                        new TableBorders(
                            new InsideHorizontalBorder {
                        Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 6
                    },
                            new InsideVerticalBorder {
                        Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 6
                    }
                            ),
                        new TableGrid(
                            new GridColumn()
                    {
                        Width = new StringValue("500")
                    },
                            new GridColumn()
                    {
                        Width = new StringValue("5200")
                    },
                            new GridColumn()
                    {
                        Width = new StringValue("700")
                    },
                            new GridColumn()
                    {
                        Width = new StringValue("1000")
                    },
                            new GridColumn()
                    {
                        Width = new StringValue("900")
                    },
                            new GridColumn()
                    {
                        Width = new StringValue("950")
                    },

                            new TableRow(
                                new TableCell(
                                    new TableCellProperties(
                                        new TableCellWidth()
                    {
                        Width = new StringValue("0"), Type = TableWidthUnitValues.Auto
                    }),
                                    new Paragraph(
                                        new Run(
                                            new Text("Lp."))
                                        )),
                                new TableCell(
                                    new TableCellProperties(
                                        new TableCellWidth()
                    {
                        Width = new StringValue("0"), Type = TableWidthUnitValues.Auto
                    }),
                                    new Paragraph(
                                        new Run(
                                            new Text("Nazwa"))
                                        )),
                                new TableCell(
                                    new TableCellProperties(
                                        new TableCellWidth()
                    {
                        Width = new StringValue("0"), Type = TableWidthUnitValues.Auto
                    }),
                                    new Paragraph(
                                        new Run(
                                            new Text("Ilość"))
                                        )),
                                new TableCell(
                                    new TableCellProperties(
                                        new TableCellWidth()
                    {
                        Width = new StringValue("0"), Type = TableWidthUnitValues.Auto
                    }),
                                    new Paragraph(
                                        new Run(
                                            new Text("Wartość")))),
                                new TableCell(
                                    new TableCellProperties(
                                        new TableCellWidth()
                    {
                        Width = new StringValue("0"), Type = TableWidthUnitValues.Auto
                    }),
                                    new Paragraph(
                                        new Run(
                                            new Text("Stawka")))),
                                new TableCell(
                                    new TableCellProperties(
                                        new TableCellWidth()
                    {
                        Width = new StringValue("0"), Type = TableWidthUnitValues.Auto
                    }),
                                    new Paragraph(
                                        new Run(
                                            new Text("Oplata"))))
                                )));
                    table.AppendChild(props);

                    foreach (ItemModel item in list)
                    {
                        string typStawkiSlownie = string.Empty;
                        if (item.TypStawki == TypStawki.Dobowa)
                        {
                            typStawkiSlownie = "Doba";
                        }
                        else if (item.TypStawki == TypStawki.Godzinowa)
                        {
                            typStawkiSlownie = "Godzinowa";
                        }
                        else
                        {
                            typStawkiSlownie = "Cena";
                        }

                        table.Append(new TableRow(
                                         new TableCell(
                                             new TableCellProperties(
                                                 new Paragraph(
                                                     new Run(
                                                         new Text(lp.ToString()))))),
                                         new TableCell(
                                             new TableCellProperties(
                                                 new Paragraph(
                                                     new Run(
                                                         new Text(item.DisplayedNazwa))))),
                                         new TableCell(
                                             new TableCellProperties(
                                                 new Paragraph(
                                                     new Run(
                                                         new Text(item.Ilosc.ToString()))))),
                                         new TableCell(
                                             new TableCellProperties(
                                                 new Paragraph(
                                                     new Run(
                                                         new Text(item.Wartosc.ToString()))))),
                                         new TableCell(
                                             new TableCellProperties(
                                                 new Paragraph(
                                                     new Run(
                                                         new Text(item.StawkaUmowa))))),
                                         new TableCell(
                                             new TableCellProperties(
                                                 new Paragraph(
                                                     new Run(
                                                         new Text(item.SumaZaPrzedmiot.ToString())))))

                                         ));

                        lp++;
                    }
                    newParagraph.InsertBeforeSelf(table);

                    bmName   = "Imie";
                    bookmark = res.Single();
                    parent   = bookmark.Parent;
                    var paragraph =
                        new Paragraph(new Run(new Text(string.Empty)),
                                      new Paragraph(
                                          new Run(new Text($"Najemca: {klient.Imie} {klient.Nazwisko} "))),
                                      new Paragraph(
                                          new Run(new Text($"Adres: { klient.Adres }"))),
                                      new Paragraph(
                                          new Run(new Text($"Pesel: {klient.Pesel} Telefon: {klient.Telefon}")))
                                      );
                    parent.InsertBeforeSelf(paragraph);
                    parent.Remove();

                    bmName    = "GodzinaOkresNajmu";
                    bookmark  = res.Single();
                    parent    = bookmark.Parent;
                    paragraph =
                        new Paragraph(
                            new Run(new Text($"{DateTime.Now.ToString("HH:mm")}")));
                    parent.InsertBeforeSelf(paragraph);
                    parent.Remove();

                    bmName    = "Data";
                    bookmark  = res.Single();
                    parent    = bookmark.Parent;
                    paragraph =
                        new Paragraph(
                            new Run(
                                new Text($"Data: {DateTime.Now.ToString("yyyy-MM-dd")}")));
                    parent.InsertBeforeSelf(paragraph);
                    parent.Remove();

                    bmName    = "DataPodpis";
                    bookmark  = res.Single();
                    parent    = bookmark.Parent;
                    paragraph =
                        new Paragraph(
                            new Run(
                                new Text($"Data: {DateTime.Now.ToString("yyyy-MM-dd")}")));
                    parent.InsertBeforeSelf(paragraph);
                    parent.Remove();

                    var sumDoZaplaty = list.Sum(x => x.SumaZaPrzedmiot);
                    bmName    = "DoZaplaty";
                    bookmark  = res.Single();
                    parent    = bookmark.Parent;
                    paragraph =
                        new Paragraph(
                            new Run(
                                new Text($"Do Zapłaty: {sumDoZaplaty.ToString()} zł")));
                    parent.InsertBeforeSelf(paragraph);
                    parent.Remove();

                    var sumKaucja = list.Sum(x => x.Kaucja);
                    bmName    = "Kaucja";
                    bookmark  = res.Single();
                    parent    = bookmark.Parent;
                    paragraph =
                        new Paragraph(
                            new Run(
                                new Text($"Kaucja: {sumKaucja.ToString()} zł")));
                    parent.InsertBeforeSelf(paragraph);
                    parent.Remove();
                }
                document.Close();
            }
            Process.Start(destinaton);
        }
コード例 #45
0
        /// <summary>
        /// Appends the documents to primary document.
        /// </summary>
        /// <param name="primaryDocument">The primary document.</param>
        /// <param name="documentstoAppend">The documents to append.</param>
        /// <returns></returns>
        public byte[] AppendDocumentsToPrimaryDocument(byte[] primaryDocument, List <byte[]> documentstoAppend)
        {
            if (documentstoAppend == null)
            {
                throw new ArgumentNullException("documentstoAppend");
            }

            if (primaryDocument == null)
            {
                throw new ArgumentNullException("primaryDocument");
            }

            byte[] output = null;

            using (MemoryStream finalDocumentStream = new MemoryStream())
            {
                finalDocumentStream.Write(primaryDocument, 0, primaryDocument.Length);

                using (WordprocessingDocument finalDocument = WordprocessingDocument.Open(finalDocumentStream, true))
                {
                    SectionProperties finalDocSectionProperties = null;
                    this.UnprotectDocument(finalDocument);

                    SectionProperties tempSectionProperties = finalDocument.MainDocumentPart.Document.Descendants <SectionProperties>().LastOrDefault();

                    if (tempSectionProperties != null)
                    {
                        finalDocSectionProperties = tempSectionProperties.CloneNode(true) as SectionProperties;
                    }

                    this.RemoveContentControlsAndKeepContents(finalDocument.MainDocumentPart.Document);

                    foreach (byte[] documentToAppend in documentstoAppend)
                    {
                        AlternativeFormatImportPart subReportPart = finalDocument.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML);
                        SectionProperties           secProperties = null;

                        using (MemoryStream docToAppendStream = new MemoryStream())
                        {
                            docToAppendStream.Write(documentToAppend, 0, documentToAppend.Length);

                            using (WordprocessingDocument docToAppend = WordprocessingDocument.Open(docToAppendStream, true))
                            {
                                this.UnprotectDocument(docToAppend);

                                tempSectionProperties = docToAppend.MainDocumentPart.Document.Descendants <SectionProperties>().LastOrDefault();

                                if (tempSectionProperties != null)
                                {
                                    secProperties = tempSectionProperties.CloneNode(true) as SectionProperties;
                                }

                                this.RemoveContentControlsAndKeepContents(docToAppend.MainDocumentPart.Document);
                                docToAppend.MainDocumentPart.Document.Save();
                            }

                            docToAppendStream.Position = 0;
                            subReportPart.FeedData(docToAppendStream);
                        }

                        if (documentstoAppend.ElementAtOrDefault(0).Equals(documentToAppend))
                        {
                            AssignSectionProperties(finalDocument.MainDocumentPart.Document, finalDocSectionProperties);
                        }

                        AltChunk altChunk = new AltChunk();
                        altChunk.Id = finalDocument.MainDocumentPart.GetIdOfPart(subReportPart);
                        finalDocument.MainDocumentPart.Document.AppendChild(altChunk);

                        if (!documentstoAppend.ElementAtOrDefault(documentstoAppend.Count - 1).Equals(documentToAppend))
                        {
                            AssignSectionProperties(finalDocument.MainDocumentPart.Document, secProperties);
                        }

                        finalDocument.MainDocumentPart.Document.Save();
                    }

                    finalDocument.MainDocumentPart.Document.Save();
                }

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

            return(output);
        }
コード例 #46
0
        private void btnSimpleWordTest_Click(object sender, EventArgs e)
        {
            try
            {
                string filepath = "test.docx";
                string msg      = "Hello World!";
                using (WordprocessingDocument doc = WordprocessingDocument.Create(filepath,
                                                                                  DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
                {
                    // Add a main document part.
                    MainDocumentPart mainPart = doc.AddMainDocumentPart();

                    // Create the document structure and add some text.
                    mainPart.Document = new Document();
                    Body body = mainPart.Document.AppendChild(new Body());

                    // Define the styles
                    Word.AddStyle(mainPart, "MyHeading1", "Titolone", "Verdana", 30, "0000FF", false, true, true);
                    Word.AddStyle(mainPart, "MyTypescript", "Macchina da scrivere", "Courier New", 10, "333333", true, false, false);

                    // Add MyHeading1 styled text
                    Paragraph headingPar = Word.CreateParagraphWithStyle("MyHeading1", JustificationValues.Center);
                    Word.AddTextToParagraph(headingPar, "Titolo con stile applicato");
                    body.AppendChild(headingPar);

                    // Add simple text
                    Paragraph para = body.AppendChild(new Paragraph());
                    Run       run  = para.AppendChild(new Run());
                    // String msg contains the text, "Hello, Word!"
                    run.AppendChild(new Text(msg));

                    // Add MyTypescript styled text

                    Paragraph typescriptParagraph = Word.CreateParagraphWithStyle("MyTypescript", JustificationValues.Left);
                    Word.AddTextToParagraph(typescriptParagraph, "È universalmente riconosciuto che un lettore che osserva il layout di una pagina viene distratto dal contenuto testuale se questo è leggibile. Lo scopo dell’utilizzo del Lorem Ipsum è che offre una normale distribuzione delle lettere (al contrario di quanto avviene se si utilizzano brevi frasi ripetute, ad esempio “testo qui”), apparendo come un normale blocco di testo leggibile. Molti software di impaginazione e di web design utilizzano Lorem Ipsum come testo modello. Molte versioni del testo sono state prodotte negli anni, a volte casualmente, a volte di proposito (ad esempio inserendo passaggi ironici).");
                    body.AppendChild(typescriptParagraph);

                    // Append a paragraph with styles
                    Paragraph newPar = createParagraphWithStyles();
                    body.AppendChild(newPar);

                    // Append a table
                    string[][] c = new string[4][];
                    for (int i = 0; i < c.Length; i++)
                    {
                        c[i] = new string[5];
                        for (int j = 0; j < c[i].Length; j++)
                        {
                            c[i][j] = i + "-" + j;
                        }
                    }
                    body.Append(Word.CreateTable(c, Word.GetTableProperties("#000000", BorderValues.Thick, "5000")));

                    // Append bullet list
                    string[] texts = { "First element", "Second Element", "Third Element" };
                    Word.CreateBulletNumberingPart(mainPart);
                    List <Paragraph> bulletList = new List <Paragraph>();
                    Word.CreateBulletOrNumberedList(100, 200, bulletList, texts.Length, texts);
                    foreach (Paragraph paragraph in bulletList)
                    {
                        body.Append(paragraph);
                    }

                    // Append numbered list
                    List <Paragraph> numberedList = new List <Paragraph>();
                    Word.CreateBulletOrNumberedList(100, 240, numberedList, texts.Length, texts, false);
                    foreach (Paragraph paragraph in numberedList)
                    {
                        body.Append(paragraph);
                    }

                    // Append image
                    Word.InsertPicture(doc, "panorama.jpg");
                }
                MessageBox.Show("Il documento è pronto!");
                Process.Start(filepath);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Problemi col documento. Se è aperto da un altro programma, chiudilo e riprova... \n" + ex.Message);
            }
        }
コード例 #47
0
 public WordDocHolder(WordprocessingDocument wordDocument)
 {
     WordDocument = wordDocument;
     InitPageSize();
     InitDefaultFontInfo();
 }
コード例 #48
0
ファイル: OxPtHelpers.cs プロジェクト: zinda2000/EasyOffice
        public static void ConvertToHtml(string file, string outputDirectory)
        {
            var fi = new FileInfo(file);

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

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

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

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

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

                    var htmlString = html.ToString(SaveOptions.DisableFormatting);
                    File.WriteAllText(destFileName.FullName, htmlString, Encoding.UTF8);
                }
            }
        }
コード例 #49
0
        public void FillConcreteContract(DomainCustomerCredit customerCredit)
        {
            if (!File.Exists(_templateDocPath))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(_templateDocPath));
                GenerateCreditContractTemplate();
            }

            var byteArray = File.ReadAllBytes(_templateDocPath);
            //            using (var fs = new FileStream(string.Format("{0}{1}.docx", CreditContractsDocPath, customerCredit.ContractNumber),FileMode.Create))
            {
                using (var stream = new MemoryStream())
                {
                    stream.Write(byteArray, 0, byteArray.Length);
                    using (var wordDoc = WordprocessingDocument.Open(stream, true))
                    {
                        var body = wordDoc.MainDocumentPart.Document.Body;
                        var runs = body.Descendants <Run>().ToList();
                        var i    = 0;

                        //contract number
                        FindAndReplace(ref i, runs, ContractNumberPlace, " " + customerCredit.ContractNumber);

                        //day & month
                        FindAndReplace(ref i, runs, DaymonthPlace, customerCredit.StartDate.ToString("dd MM"));

                        //year
                        FindAndReplace(ref i, runs, YearPlace, " " + customerCredit.StartDate.ToString("yyyy"));

                        //customerPlace
                        FindAndReplace(ref i, runs, CustomerPlace,
                                       string.Format("{0} {1}{2}", customerCredit.Customer.Lastname,
                                                     customerCredit.Customer.Firstname,
                                                     customerCredit.Customer.Patronymic != null
                                    ? " " + customerCredit.Customer.Patronymic
                                    : ""), UnderlineValues.None);

                        //credit name
                        FindAndReplace(ref i, runs, CreditPlace, customerCredit.Credit.Name);

                        //sum
                        FindAndReplace(ref i, runs, CreditSumPlace, customerCredit.CreditSum.ToString());

                        //since
                        FindAndReplace(ref i, runs, SincePlace, customerCredit.StartDate.ToString("dd.MM.yyyy"));

                        //end date
                        FindAndReplace(ref i, runs, UntilPlace, customerCredit.EndDate.ToString("dd.MM.yyyy"));

                        //percent rate
                        FindAndReplace(ref i, runs, PercentRatePlace, customerCredit.Credit.PercentRate.ToString());

                        //payment day
                        FindAndReplace(ref i, runs, PaymentDayPlace, customerCredit.StartDate.ToString("dd"));

                        wordDoc.MainDocumentPart.Document.Save();
                        //                        wordDoc.MainDocumentPart.Document.Save(fs);
                        File.WriteAllBytes(
                            string.Format("{0}{1}.docx", _creditContractsDocPath, customerCredit.ContractNumber),
                            stream.ToArray());
                    }
                }
            }
        }
コード例 #50
0
 public DocxDocumentPlaceholderContextBuilder(WordprocessingDocument document, RunProperties runProperties)
     : base(document)
 {
     _runProperties = runProperties;
 }
コード例 #51
0
        //this text replacer will replace a list of values by searching all over the doc and replace first instance
        public void ReplacePlaceholders(List <PlaceholderReplacer> placeholderReplacerList, string templateDocxFullNameAndPath, string SaveAsDocxFullNameAndPath)
        {
            string worddocFullNameAndPath = string.Empty;

            try
            {
                //make a copy if the source and save paths are different

                if (templateDocxFullNameAndPath.ToLower() != SaveAsDocxFullNameAndPath.ToLower())
                {
                    File.Copy(templateDocxFullNameAndPath, SaveAsDocxFullNameAndPath, true);
                    if (File.Exists(SaveAsDocxFullNameAndPath) == false)
                    {
                        //raise exception if save as not created
                        throw new Exception("Exception creating a copy of template in WordTemplateTextReplace cause unknown");
                    }
                    else
                    {
                        worddocFullNameAndPath = SaveAsDocxFullNameAndPath;
                    }
                }
                else
                {
                    //in this case template itself will change
                    worddocFullNameAndPath = templateDocxFullNameAndPath;
                }

                using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(worddocFullNameAndPath, true))
                {
                    foreach (PlaceholderReplacer placeholderReplacer in placeholderReplacerList)
                    {
                        if (placeholderReplacer.IsHtml)
                        {
                            //locate placeholder or key in doc
                            foreach (var paragraph in wordDoc.MainDocumentPart.RootElement.Descendants <Paragraph>())
                            {
                                if (paragraph.InnerText.Contains(placeholderReplacer.Placeholder) != true)
                                {
                                    continue;
                                }

                                bool hasJunk = placeholderReplacer.Replacer.Contains("/xml");
                                //hasJunk = true;
                                if (hasJunk)
                                {
                                    HtmlDocument htmlDocument = new HtmlDocument();
                                    htmlDocument.LoadHtml(placeholderReplacer.Replacer);

                                    while (hasJunk)
                                    {
                                        //use recursion if editor has further inner junk nodes
                                        foreach (var htmlNode in htmlDocument.DocumentNode.ChildNodes)
                                        {
                                            if (((htmlNode.InnerHtml.Contains("<xml") == true) || (htmlNode.NodeType == HtmlNodeType.Text) || (htmlNode.NodeType == HtmlNodeType.Comment)) && (htmlNode.InnerHtml.Contains("<span") == false))
                                            {
                                                htmlNode.ParentNode.RemoveChild(htmlNode, false);

                                                break;
                                            }
                                            if (htmlNode.InnerHtml.Contains("<span") == true && (htmlNode.InnerHtml.Contains("<xml") == true))
                                            {
                                                string innerhtmlForSpan = string.Empty;
                                                //in this case only span to be extracted and placed in para as innertext
                                                foreach (var htmlNodeInner in htmlNode.ChildNodes)
                                                {
                                                    if (htmlNodeInner.NodeType != HtmlNodeType.Comment)
                                                    {
                                                        innerhtmlForSpan += htmlNodeInner.OuterHtml;
                                                    }
                                                }
                                                htmlNode.InnerHtml = innerhtmlForSpan;

                                                break;
                                            }
                                        }

                                        if ((htmlDocument.DocumentNode.InnerHtml.Contains("<xml")) || (htmlDocument.DocumentNode.InnerHtml.Contains("\r")))
                                        {
                                            hasJunk = true;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }

                                    //foreach (var htmlNode in htmlDocument.DocumentNode.ChildNodes)
                                    //{
                                    //    if ((htmlNode.InnerHtml.Contains("/xml") == true) || (htmlNode.NodeType == HtmlNodeType.Text))
                                    //    {
                                    //        htmlNode.ParentNode.RemoveChild(htmlNode, false);

                                    //        break;
                                    //    }
                                    //}

                                    foreach (var htmlNode in htmlDocument.DocumentNode.ChildNodes)
                                    {
                                        if ((htmlNode.Name == "p") && (htmlNode.Attributes.Count > 0))
                                        {
                                            //htmlNode.ParentNode.RemoveChild(htmlNode, false);

                                            htmlNode.Attributes.RemoveAll();
                                        }
                                    }
                                    string backslashremoved = htmlDocument.DocumentNode.InnerHtml.Replace("\"", "'");

                                    placeholderReplacer.Replacer = backslashremoved;
                                }

                                string replacer = string.Empty;

                                //Convert para without breaks into para with breaks
                                replacer = placeholderReplacer.Replacer;

                                //addprefix to identify first para
                                string paraID = "#FirstPara#";
                                replacer = paraID + replacer.Trim();

                                //create breaks next to para
                                replacer = replacer.Replace("<p>", "<p><br/>");

                                //remove firstpara ID
                                replacer = replacer.Replace(paraID + "<p><br/>", "<p>");

                                replacer = replacer.Replace(paraID, "");


                                //incase placeholder matches check if prefix is to be added
                                if ((placeholderReplacer.InlinePrefixHtmlText != null) && (placeholderReplacer.InlinePrefixHtmlText.Trim() != string.Empty))
                                {
                                    replacer = placeholderReplacer.InlinePrefixHtmlText + replacer;
                                }
                                //else
                                //{
                                //   replacer = placeholderReplacer.Replacer;
                                //}
                                //extract inner html from html replacer

                                //var htmlNode = HtmlNode.CreateNode(placeholderReplacer.Replacer);

                                //appy para tag

                                //string  innerHtml = "<p>" + replacer + "</p>";
                                string innerHtml = replacer;

                                //init Html to openxml converter
                                HtmlToOpenXml htmlToOpenXml = new HtmlToOpenXml();

                                List <ParagraphImageData> listOfImageData = new List <ParagraphImageData>();
                                try
                                {
                                    //replace para inner open xml with the one returned from Html to openXml convert function
                                    paragraph.InnerXml = htmlToOpenXml.ConvertHtmlToOpenXml(innerHtml, listOfImageData);


                                    // get all images in paragraph
                                    List <A.Blip> imagesInParagraph = paragraph.Descendants <A.Blip>().ToList();

                                    if (imagesInParagraph.Any())
                                    {
                                        foreach (var imageInParagraph in imagesInParagraph)
                                        {
                                            string embed = imageInParagraph.Embed;

                                            ////find all original image names in paragraph
                                            //var paragraphImageNames =
                                            //    paragraph.Descendants<A.Pictures.NonVisualDrawingProperties>().ToList();

                                            ////fetch imageparts list from document
                                            var imageParts = wordDoc.MainDocumentPart.ImageParts;

                                            //locate
                                            foreach (var imageData in listOfImageData)
                                            {
                                                if (embed == imageData.ImageEmbedId)
                                                {
                                                    if (imageData.IsAddedToDocument == false)
                                                    {
                                                        var imagePart =
                                                            wordDoc.MainDocumentPart.AddImagePart(
                                                                imageData.ImageContentType);

                                                        imageData.ImageStream.Seek(0, SeekOrigin.Begin);
                                                        imagePart.FeedData(imageData.ImageStream);

                                                        var id = wordDoc.MainDocumentPart.GetIdOfPart(imagePart);
                                                        imageInParagraph.Embed      = id;
                                                        imageData.ImageNewID        = id;
                                                        imageData.IsAddedToDocument = true;
                                                    }
                                                    else
                                                    {
                                                        imageInParagraph.Embed = imageData.ImageNewID;
                                                    }
                                                }
                                            }
                                        }
                                        foreach (var imageData in listOfImageData)
                                        {
                                            imageData.ImageStream.Close();
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    //exception
                                }
                                finally
                                {
                                    //for imagestreams dispose is essential as they r inmemory datatypes that need to dispose
                                    foreach (var imageData in listOfImageData)
                                    {
                                        imageData.ImageStream.Dispose();
                                    }
                                }

                                wordDoc.Save();
                            }
                        }
                    }
                    wordDoc.Save();
                    wordDoc.Close();
                }

                using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(worddocFullNameAndPath, true))
                {
                    foreach (PlaceholderReplacer placeholderReplacer in placeholderReplacerList)
                    {
                        string replacer = placeholderReplacer.Replacer.Replace("\f", "");
                        replacer = replacer.Replace("\n", "");
                        replacer = replacer.Replace("\r", "");
                        replacer = replacer.Replace("\a", "");
                        replacer = replacer.Replace("\b", "");
                        replacer = replacer.Replace("\t", "");
                        replacer = replacer.Replace("\v", "");

                        OPTools.TextReplacer.SearchAndReplace(wordDoc, placeholderReplacer.Placeholder, replacer, false);
                    }
                    wordDoc.Save();
                    wordDoc.Close();
                }

                using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(worddocFullNameAndPath, false))
                {
                    //if (wordDoc.MainDocumentPart.Document.InnerText.Contains("#PH#") == true)
                    //{
                    //    throw new Exception("template to doc creation not successfull, some placeholders are still not updated");
                    //}
                    wordDoc.Close();
                }
            }
            catch (Exception ex)
            {
                //exception if occur site page will not show exception on ui, word will show no updation in template
                //todo: later log exceptions to mails or log files
            }
        }
コード例 #52
0
        static int RunOptions(Options opts)
        {
            if (opts.ListTypes)
            {
                return(RunListTypes());
            }

            try
            {
                OpenXmlPackage package;
                if (string.IsNullOrEmpty(opts.Input))
                {
                    Console.Error.WriteLine("#TODO");
                    return(1);
                }
                if (string.IsNullOrEmpty(opts.Type))
                {
                    Console.Error.WriteLine("[Error] Specify -t, --type. Just use either Document or Workbook if you want to insert URLs.");
                    return(1);
                }
                switch (opts.Type)
                {
                case "Document":
                case "MacroEnabledDocument":
                case "MacroEnabledTemplate":
                case "Template":
                    using (var document = WordprocessingDocument.Open(opts.Input, false))
                    {
                        package = document.Clone();
                    }
                    break;

                case "Workbook":
                case "MacroEnabledWorkbook":
                case "MacroEnabledTemplateX":
                case "TemplateX":
                    using (var document = SpreadsheetDocument.Open(opts.Input, false))
                    {
                        package = document.Clone();
                    }
                    break;

                default:
                    Console.Error.WriteLine("[Error] Specify correct document type, use --list-types to view types.");
                    return(1);
                }

                if (opts.Inspect)
                {
                    return(RunInspect(package));
                }
                if (File.Exists(opts.Metadata))
                {
                    var obj = JObject.Parse(File.ReadAllText(opts.Metadata));
                    Utils.ModifyMetadata(package, obj);
                }
                if (!string.IsNullOrEmpty(opts.Url))
                {
                    if (opts.Template)
                    {
                        WordprocessingDocument document = (WordprocessingDocument)package;
                        document.InsertTemplateURI(opts.Url);
                    }
                    else
                    {
                        string name = package.GetType().Name;
                        if (name == "WordprocessingDocument")
                        {
                            WordprocessingDocument document = (WordprocessingDocument)package;
                            document.InsertTrackingURI(opts.Url);
                        }
                        else if (name == "SpreadsheetDocument")
                        {
                            SpreadsheetDocument workbook = (SpreadsheetDocument)package;
                            workbook.InsertTrackingURI(opts.Url);
                        }
                    }
                }
                if (string.IsNullOrEmpty(opts.Output))
                {
                    Console.Error.WriteLine("[Error] Specify -o, --output.");
                    return(1);
                }

                package.SaveAs(opts.Output);
            }
            catch (OpenXmlPackageException)
            {
                Console.Error.WriteLine("[Error] Document type mismatch.");
                return(1);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("[Error] {0}", e.Message);
                return(1);
            }
            return(0);
        }
コード例 #53
0
        /// <summary>
        /// MSDN code sample
        /// https://docs.microsoft.com/en-us/office/open-xml/how-to-insert-a-picture-into-a-word-processing-document
        ///
        /// There is one issue, EditId attribute is not in the current SDK. This was learned by validating a document
        /// using <see cref="ValidateCorruptedWordDocument"/>. It has been commented out in the event someone wants
        /// to work with this code with an earlier release of the SDK.
        /// </summary>
        /// <param name="document"></param>
        /// <param name="relationshipId"></param>
        /// <param name="pWidth"></param>
        /// <param name="pHeight"></param>
        public static void AddImageToBody(WordprocessingDocument document, string relationshipId, int pWidth, int pHeight)
        {
            // Define the reference of the image.
            var element =
                new Drawing(
                    new Inline(
                        new Extent()
            {
                Cx = pWidth, Cy = pHeight
            },
                        new EffectExtent()
            {
                LeftEdge   = 0L,
                TopEdge    = 0L,
                RightEdge  = 0L,
                BottomEdge = 0L
            },
                        new DocProperties()
            {
                Id   = (UInt32Value)1U,
                Name = "Picture 1"
            },
                        new NonVisualGraphicFrameDrawingProperties(
                            new GraphicFrameLocks()
            {
                NoChangeAspect = true
            }),
                        new Graphic(
                            new GraphicData(
                                new Picture(
                                    new NonVisualPictureProperties(
                                        new NonVisualDrawingProperties()
            {
                Id   = (UInt32Value)0U,
                Name = "New Bitmap Image.jpg"
            },
                                        new NonVisualPictureDrawingProperties()),
                                    new BlipFill(
                                        new Blip(
                                            new BlipExtensionList(
                                                new BlipExtension()
            {
                Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"
            })
                                            )
            {
                Embed            = relationshipId,
                CompressionState =
                    BlipCompressionValues.Print
            },
                                        new Stretch(
                                            new FillRectangle())),
                                    new ShapeProperties(
                                        new Transform2D(
                                            new Offset()
            {
                X = 0L, Y = 0L
            },
                                            new Extents()
            {
                Cx = pWidth, Cy = pHeight
            }),
                                        new PresetGeometry(
                                            new AdjustValueList()
                                            )
            {
                Preset = ShapeTypeValues.Rectangle
            }))
                                )
            {
                Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
            })
                        )
            {
                DistanceFromTop    = (UInt32Value)0U,
                DistanceFromBottom = (UInt32Value)0U,
                DistanceFromLeft   = (UInt32Value)0U,
                DistanceFromRight  = (UInt32Value)0U         //,EditId = "50D07946" this is from an older release of the SDK
            });

            // Append the reference to body, the element should be in a Run.
            document.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
        }
コード例 #54
0
        private void otherSectionHeader(List <SectionProperties> list, List <int> intlist, WordprocessingDocument wordpro, string docxPath, XmlNode root, XmlDocument xmlDocx, string name, int flag)
        {
            MainDocumentPart Mpart = wordpro.MainDocumentPart;
            // List<int> sectionnumber = new List<int>(20);
            HeaderReference headerfirst   = null;
            HeaderReference headereven    = null;
            HeaderReference headerdefault = null;

            if (list.Count == 0)
            {
                return;
            }
            SectionProperties             s      = list[0];
            IEnumerable <HeaderReference> headrs = s.Elements <HeaderReference>();

            foreach (HeaderReference headr in headrs)
            {
                if (headr.Type == HeaderFooterValues.First)
                {
                    headerfirst = headr;
                }
                if (headr.Type == HeaderFooterValues.Even)
                {
                    headereven = headr;
                }
                if (headr.Type == HeaderFooterValues.Default)
                {
                    headerdefault = headr;
                }
            }
            for (int i = 2; i <= list.Count <SectionProperties>(); i++)
            {
                bool no2pageinsecondsection = !no2PageInfirstSection(intlist[0], wordpro.MainDocumentPart.Document.Body);
                s = list[i - 1];
                List <int> chapterTitle = Tool.getTitlePosition(wordpro);
                string     chapter      = Tool.Chapter(chapterTitle, intlist[i - 1], wordpro.MainDocumentPart.Document.Body);

                TitlePage tp = s.GetFirstChild <TitlePage>();

                headrs = s.Elements <HeaderReference>();
                foreach (HeaderReference headr in headrs)
                {
                    if (headr.Type == HeaderFooterValues.First)
                    {
                        headerfirst = headr;
                    }
                    if (headr.Type == HeaderFooterValues.Even)
                    {
                        headereven = headr;
                    }
                    if (headr.Type == HeaderFooterValues.Default)
                    {
                        headerdefault = headr;
                    }
                }
                if (tp != null)
                {
                    //合乎规范
                    XmlElement xml = xmlDocx.CreateElement("Text");
                    xml.InnerText = "页眉命名不规范,不应该设置首页不同||" + chapter;
                    root.AppendChild(xml);
                }
                else
                {
                    //奇数页
                    if (headerdefault == null)
                    {
                        if (no2pageinsecondsection)//检测独创性声明页在不在第二节
                        {
                            continue;
                        }

                        /*else
                         * {
                         *
                         * }*/
                    }
                    string     ID     = headerdefault.Id.ToString();
                    HeaderPart hp     = (HeaderPart)Mpart.GetPartById(ID);
                    Header     header = hp.Header;
                    Paragraph  p      = header.GetFirstChild <Paragraph>();
                    if (header.InnerText != null)
                    {
                        string headername = header.InnerText.Trim();
                        //字体
                        if (!Tool.correctfonts(p, wordpro, "宋体", "Times New Roman"))
                        {
                            XmlElement xml = xmlDocx.CreateElement("Text");
                            xml.InnerText = "页眉字体应为宋体||" + chapter;
                            root.AppendChild(xml);
                        }
                        //字号
                        if (!Tool.correctsize(p, wordpro, "21"))
                        {
                            XmlElement xml = xmlDocx.CreateElement("Text");
                            xml.InnerText = "页眉字号应为五号||" + chapter;
                            root.AppendChild(xml);
                        }
                        //居中
                        if (!JustificationCenter(p, Mpart))
                        {
                            XmlElement xml = xmlDocx.CreateElement("Text");
                            xml.InnerText = "页眉应居中||" + chapter;
                            root.AppendChild(xml);
                        }
                        if (flag == 1)
                        {
                            //合乎规范
                            if (!no2pageinsecondsection)
                            {
                                if (headername != "大连理工大学专业学位硕士学位论文")
                                {
                                    XmlElement xml = xmlDocx.CreateElement("Text");
                                    xml.InnerText = "奇数页页眉命名不规范应为:“大连理工大学专业学位硕士学位论文”||" + chapter;
                                    root.AppendChild(xml);
                                }
                            }
                            else
                            {
                                if (i != 2)
                                {
                                    if (headername != "大连理工大学专业学位硕士学位论文")
                                    {
                                        XmlElement xml = xmlDocx.CreateElement("Text");
                                        xml.InnerText = "奇数页页眉命名不规范应为:“大连理工大学专业学位硕士学位论文”||" + chapter;
                                        root.AppendChild(xml);
                                    }
                                }
                            }
                        }
                        if (flag == 0)
                        {
                            if (!no2pageinsecondsection)
                            {
                                if (headername != "大连理工大学硕士学位论文")
                                {
                                    XmlElement xml = xmlDocx.CreateElement("Text");
                                    xml.InnerText = "奇数页页眉命名不规范应为:“大连理工大学硕士学位论文”||" + chapter;
                                    root.AppendChild(xml);
                                }
                            }
                            else
                            {
                                if (i != 2)
                                {
                                    if (headername != "大连理工大学硕士学位论文")
                                    {
                                        XmlElement xml = xmlDocx.CreateElement("Text");
                                        xml.InnerText = "奇数页页眉命名不规范应为:“大连理工大学硕士学位论文”||" + chapter;
                                        root.AppendChild(xml);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        XmlElement xml = xmlDocx.CreateElement("Text");
                        xml.InnerText = "缺少奇数页页眉||" + chapter;
                        root.AppendChild(xml);
                    }
                    //偶数页
                    ID     = headereven.Id.ToString();
                    hp     = (HeaderPart)Mpart.GetPartById(ID);
                    header = hp.Header;
                    if (header.InnerText != null)
                    {
                        //字体
                        if (!Tool.correctfonts(p, wordpro, "宋体", "Times New Roman"))
                        {
                            XmlElement xml = xmlDocx.CreateElement("Text");
                            xml.InnerText = "页眉字体应为宋体||" + chapter;
                            root.AppendChild(xml);
                        }
                        //字号
                        if (!Tool.correctsize(p, wordpro, "21"))
                        {
                            XmlElement xml = xmlDocx.CreateElement("Text");
                            xml.InnerText = "页眉字号应为五号||" + chapter;
                            root.AppendChild(xml);
                        }
                        //居中
                        if (!JustificationCenter(p, Mpart))
                        {
                            XmlElement xml = xmlDocx.CreateElement("Text");
                            xml.InnerText = "页眉应居中||" + chapter;
                            root.AppendChild(xml);
                        }
                        string headername = header.GetFirstChild <Paragraph>().InnerText.Trim();
                        //合乎规范
                        if (!no2pageinsecondsection)
                        {
                            if (headername != name)
                            {
                                XmlElement xml = xmlDocx.CreateElement("Text");
                                xml.InnerText = "偶数页页眉命名不规范,应为论文中文题目||" + chapter;
                                root.AppendChild(xml);
                            }
                        }
                        else
                        {
                            if (i != 2)
                            {
                                if (headername != name)
                                {
                                    XmlElement xml = xmlDocx.CreateElement("Text");
                                    xml.InnerText = "偶数页页眉命名不规范,应为论文中文题目||" + chapter;
                                    root.AppendChild(xml);
                                }
                            }
                        }
                    }
                    else
                    {
                        XmlElement xml = xmlDocx.CreateElement("Text");
                        xml.InnerText = "缺少偶数页页眉||" + chapter;
                        root.AppendChild(xml);
                    }
                }
            }
        }
コード例 #55
0
        /*
         * function:the first page and the second should have no header
         * params: list:the list of sectPrs
         *      intlist:the location of sectPrs in body
         *      wordpro:
         *      docxpath:
         *      root:xml root
         *      xmlDocx
         * return:void
         */
        static private void firstSection(List <SectionProperties> list, List <int> intlist, WordprocessingDocument wordpro, string docxPath, XmlNode root, XmlDocument xmlDocx)
        {
            MainDocumentPart  Mpart = wordpro.MainDocumentPart;
            SectionProperties s     = null;

            if (list.Count == 0)
            {
                return;
            }
            s = list[0];
            TitlePage tp       = s.GetFirstChild <TitlePage>();
            int       location = intlist[0];
            bool      no2page  = no2PageInfirstSection(intlist[0], Mpart.Document.Body);
            IEnumerable <HeaderReference> headrs = s.Elements <HeaderReference>();
            HeaderReference headerfirst          = null;
            HeaderReference headereven           = null;
            HeaderReference headerdefault        = null;
            FooterReference footerfirst          = null;
            FooterReference footereven           = null;
            FooterReference footerdefault        = null;
            IEnumerable <FooterReference> footrs = s.Elements <FooterReference>();

            foreach (HeaderReference headr in headrs)
            {
                if (headr.Type == HeaderFooterValues.First)
                {
                    headerfirst = headr;
                }
                if (headr.Type == HeaderFooterValues.Even)
                {
                    headereven = headr;
                }
                if (headr.Type == HeaderFooterValues.Default)
                {
                    headerdefault = headr;
                }
            }
            foreach (FooterReference footr in footrs)
            {
                if (footr.Type == HeaderFooterValues.First)
                {
                    footerfirst = footr;
                }
                if (footr.Type == HeaderFooterValues.Even)
                {
                    footereven = footr;
                }
                if (footr.Type == HeaderFooterValues.Default)
                {
                    footerdefault = footr;
                }
            }
            //如果设置了首页不同
            if (tp != null)
            {
                if (headerfirst != null)
                {
                    string     ID     = headerfirst.Id.ToString();
                    HeaderPart hp     = (HeaderPart)Mpart.GetPartById(ID);
                    Header     header = hp.Header;
                    if (header.InnerText != null)
                    {
                        if (header.InnerText.Trim().Length > 0)
                        {
                            XmlElement xml = xmlDocx.CreateElement("Text");
                            xml.InnerText = "封面应无页眉";
                            root.AppendChild(xml);
                        }
                    }
                }
                if (footerfirst != null)
                {
                    string     ID     = footerfirst.Id.ToString();
                    FooterPart fp     = (FooterPart)Mpart.GetPartById(ID);
                    Footer     footer = fp.Footer;
                    if (footer.InnerText != null)
                    {
                        if (footer.InnerText.Trim().Length > 0)
                        {
                            XmlElement xml = xmlDocx.CreateElement("Text");
                            xml.InnerText = "封面应无页脚";
                            root.AppendChild(xml);
                        }
                    }
                }
                if (no2page)//若独创性说明在第一节内
                {
                    //查看是否设置了奇偶页不同
                    Settings setting = Mpart.DocumentSettingsPart.Settings;
                    if (setting.GetFirstChild <EvenAndOddHeaders>() != null)//若设置了奇偶页不同
                    {
                        if (headereven != null)
                        {
                            string     ID     = headereven.Id.ToString();
                            HeaderPart hp     = (HeaderPart)Mpart.GetPartById(ID);
                            Header     header = hp.Header;
                            if (header.InnerText != null)
                            {
                                if (header.InnerText.Trim().Length > 0)
                                {
                                    XmlElement xml = xmlDocx.CreateElement("Text");
                                    xml.InnerText = "独创性声明所在的页应无页眉";
                                    root.AppendChild(xml);
                                }
                            }
                        }
                        if (footereven != null)
                        {
                            string     ID     = footereven.Id.ToString();
                            FooterPart fp     = (FooterPart)Mpart.GetPartById(ID);
                            Footer     footer = fp.Footer;
                            if (footer.InnerText != null)
                            {
                                if (footer.InnerText.Trim().Length > 0)
                                {
                                    XmlElement xml = xmlDocx.CreateElement("Text");
                                    xml.InnerText = "封面应无页脚";
                                    root.AppendChild(xml);
                                }
                            }
                        }
                    }
                    else//若没有设置奇偶页不同
                    {
                        if (headerdefault != null)
                        {
                            string     ID     = headerdefault.Id.ToString();
                            HeaderPart hp     = (HeaderPart)Mpart.GetPartById(ID);
                            Header     header = hp.Header;
                            if (header.InnerText != null)
                            {
                                if (header.InnerText.Trim().Length > 0)
                                {
                                    XmlElement xml = xmlDocx.CreateElement("Text");
                                    xml.InnerText = "独创性声明所在的页应无页眉";
                                    root.AppendChild(xml);
                                }
                            }
                        }
                        if (footerdefault != null)
                        {
                            string     ID     = footerdefault.Id.ToString();
                            FooterPart fp     = (FooterPart)Mpart.GetPartById(ID);
                            Footer     footer = fp.Footer;
                            if (footer.InnerText != null)
                            {
                                if (footer.InnerText.Trim().Length > 0)
                                {
                                    XmlElement xml = xmlDocx.CreateElement("Text");
                                    xml.InnerText = "独创性声明所在的页应无页脚";
                                    root.AppendChild(xml);
                                }
                            }
                        }
                    }
                }
            }
            //若没有设置首页不同
            else
            {
                if (headerdefault != null)
                {
                    string     ID     = headerdefault.Id.ToString();
                    HeaderPart hp     = (HeaderPart)Mpart.GetPartById(ID);
                    Header     header = hp.Header;
                    if (header.InnerText != null)
                    {
                        if (header.InnerText.Trim().Length > 0)
                        {
                            XmlElement xml = xmlDocx.CreateElement("Text");
                            xml.InnerText = "封面应无页眉";
                            root.AppendChild(xml);
                        }
                    }
                }
                if (footerdefault != null)
                {
                    string     ID     = footerdefault.Id.ToString();
                    FooterPart fp     = (FooterPart)Mpart.GetPartById(ID);
                    Footer     footer = fp.Footer;
                    if (footer.InnerText != null)
                    {
                        if (footer.InnerText.Trim().Length > 0)
                        {
                            XmlElement xml = xmlDocx.CreateElement("Text");
                            xml.InnerText = "封面应无页脚";
                            root.AppendChild(xml);
                        }
                    }
                }
                if (no2page)//如果独创性说明在第一节
                {
                    Settings setting = Mpart.DocumentSettingsPart.Settings;
                    if (setting.GetFirstChild <EvenAndOddHeaders>() != null)//设置了奇偶页不同,则独创性说明是偶数页设置
                    {
                        if (headereven != null)
                        {
                            string     ID     = headereven.Id.ToString();
                            HeaderPart hp     = (HeaderPart)Mpart.GetPartById(ID);
                            Header     header = hp.Header;
                            if (header.InnerText != null)
                            {
                                if (header.InnerText.Trim().Length > 0)
                                {
                                    XmlElement xml = xmlDocx.CreateElement("Text");
                                    xml.InnerText = "独创性声明所在的页应无页眉";
                                    root.AppendChild(xml);
                                }
                            }
                        }
                        if (footereven != null)
                        {
                            string     ID     = footereven.Id.ToString();
                            FooterPart fp     = (FooterPart)Mpart.GetPartById(ID);
                            Footer     footer = fp.Footer;
                            if (footer.InnerText != null)
                            {
                                if (footer.InnerText.Trim().Length > 0)
                                {
                                    XmlElement xml = xmlDocx.CreateElement("Text");
                                    xml.InnerText = "独创性声明所在的页应无页脚";
                                    root.AppendChild(xml);
                                }
                            }
                        }
                    }
                    else//没有设置奇偶页不同
                    {
                        if (headerdefault != null)
                        {
                            string     ID     = headerdefault.Id.ToString();
                            HeaderPart hp     = (HeaderPart)Mpart.GetPartById(ID);
                            Header     header = hp.Header;
                            if (header.InnerText != null)
                            {
                                if (header.InnerText.Trim().Length > 0)
                                {
                                    XmlElement xml = xmlDocx.CreateElement("Text");
                                    xml.InnerText = "独创性声明所在的页应无页眉";
                                    root.AppendChild(xml);
                                }
                            }
                        }
                        if (footerdefault != null)
                        {
                            string     ID     = footerdefault.Id.ToString();
                            FooterPart fp     = (FooterPart)Mpart.GetPartById(ID);
                            Footer     footer = fp.Footer;
                            if (footer.InnerText != null)
                            {
                                if (footer.InnerText.Trim().Length > 0)
                                {
                                    XmlElement xml = xmlDocx.CreateElement("Text");
                                    xml.InnerText = "独创性声明所在的页应无页脚";
                                    root.AppendChild(xml);
                                }
                            }
                        }
                    }
                }
            }
            if (!no2page)//第二页独创性说明不在第一节
            {
                //确定独创性说明在不在第二节,不在报错
                if (!no2PageInfirstSection(intlist[1] - 1, Mpart.Document.Body))
                {
                    XmlElement xml = xmlDocx.CreateElement("Text");
                    xml.InnerText = "缺少独创性声明页";
                    root.AppendChild(xml);
                }
                else
                {
                    s      = list[1];
                    headrs = s.Elements <HeaderReference>();
                    tp     = s.GetFirstChild <TitlePage>();
                    foreach (HeaderReference headr in headrs)
                    {
                        if (headr.Type == HeaderFooterValues.First)
                        {
                            headerfirst = headr;
                        }
                        if (headr.Type == HeaderFooterValues.Even)
                        {
                            headereven = headr;
                        }
                        if (headr.Type == HeaderFooterValues.Default)
                        {
                            headerdefault = headr;
                        }
                    }
                    if (tp != null)//第二节设置了首页不同
                    {
                        if (headerfirst != null)
                        {
                            string     ID     = headerfirst.Id.ToString();
                            HeaderPart hp     = (HeaderPart)Mpart.GetPartById(ID);
                            Header     header = hp.Header;
                            if (header.InnerText != null)
                            {
                                if (header.InnerText.Trim().Length > 0)
                                {
                                    XmlElement xml = xmlDocx.CreateElement("Text");
                                    xml.InnerText = "独创性声明所在的页应无页眉";
                                    root.AppendChild(xml);
                                }
                            }
                        }
                        if (footerfirst != null)
                        {
                            string     ID     = footerfirst.Id.ToString();
                            FooterPart fp     = (FooterPart)Mpart.GetPartById(ID);
                            Footer     footer = fp.Footer;
                            if (footer.InnerText != null)
                            {
                                if (footer.InnerText.Trim().Length > 0)
                                {
                                    XmlElement xml = xmlDocx.CreateElement("Text");
                                    xml.InnerText = "独创性声明所在的页应无页脚";
                                    root.AppendChild(xml);
                                }
                            }
                        }
                    }
                    else//没有设置首页不同
                    {
                        Settings setting = Mpart.DocumentSettingsPart.Settings;
                        if (setting.GetFirstChild <EvenAndOddHeaders>() != null)//设置了奇偶页不同
                        {
                            if (headereven != null)
                            {
                                string     ID     = headereven.Id.ToString();
                                HeaderPart hp     = (HeaderPart)Mpart.GetPartById(ID);
                                Header     header = hp.Header;
                                if (header.InnerText != null)
                                {
                                    if (header.InnerText.Trim().Length > 0)
                                    {
                                        XmlElement xml = xmlDocx.CreateElement("Text");
                                        xml.InnerText = "独创性声明所在的页应无页眉";
                                        root.AppendChild(xml);
                                    }
                                }
                            }
                            if (footereven != null)
                            {
                                string     ID     = footereven.Id.ToString();
                                FooterPart fp     = (FooterPart)Mpart.GetPartById(ID);
                                Footer     footer = fp.Footer;
                                if (footer.InnerText != null)
                                {
                                    if (footer.InnerText.Trim().Length > 0)
                                    {
                                        XmlElement xml = xmlDocx.CreateElement("Text");
                                        xml.InnerText = "独创性声明所在的页应无页脚";
                                        root.AppendChild(xml);
                                    }
                                }
                            }
                        }
                        else//没有设置奇偶页不同
                        {
                            if (headerdefault != null)
                            {
                                string     ID     = headerdefault.Id.ToString();
                                HeaderPart hp     = (HeaderPart)Mpart.GetPartById(ID);
                                Header     header = hp.Header;
                                if (header.InnerText != null)
                                {
                                    if (header.InnerText.Trim().Length > 0)
                                    {
                                        XmlElement xml = xmlDocx.CreateElement("Text");
                                        xml.InnerText = "独创性声明所在的页应无页眉";
                                        root.AppendChild(xml);
                                    }
                                }
                            }
                            if (footerdefault != null)
                            {
                                string     ID     = footerdefault.Id.ToString();
                                FooterPart fp     = (FooterPart)Mpart.GetPartById(ID);
                                Footer     footer = fp.Footer;
                                if (footer.InnerText != null)
                                {
                                    if (footer.InnerText.Trim().Length > 0)
                                    {
                                        XmlElement xml = xmlDocx.CreateElement("Text");
                                        xml.InnerText = "独创性声明所在的页应无页脚";
                                        root.AppendChild(xml);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #56
0
        static void Main(string[] args)
        {
            var n      = DateTime.Now;
            var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second));

            tempDi.Create();

            WmlDocument solarSystemDoc = new WmlDocument("../../solar-system.docx");

            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(solarSystemDoc))
                using (WordprocessingDocument solarSystem = streamDoc.GetWordprocessingDocument())
                {
                    // get children elements of the <w:body> element
                    var q1 = solarSystem
                             .MainDocumentPart
                             .GetXDocument()
                             .Root
                             .Element(W.body)
                             .Elements();

                    // project collection of tuples containing element and type
                    var q2 = q1
                             .Select(
                        e =>
                    {
                        string keyForGroupAdjacent = ".NonContentControl";
                        if (e.Name == W.sdt)
                        {
                            keyForGroupAdjacent = e.Element(W.sdtPr)
                                                  .Element(W.tag)
                                                  .Attribute(W.val)
                                                  .Value;
                        }
                        if (e.Name == W.sectPr)
                        {
                            keyForGroupAdjacent = null;
                        }
                        return(new
                        {
                            Element = e,
                            KeyForGroupAdjacent = keyForGroupAdjacent
                        });
                    }
                        ).Where(e => e.KeyForGroupAdjacent != null);

                    // group by type
                    var q3 = q2.GroupAdjacent(e => e.KeyForGroupAdjacent);

                    // temporary code to dump q3
                    foreach (var g in q3)
                    {
                        Console.WriteLine("{0}:  {1}", g.Key, g.Count());
                    }
                    //Environment.Exit(0);


                    // validate existence of files referenced in content controls
                    foreach (var f in q3.Where(g => g.Key != ".NonContentControl"))
                    {
                        string   filename = "../../" + f.Key + ".docx";
                        FileInfo fi       = new FileInfo(filename);
                        if (!fi.Exists)
                        {
                            Console.WriteLine("{0} doesn't exist.", filename);
                            Environment.Exit(0);
                        }
                    }

                    // project collection with opened WordProcessingDocument
                    var q4 = q3
                             .Select(g => new
                    {
                        Group    = g,
                        Document = g.Key != ".NonContentControl" ?
                                   new WmlDocument("../../" + g.Key + ".docx") :
                                   solarSystemDoc
                    });

                    // project collection of OpenXml.PowerTools.Source
                    var sources = q4
                                  .Select(
                        g =>
                    {
                        if (g.Group.Key == ".NonContentControl")
                        {
                            return(new Source(
                                       g.Document,
                                       g.Group
                                       .First()
                                       .Element
                                       .ElementsBeforeSelf()
                                       .Count(),
                                       g.Group
                                       .Count(),
                                       false));
                        }
                        else
                        {
                            return(new Source(g.Document, false));
                        }
                    }
                        ).ToList();

                    DocumentBuilder.BuildDocument(sources, Path.Combine(tempDi.FullName, "solar-system-new.docx"));
                }
        }
コード例 #57
0
        public void AddTableFeature()
        {
            string[,] data = { { "Mike", "Amy" }, { "Mary", "Albert" } };

            using (WordprocessingDocument wordDocument =
                       WordprocessingDocument.Create(ArtifactsDir + "Add Table - OpenXML.docx",
                                                     WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
                mainPart.Document = new Document();

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

                Run run = para.AppendChild(new Run());
                run.AppendChild(new Text("Create text in body - Create wordprocessing document"));

                Table table = new Table();

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

                table.AppendChild(props);

                for (var i = 0; i <= data.GetUpperBound(0); i++)
                {
                    var tr = new TableRow();
                    for (var j = 0; j <= data.GetUpperBound(1); j++)
                    {
                        var tc = new TableCell();
                        tc.Append(new Paragraph(new Run(new Text(data[i, j]))));

                        // Assume you want automatically sized columns.
                        tc.Append(new TableCellProperties(
                                      new TableCellWidth {
                            Type = TableWidthUnitValues.Auto
                        }));

                        tr.Append(tc);
                    }

                    table.Append(tr);
                }

                mainPart.Document.Body.Append(table);
                mainPart.Document.Save();
            }
        }
コード例 #58
0
        /// <summary>
        /// Fills in a .docx file with the provided data.
        /// </summary>
        /// <param name="filename">Path to the template that must be used.</param>
        /// <param name="dataset">Dataset with the datatables to use to fill the document tables with.  Table names in the dataset should match the table names in the document.</param>
        /// <param name="values">Values to fill the document.  Keys should match the MERGEFIELD names.</param>
        /// <returns>The filled-in document.</returns>
        public static byte[] GetWordReport(byte[] fileByte, DataSet dataset, Dictionary <string, string> values)
        {
            // first read document in as stream
            byte[]   original = fileByte;
            string[] switches = null;

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

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

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

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

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

                    //        DataTable table = dataset.Tables[tablename];

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

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

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

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

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

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

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

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

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

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

                    //                nrow.Append(cell);
                    //            }

                    //            wtable.Append(nrow);
                    //        }

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

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

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

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

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

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

                    // process header(s)
                    foreach (HeaderPart hpart in docx.MainDocumentPart.HeaderParts)
                    {
                        //  2010/08/01: addition
                        ConvertFieldCodes(hpart.Header);

                        FillWordFieldsInElement(values, hpart.Header);
                        hpart.Header.Save();    // save header back in package
                    }

                    // process footer(s)
                    foreach (FooterPart fpart in docx.MainDocumentPart.FooterParts)
                    {
                        //  2010/08/01: addition
                        ConvertFieldCodes(fpart.Footer);

                        FillWordFieldsInElement(values, fpart.Footer);
                        fpart.Footer.Save();    // save footer back in package
                    }
                }

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

                return(data);
            }
        }
コード例 #59
0
ファイル: Program.cs プロジェクト: tilark/OpenXML
        /// <summary>
        /// 在DOC中创建一个表格,并且能够指定样式。能够指定行的高度,列的宽度,列的宽度能平分整个页面,
        /// </summary>
        /// <param name="fileName"></param>
        public static void CreateTable(string fileName)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Open(fileName, true))
            {
                Table           table   = new Table();
                TableProperties tblProp = new TableProperties(
                    new TableBorders(
                        new TopBorder()
                {
                    Val =
                        new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 12
                },
                        new BottomBorder()
                {
                    Val =
                        new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 12
                },
                        new LeftBorder()
                {
                    Val =
                        new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 12
                },
                        new RightBorder()
                {
                    Val =
                        new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 12
                },
                        new InsideHorizontalBorder()
                {
                    Val =
                        new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 12
                },
                        new InsideVerticalBorder()
                {
                    Val =
                        new EnumValue <BorderValues>(BorderValues.Single),
                    Size = 12
                }
                        )
                    );

                table.AppendChild <TableProperties>(tblProp);

                TableRow tr = new TableRow();

                TableCell tc1 = new TableCell();

                tc1.Append(new TableCellProperties(new TableCellWidth()
                {
                    Type = TableWidthUnitValues.Pct, Width = "100%"
                }));
                tc1.Append(new Paragraph(new Run(new Text("你好!"))));
                tr.Append(tc1);

                //TableCell tc2 = new TableCell(tc1.OuterXml);
                //tr.Append(tc2);
                table.Append(tr);
                //TableRow tbrow2 = new TableRow(tr.OuterXml);
                //table.Append(tbrow2);
                List <string> listTest = new List <string>();
                for (int i = 0; i < 3; i++)
                {
                    listTest.Add("String" + i.ToString());
                }
                CreateOneRowWithText(table, listTest);
                CreateOneRowWithText(table, listTest);

                doc.MainDocumentPart.Document.Body.Append(table);
            }
        }
コード例 #60
0
        public IServiceResult <MemoryStream> CreateDiplomaCard(ProposalDocRecord record)
        {
            string imagePath = Path.Combine(_hostingEnvironment.WebRootPath, "images", "putLogo.jpeg");

            using (MemoryStream mem = new MemoryStream())
            {
                using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document))
                {
                    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

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

                    var image = _drawingGetter.getPutLogo(mainPart, imagePath);
                    body.AppendChild(new Paragraph(new Run(image)));

                    body.AppendChild(_paragraphGetter.getTitle(record));

                    body.AppendChild(new Paragraph(new Run(new Text(""))));
                    body.AppendChild(new Paragraph(new Run(new Text(""))));

                    body.AppendChild(_tableGetter.getTableWithUniversityInformation(record));

                    body.AppendChild(new Paragraph(new Run(new Text(""))));

                    body.AppendChild(_paragraphGetter.getClause());

                    body.AppendChild(_tableGetter.getTableWithStudentsInformation(record));

                    body.AppendChild(new Paragraph(new Run(new Text(""))));
                    body.AppendChild(new Paragraph(new Run(new Text(""))));

                    body.AppendChild(_tableGetter.getTableWithProposalInformation(record));

                    body.AppendChild(new Paragraph(new Run(new Text(""))));
                    body.AppendChild(new Paragraph(new Run(new Text(""))));

                    body.Append(_tableGetter.getTableWithSignature());

                    body.AppendChild(new Paragraph(new Run(new Text(""))));

                    body.Append(_tableGetter.getTableWithCity(record));

                    var sectionProp = new SectionProperties(
                        new PageSize()
                    {
                        Width = 11906, Height = 16838
                    },
                        new PageMargin()
                    {
                        Left = 1417, Gutter = 0, Footer = 708, Header = 708, Bottom = 709, Right = 1417, Top = 567
                    },
                        new Columns()
                    {
                        Space = "708"
                    },
                        new DocGrid()
                    {
                        LinePitch = 360
                    }
                        );
                    body.Append(sectionProp);

                    wordDocument.Close();
                }

                return(ServiceResult <MemoryStream> .Success(mem));
            }
        }