2012-03-19 74 views
0

我有一种情况,我需要将Doc文件转换为PDF文件。我正在vb.net中开发Windows应用程序。如果可能的话,我也不想使用第三方dll。 所以任何人都可以给我一些更多的想法?将Doc文件转换为VB.Net中的PDF

+0

那么,哪些解决方案已经通过了你实现这一点,无论是的下方或其他有所一个? – 2012-08-01 10:02:24

+0

我正在使用第二个来自以下答案。我正在使用Microsoft.Office.Interop.Word。 – 2012-08-01 13:14:41

回答

2

您可以使用Office互操作这一点。但最好是使用一些托管库一样的Aspose

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 list of Word files in specified directory 
DirectoryInfo dirInfo = new DirectoryInfo(@"\\server\folder"); 
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(".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; 
+0

其很棒。但我不想使用第三方DLL。还有什么其他的办法吗?如果我使用Microsoft.Office.Interop.Word然后我需要在每个电脑上安装我需要安装我的exe的办公室。所以它不可能在PC上。 – 2012-03-19 13:44:49

1
Imports Microsoft.Office.Interop 

'This code happens to be loading a template, but it isn't necessary... 

'Opens Word Application 

Dim MyApp As New Word.Application 

'Opens new WordDoc 

Dim MyWordDoc As Word.Document = MyApp.Documents.Add(template) 

MyApp.Visible = True 

MyWordDoc = MyApp.ActiveDocument 

'code to fill doc 

'code to fill doc 

'code to fill doc 

MyWordDoc.SaveAs(FileLocation, Word.WdSaveFormat.wdFormatPDF)