将多个文件的文本从用户输入转换为pdf,而不是从文件目录转换
本文关键字:转换 pdf 文件目录 输入 文件 用户 文本 | 更新日期: 2023-09-27 17:59:46
我在这个网站上发现了这段不错的、可工作的代码,但我想做一些修改。
我想请求用户上传文档,但如果他们的文档还不是PDF格式,我想将其转换为PDF文件,例如转换所有文档、docx和excel文件。
我用它来处理.doc文件,如果我想添加更多do,我会把它们添加到"*.doc,*.docx,…"吗?
此外,如果文件在同一目录中,则当前程序正在转换该文件。我希望它能接受用户的新目录,并将其保存到不同的目录中,而不一定两者都在同一个地方——例如,程序将从。。。''文档到。。。''上传。我怎么能这么做?
这是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;
}
如果你想迭代所有具有不同扩展名的Word
文档,你可以从一个目录中获取所有文件,并用Linq过滤列表。
这里有一个例子,你需要将它合并回你的代码中才能使它工作,但你会明白的。
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
var oMissing = System.Reflection.Missing.Value;
// grab all the filenames from your directory (*.*) and filter them with linq
var wordDocumentFilenames = Directory.GetFiles(@"C:'TestFilestore'", "*.*").
Where(file =>
file.ToLower().EndsWith("doc") ||
file.ToLower().EndsWith("docx")). // extend the list to your needs
ToList();
foreach (var wordDocumentFilename in wordDocumentFilenames)
{
Microsoft.Office.Interop.Word.Document wordDocument = word.Documents.Open(
wordDocumentFilename,
ref oMissing,
/* supply the rest of the parameters */);
}