我正在测试以编程方式从 Winforms 应用程序将 Word 文档转换为 PDF。我编写了以下代码,它在我的机器上运行良好。该应用程序由一个带有 2 个按钮和一个文本框的表单组成。单击第一个按钮打开一个对话框,允许用户导航到文件夹。文件夹地址存储在文本框中。然后第二个按钮从指定的文件夹中取出每个 Word 文档,并为每个文档创建一个同名的 PDF。
namespace PDFTesting
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnFind_Click(object sender, EventArgs e)
{
try
{
FolderBrowserDialog folder = new FolderBrowserDialog();
DialogResult result = folder.ShowDialog();
if (result == DialogResult.OK)
{
string[] files = Directory.GetFiles(folder.SelectedPath);
txtLocation.Text = folder.SelectedPath.ToString();
}
else
{
txtLocation.Text = null;
}
}
catch (Exception eX)
{
throw new Exception("cDocument: Error atempting to GetPath()" + Environment.NewLine + eX.Message);
}
}
private void btnConvert_Click(object sender, EventArgs e)
{
// 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;
// Get list of Word files in specified directory
string docPath = txtLocation.Text;
DirectoryInfo dirInfo = new DirectoryInfo(docPath);
FileInfo[] wordFiles = dirInfo.GetFiles("*.doc");
word.Visible = false;
word.ScreenUpdating = false;
foreach (FileInfo wordFile in wordFiles)
{
// Cast as Object for word Open method
Object filename = (Object)wordFile.FullName;
// Use the dummy value as a placeholder for optional arguments
Document doc = word.Documents.Open(ref filename, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, 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.FullName.Replace(".docx", ".pdf");
object fileFormat = WdSaveFormat.wdFormatPDF;
// Save document into PDF Format
doc.SaveAs(ref outputFileName,
ref fileFormat, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing);
// 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)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
doc = null;
}
// word has to be cast to type _Application so that it will find
// the correct Quit method.
((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
word = null;
}
}
}
这在我的开发 PC 上完全按照预期工作,但是当我构建解决方案并分发到另一台机器(运行相同版本的 Windows 7、64 位)并安装 Word 时,我收到以下错误 -
有谁知道为什么我的迷你 PDF 应用程序不能在替代机器上运行?