将单个doc文件转换为pdf

时间:2011-03-11 07:52:25

标签: c# .net visual-studio pdf doc

我使用以下代码How do I convert Word files to PDF programmatically?将doc文件转换为pdf。但代码提到从特定目录获取所有.doc文件,而我希望只有我从应用程序中选择的文件或有时只选择一个文件。

请指导我

谢谢!

3 个答案:

答案 0 :(得分:5)

针对单个文件修改的相同代码:

using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

...

// 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 a Word file
FileInfo wordFile = new FileInfo("myDoc.doc");

word.Visible = false;
word.ScreenUpdating = false;

// 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(".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 cast to type _Application so that it will find
// the correct Quit method.
((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
word = null;

答案 1 :(得分:2)

代码正在查找文件夹中的所有.doc文件并循环遍历它们。如果你jut在文件夹中有一个文件,它只会转换那个文件。

您可以更改此行代码:

FileInfo[] wordFiles = dirInfo.GetFiles("*.doc");

只是查找你的文件,例如

FileInfo[] wordFiles = dirInfo.GetFiles("myselectedfile.doc");

答案 2 :(得分:0)