I need to open a Microsoft Word document, replace some of the text then convert to a pdf byte array. I have created code to do this but it involves saving the pdf to disk and reading the bytes back into memory. I would like to avoid writing anything to the disk as I do not need to save the file.
Below is the code I have 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 the disk? The whole operation needs to run in memory.
To explain why I need to do this, I want users of an ASP.NET MVC application to be able to upload a report template as a word document which when returned to the browser is rendered as a pdf.