2012-03-19 131 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)