Code Monkey home page Code Monkey logo

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  avatar

officeimo's Issues

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

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

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

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.

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!

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

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.

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.

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?

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!

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);

Missing license info

Hi

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

Thanks!

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 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;
        }


    }
}

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

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.

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

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;

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.

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?

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

Improve duplicated code

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.

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);

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

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;
        }

ContentControl

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

Thanks a lot!

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?

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)

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.

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.