Convert Word document to in-memory PDF byte array

I need to open a Microsoft Word document, replace a piece of text, and then convert to a PDF byte array. I created the code for this, but it involves saving pdf to disk and reading bytes back to memory. I would like not to write anything to disk, since I do not need to save the file.

Below is the code I've done so far ...

using System.IO;
using Microsoft.Office.Interop.Word;

public byte[] ConvertWordToPdfArray(string fileName, string newText)
{
    // Temporary path to save pdf
    string pdfName = fileName.Substring(0, fileName.Length - 4) + ".pdf";

    // Create a new Microsoft Word application object and open the document
    Application app = new Application();
    Document doc = app.Documents.Open(docName);

    // Make any necessary changes to the document
    Selection selection = doc.ActiveWindow.Selection;
    selection.Find.Text = "{{newText}}";
    selection.Find.Forward = true;
    selection.Find.MatchWholeWord = false;
    selection.Find.Replacement.Text = newText;
    selection.Find.Execute(Replace: WdReplace.wdReplaceAll);

    // Save the pdf to disk
    doc.ExportAsFixedFormat(pdfName, WdExportFormat.wdExportFormatPDF);

    // Close the document and exit Word
    doc.Close(false);
    app.Quit();
    app = null;

    // Read the pdf into an array of bytes
    byte[] bytes = File.ReadAllBytes(pdfName);

    // Delete the pdf from the disk
    File.Delete(pdfName);

    // Return the array of bytes
    return bytes;
}

How can I achieve the same result without writing to disk? The entire operation must be performed in memory.

To explain why I need this, I want ASP.NET MVC users to be able to download the report template as a text document, which when returned to the browser displays as pdf.

+4
source share
1

:

  • Word , . , SDK SDK , , . ( , UI, )

  • Office ASP.NET. Office, :

    Microsoft Microsoft Office , ( ASP, ASP.NET, DCOM NT), Office / , Office .

, .

+4

Source: https://habr.com/ru/post/1625295/


All Articles