Coder Social home page Coder Social logo

evotecit / officeimo Goto Github PK

View Code? Open in Web Editor NEW
263.0 8.0 47.0 14.12 MB

Fast and easy to use cross-platform .NET library that creates or modifies Microsoft Word (DocX) and later also Excel (XLSX) files without installing any software. Library is based on Open XML SDK

License: MIT License

C# 92.68% HTML 3.06% Rich Text Format 4.15% PowerShell 0.11%
docx openxml openxml-sdk office word c-sharp

officeimo's Introduction

OfficeIMO - Microsoft Word .NET Library

OfficeIMO is available as NuGet from the gallery and its preferred way of using it.

nuget downloads nuget version license nuget downloads

If you would like to contact me you can do so via Twitter or LinkedIn.

twitter blog linked

What it's all about

This is a small project (under development) that allows to create Microsoft Word documents (.docx) using .NET. Underneath it uses OpenXML SDK but heavily simplifies it. It was created because working with OpenXML is way too hard for me, and time consuming. I created it for use within the PowerShell module called PSWriteOffice, but thought it may be useful for others to use in the .NET community.

If you want to see what it can do take a look at this blog post.

I used to use the DocX library (which I co-authored/maintained before it was taken over by Xceed) to create Microsoft Word documents, but it only supports .NET Framework, and their newest community license makes the project unusable.

As I am not really a developer, and I hardly know what I'm doing if you know how to help out - please do.

  • If you see bad practice, please open an issue/submit PR.
  • If you know how to do something in OpenXML that could help this project - please open an issue/submit PR
  • If you see something that could work better - please open an issue/submit PR
  • If you see something that I made a fool of myself - please open an issue/submit PR
  • If you see something that works not the way I think it works - please open an issue/submit PR

I hope you get the drift? If it's bad - open an issue/fix it! I don't know what I'm doing! The main thing is - it has to work with .NET Framework 4.7.2, .NET Standard 2.0 and so on.

This project is under development and as such there's a lot of things that can and will change, especially if some people help out.

Platform Status Code Coverage .NET
Windows .NET 4.7.2, NET 4.8, .NET 6.0, .NET 7.0, .NET 8.0, .NET Standard 2.0, .NET Standard 2.1
Linux .NET 6.0, .NET 7.0, .NET Standard 2.0, .NET 8.0, .NET Standard 2.1
MacOs .NET 6.0, .NET 7.0, .NET Standard 2.0, .NET 8.0, .NET Standard 2.1

Support This Project

If you find this project helpful, please consider supporting its development. Your sponsorship will help the maintainers dedicate more time to maintenance and new feature development for everyone.

It takes a lot of time and effort to create and maintain this project. By becoming a sponsor, you can help ensure that it stays free and accessible to everyone who needs it.

To become a sponsor, you can choose from the following options:

Your sponsorship is completely optional and not required for using this project. We want this project to remain open-source and available for anyone to use for free, regardless of whether they choose to sponsor it or not.

If you work for a company that uses our .NET libraries or PowerShell Modules, please consider asking your manager or marketing team if your company would be interested in supporting this project. Your company's support can help us continue to maintain and improve this project for the benefit of everyone.

Thank you for considering supporting this project!

Please share with the community

Please consider sharing a post about OfficeIMO and the value it provides. It really does help!

Share on reddit Share on hacker news Share on twitter Share on facebook Share on linkedin

Features

