1

i'm using Novacode Docx for creating word document with c# but I have a problem with Merging two documents into one.As per my requirement i need to download two word documents without zipping them at once,However i didn't find a solution for that so, i have planned to merge the word documents and download them as a single file.Can some one help me how to merge word documents using Novacode Docx.

Thank you in advance.

1 Answers1

1

I do it like this :

private DocX fullReportDocument;
private DocX titleDocument;
private DocX firstDocument;
private DocX secondDocument;

public byte[] GetReport(bool WantFirstReport, bool WantSecondReport)
{

    fullDocument = DocX.Create(new MemoryStream());
    // Create title for the report
    this.GenerateTitleDocument();
    // Insert the old document into the new document.
    fullDocument.InsertDocument(titleDocument);

    // Save the new document.
    fullDocument.Save();

    if (WantFirstReport)
    {
        // Create expertise report
        this.GenrateFirstDocument();

        // Insert a page break at the beginning to separate title and expertise report properly
        firstDocument.Paragraphs[0].InsertPageBreakBeforeSelf();
        firstDocument.Save();

        // Insert the old document into the new document.
        fullDocument.InsertDocument(firstDocument);

        // Save the new document.
        fullDocument.Save();
    }

    if (WantSecondReport)
    {
        // Create expertise report
        this.GenrateSecondDocument();

        // Insert a page break at the beginning to separate title and expertise report properly
        secondDocument.Paragraphs[0].InsertPageBreakBeforeSelf();
        secondDocument.Save();

        // Insert the old document into the new document.
        fullDocument.InsertDocument(secondDocument);

        // Save the new document.
        fullDocument.Save();
    }
    return fullReportDocument.DocumentMemoryStream.ToArray();
}

But i modified the DocX librairy to add DocumentMemoryStream property that exposes the memoryStream internal MemoryStream

If you dont want to modify the DocX library you can also do this :

fullDocument.SaveAs(GENERATED_DOCX_LOCATION);
return System.IO.File.ReadAllBytes(GENERATED_DOCX_LOCATION);

GENERATED_DOCX_LOCATION is obviously a string with the physcal path of the file you want to save.

G.Dealmeida
  • 325
  • 3
  • 14