僅為了收藏,備用。原位址是: http://www.cnblogs.com/bach-gould
國慶放假前,公司有個項目裡要用到office、pdf以及圖檔的互轉,自己以前沒有接觸過,是以整理了網上林林總總的辦法,也算是總結出了最簡單有效的辦法:office -> pdf 應用Adobe Acrobat 8 Pro的一個PDFMakerAPI.dll程式集;pdf -> png(jpg,gif...)應用Ghostscript。下面詳述說明:
一、準備工作:
1.安裝Adobe Acrobat 8 Pro,本人安裝的是8.1.2版本,在你的安裝目錄下(例如我自己的:C:\Program Files\Adobe\Acrobat 8.0\PDFMaker\Common\)common目錄中找到PDFMakerAPI.dll程式集,拷貝出到項目中放DLL的檔案夾(此檔案夾為使用者儲存DLL檔案的檔案夾,名稱以自己項目為準),并在項目裡對其添加引用。
2.安裝Ghostscript,本人安裝的是8.63版本,需要用的的其他DLL:FontBox-0.1.0-dev.dll,IKVM.GNU.Classpath.dll,IKVM.Runtime.dll,PDFBox-0.7.3.dll,其中IKVM.GNU.Classpath.dll,PDFBox-0.7.3.dll要在項目裡對其添加引用,其他兩個(4個dll均放到)放到DLL檔案夾裡即可。
3.為Ghostscript配置Web.config:
<appSettings>
<add key="GhostScriptView" value="C:/Program Files/gs/gs8.63/bin"/>
<add key="GhostScriptArguments" value="-dSAFER -dBATCH -dNOPAUSE -r150 -sDEVICE=jpeg -dGraphicsAlphaBits=4"/>
</appSettings>
找到自己對應的Ghostscript安裝目錄,自行修改。
二、應用:
1.office -> pdf
引用命名空間:using PDFMAKERAPILib;關鍵代碼如下:
2 | ///參數:docfile,源office檔案絕對路徑及檔案名(C:\office\myDoc.doc);printpath,pdf檔案儲存路徑(D:\myPdf);printFileName,保 |
3 | ///存pdf檔案的檔案名(myNewPdf.pdf) |
6 | objectmissing = System.Type.Missing; |
7 | PDFMakerAppapp = new PDFMakerApp(); |
8 | app.CreatePDF(docfile, printpath + printFileName, PDFMakerSettings.kConvertAllPages, false , true , true , missing); |
2.pdf-> 圖檔
引用命名空間:using org.pdfbox.pdmodel;關鍵代碼如下:
02 | /// <param name="pdfFile">PDF文檔實體路徑</param> |
03 | /// <param name="imgPath">轉換成的圖檔檔案的存放實體路徑</param> |
05 | public static void PdfToImages( string pdfFile, string imgPath) |
07 | PDDocument doc = PDDocument.load(pdfFile); |
08 | int pageCount = doc.getDocumentCatalog().getAllPages().size(); //計算pdf文檔的總頁數 |
10 | string pdfFileName = Path.GetFileName(pdfFile); |
11 | int index = pdfFileName.LastIndexOf( '.' ); |
13 | pdfFileName = pdfFileName.Substring(0, index); |
15 | string imgFile = Path.Combine(imgPath, pdfFileName); //轉換成的圖檔檔案 |
17 | if (pageCount == 0) return ; |
21 | if (File.Exists(imgFile)) |
28 | for ( int i = 0; i < pageCount; i++) |
30 | string _imgFile = imgFile + (i + 1).ToString() + ".png" ; |
31 | if (File.Exists(_imgFile)) |
33 | File.Delete(_imgFile); |
39 | ProcessStartInfo info = new ProcessStartInfo(); |
40 | info.CreateNoWindow = true ; |
41 | info.WindowStyle = ProcessWindowStyle.Hidden; |
42 | info.WorkingDirectory = System.Configuration.ConfigurationManager.AppSettings[ "GhostScriptView" ]; |
43 | info.Arguments = System.Configuration.ConfigurationManager.AppSettings[ "GhostScriptArguments" ] + @" -sOutputFile=" + imgFile + " " + pdfFile; |
44 | info.FileName = @"gswin32c.exe" ; |
45 | Process subProcess = new Process(); |
46 | subProcess.StartInfo = info; |
48 | subProcess.WaitForExit( int .MaxValue); |
完成上述幾步即可簡便完美的完成office到彩色圖檔的轉換,大家不妨也試試。
3.總結和說明:
Acrobat 8 Pro需要激活和注冊;
Acrobat 8 Pro生成pdf的時候會有自己的虛拟列印機彈出框,當office檔案為ppt或者xls的時候會打開檔案然後再關閉,doc則不會;
office轉換的pdf存放路徑不要帶有中文;