Here's a list of features currently supported (and probably a lot I forgot) and those that are planned. It's not a closed list, more of TODO, and I'm sure there's more:

  • ☑️ Word basics
    • ☑️ Create
    • ☑️ Load
    • ☑️ Save (auto open on save as an option)
    • ☑️ SaveAs (auto open on save as an option)
  • ☑️ Word properties
    • ☑️ Reading basic and custom properties
    • ☑️ Setting basic and custom properties
  • ☑️ Sections
    • ☑️ Add Paragraphs
    • ☑️ Add Headers and Footers (Odd/Even/First)
    • ◼️ Remove Headers and Footers (Odd/Even/First)
    • ☑️ Remove Paragraphs
    • ◼️ Remove Sections
  • ☑️ Headers and Footers in the document (not including sections)
    • ☑️ Add Default, Odd, Even, First
    • ◼️ Remove Default, Odd, Even, First
  • ☑️ Paragraphs/Text and make it bold, underlined, colored and so on
  • ☑️ Paragraphs and change alignment
  • ☑️ Tables
  • ☑️ Images/Pictures (limited support - jpg only / inline type only)
    • ☑️ Add images from file to Word
    • ☑️ Save image from Word to File
    • ◼️ Other image types
    • ◼️ Other location types
  • ☑️ Hyperlinks
    • ☑️ Add HyperLink
    • ☑️ Read HyperLink
    • ◼️ Remove HyperLink
    • ☑️ Change HyperLink
  • ☑️ PageBreaks
    • ☑️ Add PageBreak
    • ☑️ Read PageBreak
    • ☑️ Remove PageBreak
    • ☑️ Change PageBreak
  • ☑️ Bookmarks
    • ☑️ Add Bookmark
    • ☑️ Read Bookmark
    • ☑️ Remove Bookmark
    • ☑️ Change Bookmark
  • ◼️ Comments
    • ☑️ Add comments
    • ☑️ Read comments
    • ◼️ Remove comments
    • ◼️ Track comments
  • ☑️ Fields
    • ☑️ Add Field
    • ☑️ Read Field
    • ☑️ Remove Field
    • ☑️ Change Field
  • ☑️ Footnotes
    • ☑️ Add new footnotes
    • ☑️ Read footnotes
    • ☑️ Remove footnotes
  • ☑️ Endnotes
    • ☑️Add new endnotes
    • ☑️Read endnotes
    • ☑️Remove endnotes
  • ◼️ Shapes
  • ◼️ Charts
    • ☑️ Add charts
  • ◼️ Lists
    • ☑️ Add lists
    • ◼️ Remove lists
  • ◼️ Table of contents
    • ☑️ Add TOC
  • ☑️ Borders
  • ☑️ Background
  • ◼️ Watermarks
    • ☑️ Add watermark
    • ◼️ Remove watermark
  • ☑️ PageBreaks
    • ☑️Add pagebreak
    • ☑️Find pagebreak
    • ☑️Remove pagebreak

Features (oneliners):

This list of features is for times when you want to quickly fix something rather than playing with full features. This features are available as part of WordHelpers class.

  • ☑️ Remove Headers and Footers from a file

Examples

Basic Document with few document properties and paragraph

This short example show how to create Word Document with just one paragraph with Text and few document properties.

string filePath = @"C:\Support\GitHub\PSWriteOffice\Examples\Documents\BasicDocument.docx";

using (WordDocument document = WordDocument.Create(filePath)) {
    document.Title = "This is my title";
    document.Creator = "Przemysław Kłys";
    document.Keywords = "word, docx, test";

    var paragraph = document.AddParagraph("Basic paragraph");
    paragraph.ParagraphAlignment = JustificationValues.Center;
    paragraph.Color = SixLabors.ImageSharp.Color.Red;

    document.Save(true);
}

Basic Document with Headers/Footers (first, odd, even)

This short example shows how to add headers and footers to Word Document.

