How to convert Word document created from template by OpenXML into MemoryStream?

How to convert Word document created from template by OpenXML into MemoryStream?

By : Gurre
Date : January 11 2021, 03:32 PM
To fix the issue you can do Found answer which works without saving to intermediate temp file. Trick is to open template for editing, use accessible stream, change document type from template to document, and return this stream.
code :
public static MemoryStream GetWordDocumentStreamFromTemplate()
    var templatePath = AppDomain.CurrentDomain.BaseDirectory + "Controllers\\" + templateFileName;
    var memoryStream = new MemoryStream();

    using (var fileStream = new FileStream(templatePath, FileMode.Open, FileAccess.Read))

    using (var document = WordprocessingDocument.Open(memoryStream, true))
        document.ChangeDocumentType(WordprocessingDocumentType.Document); // change from template to document

        var body = document.MainDocumentPart.Document.Body;

        //add some text 
        Paragraph paraHeader = body.AppendChild(new Paragraph());
        Run run = paraHeader.AppendChild(new Run());
        run.AppendChild(new Text("This is body text"));


    memoryStream.Position = 0; //let's rewind it
    return memoryStream;

Share : facebook icon twitter icon
Saving an OpenXML Document (Word) generated from a template

Saving an OpenXML Document (Word) generated from a template

By : Azhari Subroto
Date : March 29 2020, 07:55 AM
To fix this issue Are you referring to the OpenXml SDK? Unfortunately, as of OpenXml SDK 2.0, there's no SaveAs method. You'll need to:
Make a temporary copy of your template file, naming it whatever you want. Perform your OpenXml changes on the above file. Save the appropriate sections (ie. using the .myWordDocument.MainDocumentPart.Document.Save() method for the main content or someHeaderPart.Header.Save() method for a particular header).
Copy data from existing WORD document to new WORD document created from template (in code)

Copy data from existing WORD document to new WORD document created from template (in code)

By : coch9894
Date : March 29 2020, 07:55 AM
help you fix your problem Every Word document has a ThisDocument object. If you write VBA code which uses ThisDocument, that object always points to the ThisDocument object in the same file as your code. ActiveDocument, on the other hand, always points to the document that is active in Word, that is, the one that is visible in the Word window at the moment. If possible, try to avoid using ActiveDocument since it can point to a different document than what you think.
In order to access a Document object other than the one your code is in, you cannot use ThisDocument, so instead you create a reference to the other document:
code :
Option Explicit

Sub FindOtherDocument()
    Dim oOtherDocument As Document
    Set oOtherDocument = Application.Documents("Filled.docx")

    Call MsgBox("This is the name of the file which oOtherDocument points to: " & oOtherDocument.FullName)
End Sub
OpenXml Convert from Word document to HTML with Header

OpenXml Convert from Word document to HTML with Header

By : ahidal01
Date : March 29 2020, 07:55 AM
Does that help OpenXmlPowerTools ignores headers and footers when converting a docx-document to HTML, so they won't show up in the resulting HTML (you can browse the source code on github).
Perhaps it's because the concept of a 'page' doesn't apply to HTML, so there's no obvious equivalent to a document header.
create a new document from word template with multiple pages using documentformat.openxml

create a new document from word template with multiple pages using documentformat.openxml

