1. 程式人生 > WINDOWS開發 >【轉】論c#如何將word檔案轉換成pdf檔案

【轉】論c#如何將word檔案轉換成pdf檔案

引用 using Microsoft.Office.Interop.Word; 

 

/// <summary>

        /// 把Word檔案轉換成pdf檔案
        /// </summary>
        /// <param name="sourcePath">需要轉換的檔案路徑和檔名稱</param>
        /// <param name="targetPath">轉換完成後的檔案的路徑和檔名名稱</param>
        /// <returns>成功返回true,失敗返回false</returns>
public static bool GetBoolPDF(string sourcePath,string targetPath) { bool result = false; WdExportFormat wdExportFormatPDF = WdExportFormat.wdExportFormatPDF;//轉換格式1.wdExportFormatPDF轉換成pdf格式 2.wdExportFormatXPS轉換成xps格式 object missing = Type.Missing; Microsoft.Office.Interop.Word.ApplicationClass applicationClass
= null; Document document = null; try { applicationClass = new Microsoft.Office.Interop.Word.ApplicationClass(); object inputfileName = sourcePath;//需要轉格式的檔案路徑 string outputFileName = targetPath;//轉換完成後PDF或XPS檔案的路徑和檔名名稱 WdExportFormat exportFormat = wdExportFormatPDF;//
匯出檔案所使用的格式 bool openAfterExport = true;//轉換完成後是否開啟 WdExportOptimizeFor wdExportOptimizeForPrint = WdExportOptimizeFor.wdExportOptimizeForPrint;//匯出方式1.wdExportOptimizeForPrint針對列印進行匯出,質量較高,生成的檔案大小較大。2.wdExportOptimizeForOnScreen 針對螢幕顯示進行匯出,質量較差,生成的檔案大小較小。 WdExportRange wdExportAllDocument = WdExportRange.wdExportAllDocument;//匯出全部內容(列舉) int from = 0;//起始頁碼 int to = 0;//結束頁碼 WdExportItem wdExportDocumentContent = WdExportItem.wdExportDocumentContent;//指定匯出過程中是否只包含文字或包含文字的標記.1.wdExportDocumentContent:匯出檔案沒有標記,2.匯出檔案有標記 bool includeDocProps = true;//指定是否包含新匯出的檔案在文件屬性 bool keepIRM = true;// WdExportCreateBookmarks wdExportCreateWordBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks;//1.wdExportCreateNoBookmarks:不要在匯出檔案中建立書籤,2.wdExportCreateHeadingBookmarks:標題和文字框匯出的檔案中建立一個書籤,3.wdExportCreateWordBookmarks每個字的書籤,其中包括除包含頁首和頁尾中的所有書籤匯出的檔案中建立一個書籤。 bool docStructureTags = true; bool bitmapMissingFonts = true; bool UseISO19005_1 = false;//生成的文件是否符合 ISO 19005-1 (PDF/A) document = applicationClass.Documents.Open(ref inputfileName,ref missing,ref missing); if (document != null) { document.ExportAsFixedFormat(outputFileName,exportFormat,openAfterExport,wdExportOptimizeForPrint,wdExportAllDocument,from,to,wdExportDocumentContent,includeDocProps,keepIRM,wdExportCreateWordBookmarks,docStructureTags,bitmapMissingFonts,UseISO19005_1,ref missing); } result = true; } catch { result = false; } finally { if (document != null) { document.Close(ref missing,ref missing); document = null; } if (applicationClass != null) { applicationClass.Quit(ref missing,ref missing); applicationClass = null; } } return result; }