我有与微软Office非常奇怪的问题。
我有一个公共库,其唯一目的就是打开任何Word文档的文件类型传递给它(一个完整的文件路径...)并保存打开的Word文档另存为PDF文件。
怪异的问题是,如果我使用来自一个窗口服务,当它试图打开word文档库,我得到一个空...又名,在Word文档从来没有得到开放。
然而,如果我从一个WPF或Windows窗体应用程序消耗的图书馆中,我从来没有任何问题。 据我所知,有与线程(单线程公寓)的问题,但是我不知道如何解决它的工作窗外的服务。 :( :( :(
我将不胜感激任何帮助! 我得到的错误是以下几点:
异常消息:{“对象引用不设置为一个对象的一个实例。”}(参照word文档)。 内部异常:空; HRESULT:-2147467261。 数据:ListDictionaryInternal 0条目; 堆栈跟踪:在DocumentConverter.ToPdf(字符串currentWorkingFolderPath,字符串pathToDocumentToConvert)在C:\项目文件... \ DocumentConverter.cs:209线
因此,这里是库函数。 它需要的Microsoft Office参考,这是由Visual Studio工具Office创建。
private string ToPDF(string currentWorkingFolderPath, string pathToDocumentToConvert)
{
string temporaryPdfFolderPath = Path.GetFullPath(currentWorkingFolderPath + "\\pdf\\");
string temporaryPdfFilePath = Path.GetFullPath(temporaryPdfFolderPath + "\\pdffile.pdf");
if (!FileSystem.CreateDirectory(temporaryPdfFolderPath))
{
return null;
}
try
{
Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
object objectMissing = System.Reflection.Missing.Value;
wordApplication.Visible = false;
wordApplication.ScreenUpdating = false;
FileInfo wordFile = new FileInfo(pathToDocumentToConvert);
Object fileName = (Object)wordFile.FullName;
// This is where it breaks when called from windows service. Use the dummy value as a placeholder for optional arguments
Document wordDocument = wordApplication.Documents.Open(ref fileName, ref objectMissing,
true, ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing,
ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing,
ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing);
object outputFileName = (object)temporaryPdfFilePath;
object fileFormat = WdSaveFormat.wdFormatPDF ;
// Save document into PDF Format
wordDocument.SaveAs(ref outputFileName,
ref fileFormat, ref objectMissing, ref objectMissing,
ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing,
ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing,
ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing);
// 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.
object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
((_Document)wordDocument).Close(ref saveChanges, ref objectMissing, ref objectMissing);
wordDocument = null;
// word has to be cast to type _Application so that it will find
// the correct Quit method.
((Microsoft.Office.Interop.Word._Application)wordApplication).Quit(ref objectMissing, ref objectMissing, ref objectMissing);
wordApplication = null;
}
catch (Exception ex)
{
//logging code
return null;
}
return temporaryPdfFilePath;
}