一、PDF轉圖片的作用
PDF作為一種可移植性強、不受操作系統和軟硬體的限制而有廣泛應用的文檔格式,然而與之不同的是,圖片在互聯網普及的大環境下,能夠被直接顯示和瀏覽,因此,以PDF為載體時,常常需要將其轉換為圖片,使其能夠被HTML加工並在網頁上展示出來。
二、PDF轉圖片的實現方法
PDF轉圖片在網路編程中也是一個非常常見的需求,實現PDF轉圖片需要藉助第三方工具庫,在C#中推薦使用Ghostscript和iTextSharp。下面我們將分別介紹兩種方法。
三、使用Ghostscript實現PDF轉圖片
Ghostscript是一款開源的,支持多操作系統(Windows、Linux、Mac)的PostScript和PDF解釋器,具有非常好的PDF轉圖片的功能,經過個人測試,Ghostscirpt的轉換質量比iTextSharp更好,同時也較穩定。利用Ghostscript進行PDF轉圖片的代碼如下:
using System.Diagnostics; using System.IO; public bool PdfConvertToImage(string sourcePdfPath,int pageIndex,string destImagePath) { string exePath = @"C:/Program Files/gs/gs9.26/bin/gswin64c.exe"; string para = "-dNOPAUSE -sDEVICE=jpeg -r200 -dFirstPage="+pageIndex+" -dLastPage="+pageIndex+" -o "+destImagePath+" "+sourcePdfPath; Process p = new Process(); p.StartInfo.FileName = exePath; p.StartInfo.Arguments = para; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; p.Start(); string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); return true; }
參數解讀:
- -dNOPAUSE:設置不終止列印並在輸出前保持進程持續運行的模式,以便通過繼續輸入數據來獲得多頁輸出。
- -sDEVICE=jpeg:指定輸出設備為jpeg格式。
- -r200:設置輸出圖像解析度為200dpi。
- -dFirstPage、-dLastPage:指定轉換的頁數範圍。
- -o:指定輸出圖片的路徑。
四、使用iTextSharp實現PDF轉圖片
iTextSharp是一個非常著名的PDF處理庫,iTextSharp提供了PDF到圖片的實現方式,但是它的轉換質量比較一般,需要處理生成的圖片不清晰的問題,同時轉換速度較慢。下面是利用iTextSharp進行PDF轉圖片的代碼:
using System.Drawing; using iTextSharp.text; using iTextSharp.text.pdf; public bool PdfConvertToImage(string sourcePdfPath, int pageIndex, string destImagePath) { using (PdfReader reader = new PdfReader(sourcePdfPath)) { Rectangle rect = reader.GetPageSize(pageIndex); Document document = new Document(rect, 0, 0, 0, 0); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destImagePath, FileMode.Create)); document.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage page = writer.GetImportedPage(reader, pageIndex); cb.AddTemplate(page, 1, 1); document.Close(); } return true; }
iTextSharp實現PDF轉圖片的原理是解析PDF文件內容,然後將PDF文件的內容傳遞給PDF轉圖片API進行處理。
五、總結
PDF轉圖片的實現需要藉助第三方工具庫,通常推薦使用Ghostscript和iTextSharp兩種方法,Ghostscript的轉換質量比較好,但需要安裝Ghostscript環境,iTextSharp實現方式較為簡單,但轉換質量較一般。根據實際需求可以選擇最適合的轉換方法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/180027.html