Generating a DOC or DOCX using MigraDoc

3.8k views Asked by At

I am working on a project where I need to create a Word file. For this purpose, I am using MigraDoc library for C#.

Using this library, I am easily able to generate a RTF file by writing :

Document document = CreateDocument();
RtfDocumentRenderer rtf = new RtfDocumentRenderer();
rtf.Render(document, "test.rtf", null);
Process.Start("test.rtf");

But the requirement now asks me to get a DOC or DOCX file rather than a RTF file. Is there a way to generate a DOC or DOCX file using MigraDoc? And if so, how may I achieve this?

3

There are 3 answers

0
I liked the old Stack Overflow On BEST ANSWER

MigraDoc cannot generate DOC or DOCX files. Since MigraDoc is open source, you could add a renderer for DOCX if you have the knowledge and the time.

MigraDoc as it is cannot generate DOC/DOCX, but maybe you can invoke an external conversion tool after generating the RTF file.
I don't know any such tools. Word can open RTF quickly and so far our customers never complained about getting RTF, not DOC or DOCX.

Update (2019-07-29): The website mentions "Word", but this only refers to RTF. There never was an implementation for .DOC or .DOCX.

0
Alexander I. On

It seems no any MigraDoc renders that support DOC or DOCX formats.

On documentation page we can see one MigraDoc feature:

Supports different output formats (PDF, Word, HTML, any printer supported by Windows)

But seems documentation says about RTF format that perfectly works with Word. I have reviewed MigraDoc repository and I do not see any DOC renders. We can use only RTF converter for Word supporting. So we can't generate DOC file directly using this package.

But we can convert RTF to DOC or DOCX easily (and for free) using FreeSpire.Doc nuget package.

Full code example is here:

using MigraDoc.DocumentObjectModel;
using MigraDoc.RtfRendering;
using Spire.Doc;
using System.IO;

namespace MigraDocTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var stream = new MemoryStream())
            {
                // Generate RTF (using MigraDoc)
                var migraDoc = new MigraDoc.DocumentObjectModel.Document();
                var section = migraDoc.AddSection();
                var paragraph = section.AddParagraph();
                paragraph.AddFormattedText("Hello World!", TextFormat.Bold);
                var rtfDocumentRenderer = new RtfDocumentRenderer();
                rtfDocumentRenderer.Render(migraDoc, stream, false, null);

                // Convert RTF to DOCX (using Spire.Doc)
                var spireDoc = new Spire.Doc.Document();
                spireDoc.LoadFromStream(stream, FileFormat.Auto);
                spireDoc.SaveToFile("D:\\example.docx", FileFormat.Docx );
            }
        }
    }
}
1
Oli Bowe On

You can use Microsoft's DocumentFormat.OpenXML library which has a NuGet package.