我在这个网站上发现了这段不错的、可以工作的代码,但我想做一些修改。
我想要求用户上传一个文档,但如果他们的文档不是 PDF 格式,我想将其转换为 PDF 文件,例如转换所有 doc、docx 和 excel 文件。
我让它与 .doc 文件一起工作,如果我想添加更多,我会将它们添加到“*.doc,*.docx,...”吗?
此外,如果文件位于同一目录中,则当前程序正在转换文件。我希望它接受来自用户的新目录并将其保存到不同的目录,并且不一定都在同一个位置 - 例如,程序将从 ...\Documents 保存到 ...\Uploads。我怎么能这样做?
这是Word到PDF的代码:
private void Word2PDF() {
//Create a new Microsoft Word application object
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
//Adding dummy value because c# doesn't have optional arguments
object oMissing = System.Reflection.Missing.Value;
//Getting list of word files in specified directory
DirectoryInfo dirInfo = new DirectoryInfo("C:\\TestFilestore\\");
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;
Microsoft.Office.Interop.Word.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(".doc", ".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 case to type_application so that it will find the correct quit method.
((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
word = null;
}