将Word,PDF文档转化为图片
1 #region 将Word文档转化为图片 2 /// <summary> 3 /// 将Word文档转化为图片 4 /// </summary> 5 /// <param name="wordpath">需要转换的word文档的全路径</param> 6 public void Word_Convert2Image(string wordpath) 7 { 8 //第一步:将Word文档转化为Pdf文档(中间过程) 9 Aspose.Words.Document doc = new Aspose.Words.Document(wordpath); 10 //生成的pdf的路径 11 string Pdfpath = Server.MapPath("images") + "Word2Pdf.pdf"; 12 doc.Save(Pdfpath, Aspose.Words.SaveFormat.Pdf); //生成中间文档pdf 13 14 //第二部:开始把第一步中转化的pdf文档转化为图片 15 int i = 1; 16 Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(Pdfpath); 17 while (i <= pdfDocument.Pages.Count) 18 { 19 if (!string.IsNullOrEmpty(Pdfpath)) 20 { 21 GetImage(Pdfpath, i); 22 GC.Collect(); //回收内存 23 } 24 i++; 25 } 26 //图片转化完成之后,删除中间过程产生的pdf文档 27 if (File.Exists(Pdfpath)) 28 File.Delete(Pdfpath); 29 } 30 #endregion 31 #region 将pdf转化为图片 32 /// <summary> 33 /// 将PDF 相应的页转换为图片 34 /// </summary> 35 /// <param name="strPDFpath">PDF 路径</param> 36 /// <param name="Page">需要转换的页页码</param> 37 private void GetImage(string strPDFpath, int Page) 38 { 39 GC.Collect(); 40 string strSavePath = Server.MapPath("images"); 41 byte[] ImgData = GetImgData(strPDFpath, Page); 42 MemoryStream ms = new MemoryStream(ImgData, 0, ImgData.Length); 43 Bitmap returnImage = (Bitmap)Bitmap.FromStream(ms); 44 string picName=string.Format("{0}_{1}.jpg", CreatePicName(),Page); 45 string strImgPath = Path.Combine(strSavePath, picName); //图片名称可在此修改 46 returnImage.Save(strImgPath); 47 returnImage.Dispose(); 48 ms.Dispose(); 49 AddImage(Page, picName); //将图片添加到数据库 50 } 51 /// <summary> 52 /// 从PDF中获取首页的图片 53 /// </summary> 54 /// <param name="PDFPath">PDF 文件路径</param> 55 /// <param name="Page">需要获取的第几页</param> 56 /// <returns></returns> 57 private byte[] GetImgData(string PDFPath, int Page) 58 { 59 System.Drawing.Image img = PDFView.ConvertPDF.PDFConvert.GetPageFromPDF(PDFPath, Page, 200, "", true); 60 return GetDataByImg(img);//读取img的数据并返回 61 } 62 /// <summary> 63 /// 将单页的PDF转换为图片 64 /// </summary> 65 /// <param name="_image"></param> 66 /// <returns></returns> 67 private byte[] GetDataByImg(System.Drawing.Image _image) 68 { 69 System.IO.MemoryStream Ms = new MemoryStream(); 70 _image.Save(Ms, System.Drawing.Imaging.ImageFormat.Jpeg); 71 byte[] imgdata = new byte[Ms.Length]; 72 Ms.Position = 0; 73 Ms.Read(imgdata, 0, Convert.ToInt32(Ms.Length)); 74 Ms.Close(); 75 return imgdata; 76 } 77 #endregion