using (WordDocument document = WordDocument.Create(filePath)) {
    document.Sections[0].PageOrientation = PageOrientationValues.Landscape;
    document.AddParagraph("Test Section0");
    document.AddHeadersAndFooters();
    document.DifferentFirstPage = true;
    document.DifferentOddAndEvenPages = true;

    document.Sections[0].Header.First.AddParagraph().SetText("Test Section 0 - First Header");
    document.Sections[0].Header.Default.AddParagraph().SetText("Test Section 0 - Header");
    document.Sections[0].Header.Even.AddParagraph().SetText("Test Section 0 - Even");

    document.AddPageBreak();
    document.AddPageBreak();
    document.AddPageBreak();
    document.AddPageBreak();

    var section1 = document.AddSection();
    section1.PageOrientation = PageOrientationValues.Portrait;
    section1.AddParagraph("Test Section1");
    section1.AddHeadersAndFooters();
    section1.Header.Default.AddParagraph().SetText("Test Section 1 - Header");
    section1.DifferentFirstPage = true;
    section1.Header.First.AddParagraph().SetText("Test Section 1 - First Header");

    document.AddPageBreak();
    document.AddPageBreak();
    document.AddPageBreak();
    document.AddPageBreak();

    var section2 = document.AddSection();
    section2.AddParagraph("Test Section2");
    section2.PageOrientation = PageOrientationValues.Landscape;
    section2.AddHeadersAndFooters();
    section2.Header.Default.AddParagraph().SetText("Test Section 2 - Header");

    document.AddParagraph("Test Section2 - Paragraph 1");

    var section3 = document.AddSection();
    section3.AddParagraph("Test Section3");
    section3.AddHeadersAndFooters();
    section3.Header.Default.AddParagraph().SetText("Test Section 3 - Header");

    Console.WriteLine("Section 0 - Text 0: " + document.Sections[0].Paragraphs[0].Text);
    Console.WriteLine("Section 1 - Text 0: " + document.Sections[1].Paragraphs[0].Text);
    Console.WriteLine("Section 2 - Text 0: " + document.Sections[2].Paragraphs[0].Text);
    Console.WriteLine("Section 2 - Text 1: " + document.Sections[2].Paragraphs[1].Text);
    Console.WriteLine("Section 3 - Text 0: " + document.Sections[3].Paragraphs[0].Text);

    Console.WriteLine("Section 0 - Text 0: " + document.Sections[0].Header.Default.Paragraphs[0].Text);
    Console.WriteLine("Section 1 - Text 0: " + document.Sections[1].Header.Default.Paragraphs[0].Text);
    Console.WriteLine("Section 2 - Text 0: " + document.Sections[2].Header.Default.Paragraphs[0].Text);
    Console.WriteLine("Section 3 - Text 0: " + document.Sections[3].Header.Default.Paragraphs[0].Text);
    document.Save(true);
}

Advanced usage of OfficeIMO

This short example shows multiple features of OfficeIMO.Word

string filePath = System.IO.Path.Combine(folderPath, "AdvancedDocument.docx");
using (WordDocument document = WordDocument.Create(filePath)) {
    // lets add some properties to the document
    document.BuiltinDocumentProperties.Title = "Cover Page Templates";
    document.BuiltinDocumentProperties.Subject = "How to use Cover Pages with TOC";
    document.ApplicationProperties.Company = "Evotec Services";

    // we force document to update fields on open, this will be used by TOC
    document.Settings.UpdateFieldsOnOpen = true;

    // lets add one of multiple added Cover Pages
    document.AddCoverPage(CoverPageTemplate.IonDark);

    // lets add Table of Content (1 of 2)
    document.AddTableOfContent(TableOfContentStyle.Template1);

    // lets add page break
    document.AddPageBreak();

    // lets create a list that will be binded to TOC
    var wordListToc = document.AddTableOfContentList(WordListStyle.Headings111);

    wordListToc.AddItem("How to add a table to document?");

    document.AddParagraph("In the first paragraph I would like to show you how to add a table to the document using one of the 105 built-in styles:");

    // adding a table and modifying content
    var table = document.AddTable(5, 4, WordTableStyle.GridTable5DarkAccent5);
    table.Rows[3].Cells[2].Paragraphs[0].Text = "Adding text to cell";
    table.Rows[3].Cells[2].Paragraphs[0].Color = Color.Blue; ;
    table.Rows[3].Cells[3].Paragraphs[0].Text = "Different cell";

    document.AddParagraph("As you can see adding a table with some style, and adding content to it ").SetBold().SetUnderline(UnderlineValues.Dotted).AddText("is not really complicated").SetColor(Color.OrangeRed);

    wordListToc.AddItem("How to add a list to document?");

    var paragraph = document.AddParagraph("Adding lists is similar to ading a table. Just define a list and add list items to it. ").SetText("Remember that you can add anything between list items! ");
    paragraph.SetColor(Color.Blue).SetText("For example TOC List is just another list, but defining a specific style.");

    var list = document.AddList(WordListStyle.Bulleted);
    list.AddItem("First element of list", 0);
    list.AddItem("Second element of list", 1);

    var paragraphWithHyperlink = document.AddHyperLink("Go to Evotec Blogs", new Uri("https://evotec.xyz"), true, "URL with tooltip");
    // you can also change the hyperlink text, uri later on using properties
    paragraphWithHyperlink.Hyperlink.Uri = new Uri("https://evotec.xyz/hub");
    paragraphWithHyperlink.ParagraphAlignment = JustificationValues.Center;

    list.AddItem("3rd element of list, but added after hyperlink", 0);
    list.AddItem("4th element with hyperlink ").AddHyperLink("included.", new Uri("https://evotec.xyz/hub"), addStyle: true);

    document.AddParagraph();

    var listNumbered = document.AddList(WordListStyle.Heading1ai);
    listNumbered.AddItem("Different list number 1");
    listNumbered.AddItem("Different list number 2", 1);
    listNumbered.AddItem("Different list number 3", 1);
    listNumbered.AddItem("Different list number 4", 1);

    var section = document.AddSection();
    section.PageOrientation = PageOrientationValues.Landscape;
    section.PageSettings.PageSize = WordPageSize.A4;

    wordListToc.AddItem("Adding headers / footers");

    // lets add headers and footers
    document.AddHeadersAndFooters();

    // adding text to default header
    document.Header.Default.AddParagraph("Text added to header - Default");

    var section1 = document.AddSection();
    section1.PageOrientation = PageOrientationValues.Portrait;
    section1.PageSettings.PageSize = WordPageSize.A5;

    wordListToc.AddItem("Adding custom properties to document");

    document.CustomDocumentProperties.Add("TestProperty", new WordCustomProperty { Value = DateTime.Today });
    document.CustomDocumentProperties.Add("MyName", new WordCustomProperty("Some text"));
    document.CustomDocumentProperties.Add("IsTodayGreatDay", new WordCustomProperty(true));

    document.Save(openWord);
}

