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)
{
string pdfName = fileName.Substring(0, fileName.Length - 4) + ".pdf";
Application app = new Application();
Document doc = app.Documents.Open(docName);
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);
doc.ExportAsFixedFormat(pdfName, WdExportFormat.wdExportFormatPDF);
doc.Close(false);
app.Quit();
app = null;
byte[] bytes = File.ReadAllBytes(pdfName);
File.Delete(pdfName);
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.
source
share