我需要提供将 RTF/WORD 文件转换为 PDF 并将其作为电子邮件附件发送的功能,为此我尝试了如下所示的代码:
// Create a new Microsoft Word application object
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
// C# doesn't have optional arguments so we'll need a dummy value
object oMissing = System.Reflection.Missing.Value;
Document doc;
protected void Page_Load(object sender, EventArgs e)
{
ConvertToPDF("test.doc");
}
void ConvertToPDF(string sFileName)
{
// Create a new Microsoft Word application object
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
// C# doesn't have optional arguments so we'll need a dummy value
object oMissing = System.Reflection.Missing.Value;
Document doc;
try
{
word.Visible = false;
word.ScreenUpdating = false;
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(".") + "\\TempDoc");
FileInfo[] wordFile = dirInfo.GetFiles(sFileName);
if (wordFile.Length > 0)
{
Object filename = (Object)wordFile[0].FullName;
// Use the dummy value as a placeholder for optional arguments
doc = word.Documents.Open2000(ref filename, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
doc.Activate();
object outputFileName = wordFile[0].FullName.Replace(".doc", "");
object fileFormat = WdSaveFormat.wdFormatPDF;
// Save document into PDF Formats
doc.SaveAs2000(ref outputFileName, ref fileFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
}
}
catch (Exception ex)
{
Response.Write(ex);
}
finally
{
// Close the Word document, but leave the Word application open.
// doc has to be cast to type _Document so that it will find the
// correct Close method.
doc = null;
// word has to be cast to type _Application so that it will find
// the correct Quit method.
word = null;
}
}
但它在 doc.SaveAs2000(ref outputFileName, ref fileFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing) 上给出错误;陈述。
这可能是我们拥有 Microsoft Office 2007 的原因,在此,没有任何选项可以保存为 PDF 文件。在 Microsoft Office 2010 中,它具有该选项,因此当 Microsoft Office 2010 安装在服务器上时,此代码可能会起作用。