Tests

In addition to the fact that OfficeIMO.Word uses Unit Tests, Characterization Tests are also used. Characterization test were added in order to not overlook a change that breaks the behavior. These tests are based on Verify ("Snapshot Testing in .NET with Verify"). if you need to add or update a verified snapshot, you can use the powershell script:

$ pwsh -c ./Build/ApproveVerifyTests.ps1

officeimo's People

Contributors

bytesamurai avatar crjc avatar hisuwh avatar jordan-hemming avatar przemyslawklys avatar rstm-sf avatar startewho avatar the-faulty avatar tmheath avatar topperdel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

officeimo's Issues

Table AutoFit To Content

Initially, I thought about implementing Table AutoFitType, but it seems that AutoFit.ToContent is not something that is automatic but is something that Word does automatically, as in set it to fixes size and then using TabelGrid sizes sets the rest.

I don't know the magic numbers to count this - but maybe someone does to fix this in future.

public enum AutoFitType {
    ToContent,
    ToWindow,
    Fixed
}

public AutoFitType? AutoFit {
    get {
        if (this.Width == 0 && WidthType == TableWidthUnitValues.Auto) {
            return AutoFitType.ToContent;
        } else if (this.Width == 5000 && WidthType == TableWidthUnitValues.Pct) {
            return AutoFitType.ToWindow;
        } else if (this.LayoutType == TableLayoutValues.Fixed) {
            return AutoFitType.Fixed;
        }
        return null;
    }
    set {
        if (value == AutoFitType.ToContent) {
            this.Width = 0;
            this.WidthType = TableWidthUnitValues.Auto;
            //this.LayoutType = TableLayoutValues.Autofit;
        } else if (value == AutoFitType.ToWindow) {
            this.Width = 5000;
            this.WidthType = TableWidthUnitValues.Pct;
        } else if (value == AutoFitType.Fixed) {
            this.LayoutType = TableLayoutValues.Fixed;
        } else {
            throw new ArgumentException("Invalid value for AutoFitType. Probably should add null handling");
        }
    }
}
        public TableGrid GenerateTableGrid()
        {
            TableGrid tableGrid1 = new TableGrid();
            GridColumn gridColumn1 = new GridColumn(){ Width = "3116" };
            GridColumn gridColumn2 = new GridColumn(){ Width = "3117" };
            GridColumn gridColumn3 = new GridColumn(){ Width = "3117" };

            tableGrid1.Append(gridColumn1);
            tableGrid1.Append(gridColumn2);
            tableGrid1.Append(gridColumn3);
            return tableGrid1;
        }