By : user3413977
Date : March 29 2020, 07:55 AM
hope this fix your issue The sample code below (which is unit-tested and works) does what you are trying to achieve. It is based on the following interpretation of the question and assumptions:
"Control place holders" means "Rich Text content controls", which are called block-level structured document tags (SDTs) in Open XML lingo and are thus represented by the SdtBlock class in the Open XML SDK. The content controls have tags, meaning the relevant w:sdt elements have grandchild elements like . Those tags are used to link the data received from the REST service to the content controls. The data is provided as a Dictionary, mapping tag values to the content control text (data).
code :
public class ContentControlWriter
    private readonly IDictionary<string, string> _contentMap;

    /// <summary>
    /// Initializes a new ContentControlWriter instance.
    /// </summary>
    /// <param name="contentMap">The mapping of content control tags to content control texts.
    /// </param>
    public ContentControlWriter(IDictionary<string, string> contentMap)
        _contentMap = contentMap;

    /// <summary>
    /// Transforms the given WordprocessingDocument by setting the content
    /// of relevant block-level content controls.
    /// </summary>
    /// <param name="wordDocument">The WordprocessingDocument to be transformed.</param>
    public void WriteContentControls(WordprocessingDocument wordDocument)
        MainDocumentPart part = wordDocument.MainDocumentPart;
        part.Document = (Document) TransformDocument(part.Document);

    private object TransformDocument(OpenXmlElement element)
        if (element is SdtBlock sdt)
            string tagValue = GetTagValue(sdt);
            if (_contentMap.TryGetValue(tagValue, out string text))
                return TransformSdtBlock(sdt, text);

        return Transform(element, TransformDocument);

    private static object TransformSdtBlock(OpenXmlElement element, string text)
        return element is SdtContentBlock
            ? new SdtContentBlock(new Paragraph(new Run(new Text(text))))
            : Transform(element, e => TransformSdtBlock(e, text));

    private static string GetTagValue(SdtElement sdt) => sdt
        .Select(tag => tag.Val.Value)

    private static T Transform<T>(T element, Func<OpenXmlElement, object> transformation)
        where T : OpenXmlElement
        var transformedElement = (T) element.CloneNode(false);
        transformedElement.Append(element.Elements().Select(e => (OpenXmlElement) transformation(e)));
        return transformedElement;
Image Size Not Applied when opening OpenXML Word Document Created in C#

Image Size Not Applied when opening OpenXML Word Document Created in C#

By : Aissam Musnaoui
Date : March 29 2020, 07:55 AM
should help you out this is a pretty old question but I think it's worth answering anyway since this seems to come up a lot.
I also used the above sample and it works well, except that cx and cy are hard-coded and distort the image.
Related Posts Related Posts :
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • c# wpf | create complex object with user-defined name to Serialize into JSON
  • How can I get a instance of a generic list with reflection?
  • WPF XAML - Design time and visibility of textbox
  • EF Core and MySql query is too slow
  • Getting Registered App Display Name from an App Id
  • How to get all variables from a string
  • Delete entity with all childs connected
  • Azure Build agent cant´t find class library referance
  • Initialize Nested Dictionaries in c#
  • .Net Core Binding
  • Loading a pop up page in ASP.net through a js file
  • How to pass alert or notification message from controller to View?
  • C# to pause, turn on ssas server, backup cube.... how to?
  • How to execute DataTable.Select() for a column of custom class type for a particular element in that C#
  • how to connect mysql8.0 with C#
  • Passing incorrect values into MultiValueConverter by MultiBinding
  • Can i use IEnumerator as Update func?
  • How to convert API Json response to C# Array?
  • Blazor Textfield Oninput User Typing Delay
  • Performing both layout and render transform results in wrong output
  • uwp beforetextchanged cursor moving in front of text
  • How to keep duplicates from a string[] exclude words from a List and print them out
  • .Net Core Strings.Asc/Mid/Chr/Len missing even after importing Microsoft.VisualBasic
  • How to return to previous search page without being asked to Confirm Form Re-submission and keeping the results on ASP.N
  • How set a identity scaffolding item/page how initial page in asp.net MVC core?
  • LINQ isn't calling Dispose on my IEnumerator when using Union and Select, expected behavior or bug?
  • What is "ByteArray.uncompress()" in AS3 equivalent to in C#?
  • Getting a specific letter from a string variable for my simple guessing game for clues
  • Send an email with Outlook without a subject --- dialog box issue
  • passing List<MyModel> from my controller in the "WebInterfaceProject" to the processor method in "D
  • How can I make a single slider that changes the color of an object?
  • Remap JSON parameter in c#
  • What is the difference between "this ref" and "ref this" when talking about C# 7.2 ref extension met
  • Convert OpenSSL encryption into native C#
  • Accessing Properties in Razor Pages
  • How to get SOAP element value
  • Projection after Group
  • C# error cannot convert sytem.text.regularexpressions.match to string
  • Issues with Save/Load System in a Text Based Adventure game made with ScriptableObjects in Unity
  • VS2019 MSBuild.exe - ASP .Net MVC project fails to publish when using PublishProfile, but works when using OutDir parame
  • Does <pages validateRequest="false" /> in Web.config still matter?
  • How to send new request to redirect URL with new access token
  • Attempt to invoke virtual method on a null object reference Xamarin LockScreen
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org