私はこのサイトでこの素晴らしい、機能するコードを見つけましたが、いくつか変更を加えたかったのです。
アップロードするドキュメントをユーザーに依頼したいのですが、すべてのdoc、docx、Excelファイルの変換など、まだPDF形式でない場合は、ドキュメントをPDFファイルに変換したいと思います。
.docファイルで動作するようになりました。さらにdoを追加したい場合は、それらを「* .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;
}