Table text alignment

How to set the text alignment in table cell? left, center or right.

I tried to set text, run, paragraph, tablecell and tablerow properties, it didnt work.

thanks a lot!

Implicitly changing the target file document when saving with a different filename

Implicitly changing the loaded file document when saving with a different filename. I think changing the target document should not change the current WordDocument object. This behavior was introduced due to a document cloning issue dotnet/Open-XML-SDK#1139

We can see this

word._fileStream = new FileStream(filePath, FileMode.Open, readOnly ? FileAccess.Read : FileAccess.ReadWrite);

//Close existing fileStream
if (_fileStream != null) {
_fileStream.Dispose();
}
_fileStream = new FileStream(filePath, FileMode.Create);
//Clone and SaveAs don't actually clone document properties for some reason, so they must be copied manually
using (var clone = this._wordprocessingDocument.Clone(_fileStream)) {
CopyPackageProperties(_wordprocessingDocument.PackageProperties, clone.PackageProperties);
}
_fileStream.Flush();
FilePath = filePath;

Modify .csproj file for multi platform compatibility

At the moment, macOS users are not able to run the this project, due to a lack of target frameworks on their platforms and missing dependencies, e.g. the Test project requires a line like this:

<PackageReference Include="Microsoft.TestPlatform.ObjectModel" Version="17.4.0" Condition="$([MSBuild]::IsOsPlatform('OSX'))" />

Definition of Done:

  • Project configuration has been tested on Windows in Visual Studio and VS code (Omnisharp)
  • Project configuration has been tested on Mac in Visual Studio and VS code (Omnisharp)
  • Project configuration has been tested on Linux in VS code (Omnisharp)

When I am upgrading from 0.4.0 to 0.4.1 Lists do not show up anymore

Hello.
I'm sorry but I do not really know how to publish a issue in github, so please ask if any more information is needed.

What I do:
Run the code example for an advance document from the readme, also tried the exmaple where
Tried with .net 4.7.2, .net 5, .net 6 and .net 7. They all return the same issue.

Also tried the list code that was updated 18 days ago, where it describe some of the same issue, lists not appearing.
#62 Fix not saving list when save to Stream
OfficeIMO/OfficeIMO.Examples/Word/Lists/Lists.Create2.cs

Issue:
On version 0.4.0 tittles, lists and TOC appears like normal. When I run the code example after upgrading to 0.4, text from the list appears, but not the bulletpoint itself. The titles lacks formating. See picture bellow.

Picture:
image

Extending field type list

Hey,
At the moment, I have struggles to add custom field codes because the enum does not contain the whole list of field codes, but only a subset:
https://github.com/EvotecIT/OfficeIMO/blob/master/OfficeIMO.Word/WordField.cs#L10

E.g., could we add BIBLIOGRAPHY to it?
See: https://support.microsoft.com/en-us/office/field-codes-bibliography-field-cbb17838-05d7-4533-8066-4791aeddb9de

Some field codes require switches, so how about passing a dictionary to AddField(...) as an optional argument?

Do you think that is doable? Do you prefer a PR or to do it yourself?

Sections tracking - Manual vs Automatic

I try to build everything as it is within the document, loading it when it's requested with the exception of sections.

I've tried to fix sections: using the code below, but sections are complicated beasts. They move around when adding new sections so I often lost track of sections that just moved because of the new section. Either I don't understand it well enough to build it automatically or the approach I require for Sections to work - is just the way it is.

public List<WordSection> Sections = new List<WordSection>();

private List<WordSection> GetSections() {
    List<WordSection> listSections1 = new List<WordSection>();
    if (_wordprocessingDocument.MainDocumentPart.Document != null) {
        if (_wordprocessingDocument.MainDocumentPart.Document.Body != null) {
            var listElements = _wordprocessingDocument.MainDocumentPart.Document.Body.ChildElements;
            foreach (var element in listElements) {
                if (element is Paragraph) {
                    Paragraph paragraph = (Paragraph)element;
                    if (paragraph.ParagraphProperties != null && paragraph.ParagraphProperties.SectionProperties != null) {
                        listSections1.Add(new WordSection(this, paragraph.ParagraphProperties.SectionProperties, paragraph));
                    }
                }
            }
            var sectionProp = _wordprocessingDocument.MainDocumentPart.Document.Body.ChildElements.OfType<SectionProperties>().FirstOrDefault();
            var section = new WordSection(this, sectionProp, null);
            listSections1.Add(section);
        }
    }
    return listSections1;
}

public List<WordSection> SectionsGenerated {
    get {
        return GetSections();
    }
}

Leaving it for the future to either close or fix.

Add a Table Cell Fill

using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;

namespace GeneratedCode
{
    public class GeneratedClass
    {
        // Creates an TableCell instance and adds its children.
        public TableCell GenerateTableCell()
        {
            TableCell tableCell1 = new TableCell();

            TableCellProperties tableCellProperties1 = new TableCellProperties();
            TableCellWidth tableCellWidth1 = new TableCellWidth(){ Width = "3116", Type = TableWidthUnitValues.Dxa };
            Shading shading1 = new Shading(){ Val = ShadingPatternValues.Clear, Color = "auto", Fill = "4472C4", ThemeFill = ThemeColorValues.Accent1 };

            tableCellProperties1.Append(tableCellWidth1);
            tableCellProperties1.Append(shading1);
            Paragraph paragraph1 = new Paragraph(){ RsidParagraphAddition = "001F2E94", RsidRunAdditionDefault = "001F2E94", ParagraphId = "037BA2FD", TextId = "77777777" };

            tableCell1.Append(tableCellProperties1);
            tableCell1.Append(paragraph1);
            return tableCell1;
        }


    }
}

Option to save to Stream rather than file path

I am developing a web application and want to be able to generate a word document to then be downloaded by the user.

This library does not give me the option to save to a Stream only a file path

Unable to format external hyperlinks

I'm trying to format external hyperlinks with custom font color and size, no underline, but cannot get anything other than the default font from the document.

I have tried setting the font attributes inline:
document.AddHyperLink("Go to Evotec Blogs", new Uri("https://evotec.xyz")).SetColorHex("1C8FD6").SetFontSize(14).SetBold();

I have tried setting the font attributes after the fact:
var paragraphWithHyperLink = document.AddHyperLink("Go to Evotec Blogs", new Uri("https://evotec.xyz"));
paragraphWithHyperLink.SetColorHex("1C8FD6").SetFontSize(14).SetBold();

I have tried creating the hyperlink off a new paragraph:
WordParagraph paragraph = document.AddParagraph();
paragraph.AddHyperLink("Go to Evotec Blogs", new Uri("https://evotec.xyz")).SetColorHex("1C8FD6").SetFontSize(14).SetBold();

None of these attempts have worked. Am I missing something? Thank you!

Validation errors Description="Attribute 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:styleId' should have unique value. Its current value 'ListTable6Colorful-Accent5' duplicates with others."

image

Basically all tables styles are reporting this error. This seems standard even for documents generated by Office 365. When you create a word document and add 1-3-50 tables to it, and add multiple styles validation errors will occur. It doesn't seem to affect anything and doesn't show up for FileFormat 2007. Only for newer formats.

Loaded Word document got changed unexpectedly

Hi,
I want to use an existing docx file as a template to generate a circular letter and save each file separately.

So the template documents is being loaded with the "readonly" parameter set to true and the "autosave" parameter to false:

      using (WordDocument document = WordDocument.Load(template, true, false))
      {...
      
              document.Save(filepath);
      }

When the changes to the document (filled up placeholders) is done, the save function is called with a given new filepath.

Why is the source document (template) always being updated? This breaks my template.
Is the "readonly" option not working properly?

A separate SaveAS function would be helpful to fully prevent changes to the source file.

Thank you for any hint.

ContentControl

How can I insert ContentControl or input text into an existing contentcontrol?

Thanks a lot!

Set special characters to the document's default font.

Hello, I wanted to know if there's a way to set the default font for special characters for example, I put the default font in the "Segoe UI" document, but when it has a special character it stays with the "Calibri" font, how can I adjust it? Note, the font supports special characters. (follow the prints)

image






image

Set special characters to the document's default font.

Hello, I wanted to know if there's a way to set the default font for special characters for example, I put the default font in the "Segoe UI" document, but when it has a special character it stays with the "Calibri" font, how can I adjust it? Note, the font supports special characters. (follow the prints)

image




image

using (WordDocument document = WordDocument.Create(filePath))
                {
                    document.Settings.Language = "pt-Br";

                    string title = "INSTRUMENTO PARTICULAR DE CONSTITUIÇÃO DE GARANTIA DE\r\nALIENAÇÃO FIDUCIÁRIA DE IMÓVEL\r\n";

 document.AddParagraph(title).SetBold().ParagraphAlignment = JustificationValues.Center;
document.Save();

that's just the title, I need to adjust it in every document.

Better support for images

  • Support for JPG
  • Support for BMP, GIF, PNG, TIFF
  • Support for images in headers/footers - #53
  • Support for images in tables - #53
  • Wrap Text
  • Alt Text
  • Size and position
  • Format Picture

I am not sure if those are even possible or word does this natively, but I'll add it here

  • Corrections
  • Transparency Effects
  • Artistic Effects

Docs: http://officeopenxml.com/drwPic-ImageData.php

Handling of new line characters

Right now if the text contains NewLine character, the rendering as Text or Paragraph ignores the newline and renders its as plain text.

If we manually add Paragraph there is additional BREAK (ENTER) rendered which is not rendered if we press SHIFT+ENTER in Word.

Example

                    var json = JValue.Parse(oldJson).ToString(Formatting.Indented);
                    string[ ] newLineArray = { Environment.NewLine };
                    string[ ] textArray = json.Split( newLineArray, StringSplitOptions.None );
                    for (int index = 0; index < textArray.Length; index++)
                    {                             
                        document.AddParagraph(textArray[index]);          
                    }

This will render the Word Document as below,

image

What is expected is

image

Please suggest what is the best way to replace an ENTER with a SHIFT+ENTER

Add Headers and Footers

  • Headers and Footers
    • Basic support for Headers and Footers during New
      • First
      • Odd
      • Even
    • Basic support for Headers and Footers during Load
      • First
      • Odd
      • Even
    • Support for headers/footers with sections

Opinion: Focus on word and ignore Excel

I notice in your code there is the start of an implementation for Excel. If you are not already aware there is excellent library for Excel already: https://spreadsheetlight.com/

However, I have not seen another open-source Word library. I think efforts would be best focussed on that. This looks really good already, but would great to have this fully fleshed out alongside SpreadsheetLight as complete solution for Word and Excel.

Just my opinion of course, feel free to do what you think is best.

Table styles are not being applied

Styles are not visible.

 document.Tables[0].Style = WordTableStyle.GridTable1LightAccent3;
 document.AddTable(4, 4, WordTableStyle.GridTable1LightAccent3);

Both ways are not working or don't seem to have any effect in my document. Possibly a bug?

Object reference not set to an instance of an object when adding bookmark

Example showing issue: HeadersAndFooters.Sections1(folderPath, false);

image

System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=OfficeIMO.Word
StackTrace:
at OfficeIMO.Word.WordBookmark.AddBookmark(WordParagraph paragraph, String bookmarkName) in C:\Support\GitHub\OfficeIMO\OfficeIMO.Word\WordBookmark.cs:line 54

using (WordDocument document = WordDocument.Create(filePath)) {
document.AddParagraph("Basic paragraph");
document.AddTable(1, 1);
var para = document.AddBookmark("Test");
document.AddHeadersAndFooters();
document.Sections[0].Header.Default.AddParagraph().AddText("Section 0").AddBookmark("BookmarkInSection0Header1");
var tableHeader = document.Sections[0].Header.Default.AddTable(3, 4);
tableHeader.Rows[0].Cells[3].Paragraphs[0].Text = "This is sparta";
Console.WriteLine(document.Sections[0].Header.Default.Tables.Count);

Using Save with Filepath during Load doesn't work correctly

Currently, when you load document and try to save it as another document it seems to save as both filePath31 and filePath4`.

            using (WordDocument document = WordDocument.Load(filePath3)) {
                Assert.True(filePath3.IsFileLocked() == true);

                Assert.True(document.Paragraphs.Count == 3);
                document.AddParagraph("More paragraphs!");
                Assert.True(document.Paragraphs.Count == 4);
                document.Save(filePath4);
            }

This needs to be fixed, but I am not sure how, as my tries failed.

Field Codes as a domain model

At the moment, field codes take parameters only as a list of strings. Though this approach is quite flexible, it would be nice to provide a typed-based abstraction of the different field codes.

The complete list is available here: https://support.microsoft.com/en-us/office/list-of-field-codes-in-word-1ad6d91a-55a7-4a8d-b535-cf7888659a51

The current WordFieldType enum needs to be refactored so that each value of the Enum becomes a class, which encapsulates possible instructions and switches of a field code. As an example, an ASK field code class might look like this:

image

Improve duplicated code

Stream does not support writing.

@rstm-sf it seems your change for Save has broken some examples

System.NotSupportedException
  HResult=0x80131515
  Message=Stream does not support writing.
  Source=System.Private.CoreLib
  StackTrace:
   at System.ThrowHelper.ThrowNotSupportedException_UnwritableStream()
   at System.IO.FileStream.SetLength(Int64 value)
   at OfficeIMO.Word.WordDocument.Save(String filePath, Boolean openWord) in C:\Support\GitHub\OfficeIMO\OfficeIMO.Word\WordDocument.cs:line 602
   at OfficeIMO.Word.WordDocument.Save(Boolean openWord) in C:\Support\GitHub\OfficeIMO\OfficeIMO.Word\WordDocument.cs:line 633
   at OfficeIMO.Examples.Word.LoadDocuments.LoadWordDocument_Sample1(Boolean openWord) in C:\Support\GitHub\OfficeIMO\OfficeIMO.Examples\Word\LoadDocuments\LoadDocuments.Sample1.cs:line 30
   at OfficeIMO.Examples.Program.Main(String[] args) in C:\Support\GitHub\OfficeIMO\OfficeIMO.Examples\Program.cs:line 76

image

All examples that load documents seem to be affected:

LoadDocuments.LoadWordDocument_Sample1(false);
LoadDocuments.LoadWordDocument_Sample2(false);
LoadDocuments.LoadWordDocument_Sample3(false);

Add method to create a document in Stream

At the moment, it is not possible to set the Stream into which the document will be saved. This is convenient when we do not want to save the file locally, but only generate it in memory.

Adding Watermark to section that has not initialized headers will throw an error

Error thrown:

image

System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=OfficeIMO.Word
StackTrace:
at OfficeIMO.Word.WordWatermark..ctor(WordDocument wordDocument, WordSection wordSection, WordHeader wordHeader, WordWatermarkStyle style, String text) in C:\Support\GitHub\OfficeIMO\OfficeIMO.Word\WordWatermark.cs:line 98

List style is not saved when saving to stream

internal static void Example_BasicLists_Save_To_Stream(string folderPath, bool openWord) {
    using var document = WordDocument.Create();
    foreach (var listStyle in (WordListStyle[])Enum.GetValues(typeof(WordListStyle))) {
        var paragraph = document.AddParagraph(listStyle.ToString());
        paragraph.SetColor(Color.Red).SetBold();
        paragraph.ParagraphAlignment = JustificationValues.Center;

        var wordList1 = document.AddList(listStyle);
        wordList1.AddItem("Text 1", 0);
        wordList1.AddItem("Text 2", 1);
        wordList1.AddItem("Text 3", 2);
        wordList1.AddItem("Text 4", 3);
        wordList1.AddItem("Text 5", 4);
        wordList1.AddItem("Text 6", 5);
        wordList1.AddItem("Text 7", 6);
        wordList1.AddItem("Text 8", 7);
        wordList1.AddItem("Text 9", 8);
    }

    using var outputStream = new MemoryStream();
    document.Save(outputStream);

    var filePath = Path.Combine(folderPath, "Document with Lists when save to stream.docx");
    File.WriteAllBytes(filePath, outputStream.ToArray());
    if (openWord) {
        Helpers.Open(filePath, openWord);
    }
}

image

compatibility mode

I noticed that the generated document it opens in "compatibility mode", in which office version is it generated? is there a way I can set the version? and which version it is saved?

Missing license info

Hi

Would you mind providing license information for this project/repository?

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.