/// <summary> /// 将pdf文档转换为jpg图片 /// </summary> /// <param name="filePath">选择文件的路径</param> /// <param name="fileName">选择文件的文件名称</param> private void pdfConverToImage(string filePath, string fileName) { try { Aspose.Pdf.Document document = new Aspose.Pdf.Document(filePath); Aspose.Pdf.Devices.Resolution resolution = new Aspose.Pdf.Devices.Resolution(300); Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(resolution, 100); for (int i = 1; i <= document.Pages.Count; i++) { FileStream fileStream = new FileStream(fileName.Split('.')[0] + i + ".jpg", FileMode.OpenOrCreate); jpegDevice.Process(document.Pages[i], fileStream); fileStream.Close(); } lblConver.Visible = false; DialogResult dialogResult = MessageBox.Show("转换成功,是否打开转换图片文件夹", "转换结果", MessageBoxButtons.OKCancel); if (dialogResult == DialogResult.OK) { System.Diagnostics.Process.Start("Explorer.exe", Environment.CurrentDirectory); } } catch (Exception) { lblConver.Enabled = false; MessageBox.Show("转换失败", "转换结果"); } }
public static void PDFThumbImage(string pdfInputPath, string imageOutputPath, string imageName) { if (!File.Exists(pdfInputPath)) { throw new FileNotFoundException(); } if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); } //Open document Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(pdfInputPath); int Count = pdfDocument.Pages.Count; Count = 1; for (int pageCount = 1; pageCount <= Count; pageCount++)//1 { string _path = Path.Combine(imageOutputPath, imageName) + "_" + pageCount + ".jpg"; using (FileStream imageStream = new FileStream(_path, FileMode.Create)) { //Create Resolution object Aspose.Pdf.Devices.Resolution rs = new Aspose.Pdf.Devices.Resolution(300); Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(200, 150, rs, 100); //Convert a particular page and save the image to stream jpegDevice.Process(pdfDocument.Pages[pageCount], imageStream); //Close stream imageStream.Close(); } } }
public void ConvertToImage(string filePath, int resolution) { Aspose.Pdf.Document doc = new Aspose.Pdf.Document(filePath); string imageName = Path.GetFileNameWithoutExtension(filePath); for (int i = 1; i <= doc.Pages.Count; i++) { int pageNum = i; string imgPath = string.Format("{0}_{1}.Jpeg", Path.Combine(Path.GetDirectoryName(filePath), imageName), i.ToString("000")); if (File.Exists(imgPath)) { InvokeCallBack(pageNum, imgPath); continue; } using (MemoryStream stream = new MemoryStream()) { Aspose.Pdf.Devices.Resolution reso = new Aspose.Pdf.Devices.Resolution(resolution); Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(reso, 100); jpegDevice.Process(doc.Pages[i], stream); using (Image image = Image.FromStream(stream)) { new Bitmap(image).Save(imgPath, ImageFormat.Jpeg); } } InvokeCallBack(pageNum, imgPath); } Task.WaitAll(TaskList.ToArray()); }
private void button1_Click(object sender, EventArgs e) { var imageWidth = 77; var imageHeight = 109; var resolution = new Aspose.Pdf.Devices.Resolution(300); var imageDevice = new Aspose.Pdf.Devices.PngDevice(imageWidth, imageHeight, resolution); var path = Path.GetDirectoryName(Application.ExecutablePath).Replace("bin\\Debug", string.Empty); var testFile = path + @"TestImages\Superheros.pdf"; var imageLocation = path + "GeneratedImages\\Superheros.png"; var dummypath = path + "DummyFolder\\Superheroes.pdf"; var pdfDocument = new Aspose.Pdf.Document(testFile); imageDevice.RenderingOptions.SystemFontsNativeRendering = true; //Having this line results in "GeneratedImages\\Superheros.png"; being empty. Not having it makes the said png have the text from the source-pdf pdfDocument.Save(dummypath); if (imageDevice != null) { using (var imageStream = new FileStream(imageLocation, FileMode.OpenOrCreate)) { imageDevice.Process(pdfDocument.Pages[1], imageStream); imageStream.Close(); } } }
public void PdfToImage(Document file, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution = 128) { file.isyl = "1"; new DocumentB().Update(file); Task <string> TaskCover = Task.Factory.StartNew <string>(() => { Aspose.Pdf.Document doc = new Aspose.Pdf.Document(file.FullPath); if (doc == null) { throw new Exception("pdf文件无效或者pdf文件被加密!"); } if (imageOutputDirPath.Trim().Length == 0) { imageOutputDirPath = Path.GetDirectoryName(file.FullPath); } if (!Directory.Exists(imageOutputDirPath)) { Directory.CreateDirectory(imageOutputDirPath); } if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > doc.Pages.Count || endPageNum <= 0) { endPageNum = doc.Pages.Count; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } string imageNamePrefix = Path.GetFileNameWithoutExtension(file.FullPath); for (int i = startPageNum; i <= endPageNum; i++) { MemoryStream stream = new MemoryStream(); string imgPath = Path.Combine(imageOutputDirPath, imageNamePrefix) + "_" + i.ToString() + ".png"; Aspose.Pdf.Devices.Resolution reso = new Aspose.Pdf.Devices.Resolution(resolution); Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(reso, 100); jpegDevice.Process(doc.Pages[i], stream); Image img = Image.FromStream(stream); Bitmap bm = new Bitmap(img); bm.Save(imgPath, ImageFormat.Jpeg); img.Dispose(); stream.Dispose(); bm.Dispose(); } file.ylinfo = endPageNum.ToString(); file.isyl = "2"; new DocumentB().Update(file); return("success"); }); }
public static void Pdf2Jpg(Aspose.Pdf.Document pdfDocument, string targetPath, int?pages) { if (string.IsNullOrEmpty(targetPath)) { throw new ArgumentNullException("targetPath"); } var dir = Path.GetDirectoryName(targetPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (pdfDocument.Pages.Count == 1) { pages = 1; } if (pages != null) { using (var imageStream = new FileStream(targetPath, FileMode.Create)) { var resolution = new Aspose.Pdf.Devices.Resolution(ConfigDefine.Pdf2JpgResolution); var jpegDevice = new Aspose.Pdf.Devices.JpegDevice(resolution, 100); jpegDevice.Process(pdfDocument.Pages[pages.Value], imageStream); imageStream.Close(); } } else { var imageDir = Path.Combine(dir, Guid.NewGuid().ToString()); Directory.CreateDirectory(imageDir); for (pages = 1; pages <= pdfDocument.Pages.Count; pages++) { using (var imageStream = new FileStream(Path.Combine(imageDir, pages + ".jpg"), FileMode.Create)) { var resolution = new Aspose.Pdf.Devices.Resolution(ConfigDefine.Pdf2JpgResolution); var jpegDevice = new Aspose.Pdf.Devices.JpegDevice(resolution, 100); jpegDevice.Process(pdfDocument.Pages[pages.Value], imageStream); imageStream.Close(); } } MergerImage(imageDir, targetPath); try { Directory.Delete(imageDir, true); } catch (Exception ex) { throw new ArgumentNullException(string.Format("删除临时目录出错:{0};其他错误信息:{1}", imageDir, ex)); } } }
public string PdfToImageByPath(string FilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution = 128) { Aspose.Pdf.Document doc = new Aspose.Pdf.Document(FilePath); if (doc == null) { throw new Exception("pdf文件无效或者pdf文件被加密!"); } if (imageOutputDirPath.Trim().Length == 0) { imageOutputDirPath = Path.GetDirectoryName(FilePath); } if (!Directory.Exists(imageOutputDirPath)) { Directory.CreateDirectory(imageOutputDirPath); } if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > doc.Pages.Count || endPageNum <= 0) { endPageNum = doc.Pages.Count; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } string imageNamePrefix = Path.GetFileNameWithoutExtension(FilePath); for (int i = startPageNum; i <= endPageNum; i++) { MemoryStream stream = new MemoryStream(); string imgPath = Path.Combine(imageOutputDirPath, imageNamePrefix) + "_" + i.ToString() + ".png"; Aspose.Pdf.Devices.Resolution reso = new Aspose.Pdf.Devices.Resolution(resolution); Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(reso, 100); jpegDevice.Process(doc.Pages[i], stream); Image img = Image.FromStream(stream); Bitmap bm = new Bitmap(img); bm.Save(imgPath, ImageFormat.Jpeg); img.Dispose(); stream.Dispose(); bm.Dispose(); } return(endPageNum.ToString()); }
/// <summary> /// PDF转图片到数据流 /// </summary> /// <param name="originFilePath"></param> /// <param name="startPageNum"></param> /// <param name="endPageNum"></param> /// <param name="imageFormat"></param> /// <param name="resolution"></param> /// <returns></returns> public List <Stream> ConvertPDFToImage(string originFilePath, int startPageNum, int endPageNum, ImageFormat imageFormat, int resolution) { string extension = Path.GetExtension(originFilePath.Trim()).ToLower(); if (extension != ".pdf") { throw new Exception("文件类型错误"); } List <Stream> listImage = new List <Stream>(); try { Aspose.Pdf.Document doc = new Aspose.Pdf.Document(originFilePath); if (doc == null) { throw new Exception("pdf文件无效或者pdf文件被加密!"); } if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > doc.Pages.Count || endPageNum <= 0) { endPageNum = doc.Pages.Count; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } if (resolution <= 0) { resolution = 128; } string imageNamePrefix = System.IO.Path.GetFileNameWithoutExtension(originFilePath); ImageSaveOptions imageSaveOptions = new ImageSaveOptions(GetSaveFormat(imageFormat)); for (int i = startPageNum; i <= endPageNum; i++) { MemoryStream stream = new MemoryStream(); Aspose.Pdf.Devices.Resolution reso = new Aspose.Pdf.Devices.Resolution(resolution); Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(reso, 100); jpegDevice.Process(doc.Pages[i], stream); listImage.Add(stream); } } catch (Exception ex) { throw new Exception(ex.ToString()); } return(listImage); }
static void pdf2Image() { string path = "\\\\Lsdwzjdit014\\a\\test.pdf";//@"C:\Users\zhangzheng\Desktop\test.pdf"; Aspose.Pdf.Document document = new Aspose.Pdf.Document(path); //document.Save("d:\\a.html", SaveFormat.Html); //document.Pages.Count MemoryStream memoryStream = new MemoryStream(); Aspose.Pdf.Devices.Resolution reso = new Aspose.Pdf.Devices.Resolution(128); Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(reso, 100); jpegDevice.Process(document.Pages[1], memoryStream); System.Drawing.Image img = System.Drawing.Image.FromStream(memoryStream); img.Save("d:\\a.jpeg", ImageFormat.Jpeg); }
static void ppt2Image() { string path = @"C:\Users\zhangzheng\Desktop\Visual Studio Team Services.pptx"; Presentation presentation = new Presentation(path); MemoryStream stream = new MemoryStream(); presentation.Save(stream, Aspose.Slides.Export.SaveFormat.Pdf); Aspose.Pdf.Document document = new Aspose.Pdf.Document(stream); MemoryStream memoryStream = new MemoryStream(); Aspose.Pdf.Devices.Resolution reso = new Aspose.Pdf.Devices.Resolution(128); Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(reso, 100); jpegDevice.Process(document.Pages[1], memoryStream); System.Drawing.Image img = System.Drawing.Image.FromStream(memoryStream); img.Save("d:\\A\\ppt.jpg", ImageFormat.Jpeg); }
public static void Run() { // ExStart:PerformOCROnPDF // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OCR(); //Create an instance of Document to load the PDF var pdfDocument = new Aspose.Pdf.Document(dataDir + "Sample.pdf"); //Create an instance of OcrEngine for recognition var ocrEngine = new Aspose.OCR.OcrEngine(); //Iterate over the pages of PDF for (int pageCount = 1; pageCount <= pdfDocument.Pages.Count; pageCount++) { //Creating a MemoryStream to hold the image temporarily using (var imageStream = new System.IO.MemoryStream()) { //Create Resolution object with DPI value var resolution = new Aspose.Pdf.Devices.Resolution(300); //Create JPEG device with specified attributes (Width, Height, Resolution, Quality) //where Quality [0-100], 100 is Maximum var jpegDevice = new Aspose.Pdf.Devices.JpegDevice(resolution, 100); //Convert a particular page and save the image to stream jpegDevice.Process(pdfDocument.Pages[pageCount], imageStream); imageStream.Position = 0; //Set Image property of OcrEngine to the stream obtained from previous step ocrEngine.Image = Aspose.OCR.ImageStream.FromStream(imageStream, Aspose.OCR.ImageStreamFormat.Jpg); //Perform OCR operation on one page at a time if (ocrEngine.Process()) { Console.WriteLine(ocrEngine.Text); } } } // ExStart:PerformOCROnPDF }
/// <summary> /// PdfToImgMethod /// </summary> /// <param name="filename"></param> /// <param name="i"></param> /// <param name="pdf"></param> private static void PdfToImgMethod(string filename, int i, Aspose.Pdf.Document pdf) { try { string imgpath = imageDirectoryPath + "/" + filename + "_" + i + ".jpeg"; if (!File.Exists(imgpath)) { using (FileStream imageStream = new FileStream(imgpath, FileMode.Create)) { Aspose.Pdf.Devices.Resolution resolution = new Aspose.Pdf.Devices.Resolution(90); // 像素 Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(resolution, 80); // 图片质量 jpegDevice.Process(pdf.Pages[i], imageStream); imageStream.Close(); } } } catch (Exception) { } }
public void ProcessRequest(HttpContext context) { this.MyUtility.InitLog("Images"); context.Response.Clear(); string data = string.Empty, message = string.Empty; SysCode code = SysCode.A000; string session_key = string.Empty, file_id = string.Empty, file_full_path = string.Empty, year_and_month = string.Empty, user_id = string.Empty; int file_type = 0, file_seq = 0; string[] para_arry = null; List <IDataParameter> para = null; DataTable dt = null; string strSql = string.Empty; Aspose.Pdf.License license = new Aspose.Pdf.License(); license.SetLicense("Aspose.Pdf.lic"); try { #region 取得參數 data = context.GetRequest("data").DecryptDES(); if (String.IsNullOrEmpty(data)) { throw new Utility.ProcessException(string.Format("參數為空值"), ref code, SysCode.E004); } this.MyUtility.WriteLog(Mode.LogMode.DEBUG, context, string.Format("DATA.Parameter:{0}", data)); #endregion para_arry = data.Split('|'); if (!para_arry.Length.Equals(7)) { throw new Utility.ProcessException(string.Format("參數不足{0}/7", para_arry.Length), ref code, SysCode.E004); } file_id = para_arry[0]; file_type = Convert.ToInt32(para_arry[1]); year_and_month = para_arry[2]; session_key = para_arry[3]; file_full_path = para_arry[4]; file_seq = Convert.ToInt32(para_arry[5]); user_id = para_arry[6]; bool exists = File.Exists(file_full_path); if (!exists && file_type < 10) { throw new Utility.ProcessException(string.Format("調閱檔案不存在"), ref code, SysCode.E006); } if (!exists && file_type.Equals(11)) { DataRow[] dr = null; strSql = this.MyUtility.Select.FILE_TABLE_NOT_IMAGE(year_and_month, file_id, ref para); #region SQL Debug this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, strSql); this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, para.ToLog()); #endregion dt = this.MyUtility.DBConn.GeneralSqlCmd.ExecuteToDataTable(strSql, para); string pdf_file_path = string.Empty; if (dt.Rows.Count > 0) { dr = dt.Select(string.Format("FILE_TYPE=1")); if (dr != null && dr.Length > 0) { pdf_file_path = dr[0]["FILE_ROOT"].ToString().Trim().FilePathCombine(dr[0]["FILE_PATH"].ToString().Trim()); } } exists = File.Exists(pdf_file_path); this.MyUtility.WriteLog(context, string.Format("PDF.Path:{0},{1}", pdf_file_path, exists)); if (!exists) { throw new Utility.ProcessException(string.Format("PDF不存在"), ref code, SysCode.E006); } #region PDF 切割 try { using (Document pdfDocument = new Document(pdf_file_path)) { Aspose.Pdf.Devices.Resolution resolution = new Aspose.Pdf.Devices.Resolution(150); Aspose.Pdf.Devices.JpegDevice jpegDeviceLarge = new Aspose.Pdf.Devices.JpegDevice(resolution); if (file_seq <= 0 || file_seq > pdfDocument.Pages.Count) { this.MyUtility.WriteLog(Mode.LogMode.ERROR, context, string.Format("PDF.Pages.Count:{0},FILE_SEQ:{1}", pdfDocument.Pages.Count, file_seq)); throw new Utility.ProcessException(string.Format("查無影像檔及無法從PDF內拆檔"), ref code, SysCode.E005); } jpegDeviceLarge.Process(pdfDocument.Pages[file_seq], file_full_path); if (!File.Exists(file_full_path)) { throw new Utility.ProcessException(string.Format("頁次{0}拆檔失敗", file_seq), ref code, SysCode.E005); } } } catch (System.Exception ex) { this.MyUtility.WriteLog(Mode.LogMode.ERROR, context, ex.ToString()); throw new Utility.ProcessException(ex.Message, ref code, SysCode.E005); } #endregion } this.MyUtility.DBLog(context, code, "Images", session_key, user_id, data); string file_ext = Path.GetExtension(file_full_path).Remove(0, 1); if (file_type < 10) { this.MyUtility.ResponseFile(context, file_full_path, file_ext); } else { this.MyUtility.DrawImage(context, file_full_path, file_ext); } } catch (System.Exception ex) { message = ex.Message; this.MyUtility.WriteLog(Mode.LogMode.ERROR, context, ex.ToString()); code = !code.Equals(SysCode.A000) ? code : SysCode.E999; this.MyUtility.DBLog(context, code, "Images", session_key, user_id, !String.IsNullOrEmpty(data) ? string.Format("{0}\r\n{1}", data, ex.Message) : ex.Message); this.MyUtility.DrawMessage(context, ex.Message); this.MyUtility.SendEMail(context, "Images", session_key, code); } finally { license = null; dt = null; para = null; this.MyUtility.CloseConn(); GC.Collect(); GC.WaitForPendingFinalizers(); } }
/// <summary> /// 将pdf文档转换为图片的方法 /// </summary> /// <param name="originFilePath">pdf文件路径</param> /// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为pdf所在路径</param> /// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为pdf总页数</param> /// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param> public void ConvertToImage(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution, string zskguid, string zskname) { try { Aspose.Pdf.Document doc = new Aspose.Pdf.Document(originFilePath); if (doc == null) { throw new Exception("pdf文件无效或者pdf文件被加密!"); } if (imageOutputDirPath.Trim().Length == 0) { imageOutputDirPath = Path.GetDirectoryName(originFilePath); } if (!Directory.Exists(imageOutputDirPath)) { Directory.CreateDirectory(imageOutputDirPath); } if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > doc.Pages.Count || endPageNum <= 0) { endPageNum = doc.Pages.Count; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } if (resolution <= 0) { resolution = 128; } string imageNamePrefix = Path.GetFileNameWithoutExtension(originFilePath); for (int i = startPageNum; i <= endPageNum; i++) { if (this.cancelled) { break; } MemoryStream stream = new MemoryStream(); string imgPath = Path.Combine(imageOutputDirPath, imageNamePrefix) + "_" + i.ToString("000") + ".jpg"; Aspose.Pdf.Devices.Resolution reso = new Aspose.Pdf.Devices.Resolution(resolution); Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(reso, 100); jpegDevice.Process(doc.Pages[i], stream); Image img = Image.FromStream(stream); Bitmap bm = ESBasic.Helpers.ImageHelper.Zoom(img, 0.6f); bm.Save(imgPath, ImageFormat.Jpeg); img.Dispose(); stream.Dispose(); bm.Dispose(); System.Threading.Thread.Sleep(200); if (this.ProgressChanged != null) { this.ProgressChanged(i - 1, endPageNum); } string imgname = zskname + "_" + i.ToString("000"); string[] sArray = System.Text.RegularExpressions.Regex.Split(imgPath, "ZSKWJ", System.Text.RegularExpressions.RegexOptions.IgnoreCase); string imgpatch = "ZSKWJ" + sArray[1].ToString(); } if (this.cancelled) { return; } if (this.ConvertSucceed != null) { this.ConvertSucceed(); } } catch (Exception ex) { if (this.ConvertFailed != null) { this.ConvertFailed(ex.Message); } } }
/// <summary> /// 将pdf文档转换为图片的方法 /// </summary> /// <param name="originFilePath">pdf文件路径</param> /// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为pdf所在路径</param> /// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为pdf总页数</param> /// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param> private void ConvertToImage(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution) { try { Aspose.Pdf.Document doc = new Aspose.Pdf.Document(originFilePath); if (doc == null) { throw new Exception("pdf文件无效或者pdf文件被加密!"); } if (imageOutputDirPath.Trim().Length == 0) { imageOutputDirPath = Path.GetDirectoryName(originFilePath); } if (!Directory.Exists(imageOutputDirPath)) { Directory.CreateDirectory(imageOutputDirPath); } if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > doc.Pages.Count || endPageNum <= 0) { endPageNum = doc.Pages.Count; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } if (resolution <= 0) { resolution = 128; } string imageNamePrefix = Path.GetFileNameWithoutExtension(originFilePath); for (int i = startPageNum; i <= endPageNum; i++) { if (this.cancelled) { break; } MemoryStream stream = new MemoryStream(); string imgPath = Path.Combine(imageOutputDirPath, imageNamePrefix) + "_" + i.ToString("000") + ".jpg"; Aspose.Pdf.Devices.Resolution reso = new Aspose.Pdf.Devices.Resolution(resolution); Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(reso, 100); jpegDevice.Process(doc.Pages[i], stream); Image img = Image.FromStream(stream); Bitmap bm = ESBasic.Helpers.ImageHelper.Zoom(img, 0.6f); bm.Save(imgPath, ImageFormat.Jpeg); img.Dispose(); stream.Dispose(); bm.Dispose(); System.Threading.Thread.Sleep(200); if (this.ProgressChanged != null) { this.ProgressChanged(i - 1, endPageNum); } } if (this.cancelled) { return; } if (this.ConvertSucceed != null) { this.ConvertSucceed(); } } catch (Exception ex) { if (this.ConvertFailed != null) { this.ConvertFailed(ex.Message); } } }
public void ProcessRequest(HttpContext context) { this.MyUtility.InitLog("GetImageBase64"); context.Response.Clear(); context.Response.ContentType = "application/json"; string json = string.Empty, data = string.Empty, message = string.Empty; SysCode code = SysCode.B000; XmlDocument xmlDoc = null; string xPath = string.Empty, strSql = string.Empty; List <IDataParameter> para = null; DataTable dt = null; string USERID = string.Empty; string year_and_month = string.Empty; string session_key = string.Empty, session_info = string.Empty; Aspose.Pdf.License license = new Aspose.Pdf.License(); license.SetLicense("Aspose.Pdf.lic"); IMAGE_BASE64_CLASS.IMAGE_BASE64_ITEM[] image_item_list = null; try { #region 取得參數 data = context.GetRequest("data"); if (String.IsNullOrEmpty(data)) { throw new Utility.ProcessException(string.Format("參數為空值"), ref code, SysCode.E004); } this.MyUtility.WriteLog(Mode.LogMode.DEBUG, context, string.Format("DATA.JSON:{0}", data)); #endregion xmlDoc = JsonConvert.DeserializeXmlNode(data); XmlNode xmlNodeProcessInfo = xmlDoc.SelectSingleNode(xPath = string.Format("./CHANGINGTEC/PROCESS_INFO")); if (xmlNodeProcessInfo == null) { throw new Utility.ProcessException(xPath, ref code, SysCode.E003); } USERID = xmlNodeProcessInfo.SelectSingleNode(string.Format("USERID"), ref code, false); session_key = xmlNodeProcessInfo.SelectSingleNode(string.Format("SESSION_KEY"), ref code, false); this.MyUtility.WriteLog(context, string.Format("SESSION_KEY:{0}", session_key)); if (String.IsNullOrEmpty(session_key)) { year_and_month = xmlNodeProcessInfo.SelectSingleNode(string.Format("YM"), ref code); this.MyUtility.CheckAndCreateTable(context, year_and_month, ref code); string CHANNEL_CODE = xmlNodeProcessInfo.SelectSingleNode(string.Format("CHANNEL_CODE"), ref code); string TXN_TYPE = xmlNodeProcessInfo.SelectSingleNode(string.Format("TXN_TYPE"), ref code); string TXN_ID = xmlNodeProcessInfo.SelectSingleNode(string.Format("TXN_ID"), ref code); string REPORT_SERIAL_NO = xmlNodeProcessInfo.SelectSingleNode(string.Format("REPORT_SERIAL_NO"), ref code); string GUID = xmlNodeProcessInfo.SelectSingleNode(string.Format("GUID"), ref code); this.MyUtility.DBLog(context, SysCode.B001, "GetImageBase64", string.Empty, USERID, session_info = string.Format("{0}_{1}_{2}_{3}_{4}_{5}", year_and_month, CHANNEL_CODE, TXN_TYPE, TXN_ID, REPORT_SERIAL_NO, GUID)); strSql = this.MyUtility.Select.FILE_TABLE(year_and_month, CHANNEL_CODE, TXN_TYPE, TXN_ID, REPORT_SERIAL_NO, GUID, ref para); #region SQL Debug this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, strSql); this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, para.ToLog()); #endregion dt = this.MyUtility.DBConn.GeneralSqlCmd.ExecuteToDataTable(strSql, para); if (dt.Rows.Count.Equals(0)) { year_and_month = year_and_month.GetPreviousYM(); this.MyUtility.CheckAndCreateTable(context, year_and_month, ref code); strSql = this.MyUtility.Select.FILE_TABLE(year_and_month, CHANNEL_CODE, TXN_TYPE, TXN_ID, REPORT_SERIAL_NO, GUID, ref para); #region SQL Debug this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, strSql); this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, para.ToLog()); #endregion dt = this.MyUtility.DBConn.GeneralSqlCmd.ExecuteToDataTable(strSql, para); } } else { year_and_month = session_key.Split('-')[0]; this.MyUtility.CheckAndCreateTable(context, year_and_month, ref code); this.MyUtility.DBLog(context, SysCode.B001, "GetImageBase64", string.Empty, USERID, session_info = string.Format("{0}_{1}", year_and_month, session_key)); strSql = this.MyUtility.Select.FILE_TABLE(year_and_month, session_key, ref para); #region SQL Debug this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, strSql); this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, para.ToLog()); #endregion dt = this.MyUtility.DBConn.GeneralSqlCmd.ExecuteToDataTable(strSql, para); } if (dt.Rows.Count.Equals(0)) { throw new Utility.ProcessException(string.Format("查無資料"), ref code, SysCode.E007); } this.MyUtility.DBLog(context, SysCode.A001, "GetImageBase64", session_key = dt.Rows[0]["SESSION_KEY"].ToString(), USERID, string.Empty); this.MyUtility.WriteLog(context, string.Format("SESSION_KEY:{0}", session_key)); DataRow[] dr_pdf = dt.Select(string.Format("FILE_TYPE=1")); string pdf_file_full_path = string.Empty; bool pdf_exists = false; if (dr_pdf.Length > 0) { string pdf_file_root = dr_pdf[0]["FILE_ROOT"].ToString(); string pdf_file_path = dr_pdf[0]["FILE_PATH"].ToString(); pdf_file_full_path = pdf_file_root.FilePathCombine(pdf_file_path); pdf_exists = File.Exists(pdf_file_full_path); this.MyUtility.WriteLog(context, string.Format("{0},{1}", pdf_file_full_path, pdf_exists)); } DataRow[] dr_image = dt.Select(string.Format("FILE_TYPE=11")); this.MyUtility.WriteLog(context, string.Format("Image.Count:{0}", dr_image.Length)); if (dr_image.Length.Equals(0)) { throw new Utility.ProcessException(string.Format("查無資料"), ref code, SysCode.E007); } image_item_list = new IMAGE_BASE64_CLASS.IMAGE_BASE64_ITEM[dr_image.Length]; for (int i = 0; i < dr_image.Length; i++) { session_key = dr_image[i]["SESSION_KEY"].ToString(); string file_id = dr_image[i]["FILE_ID"].ToString(); int file_seq = Convert.ToInt16(dr_image[i]["FILE_SEQ"].ToString()); string file_root = dr_image[i]["FILE_ROOT"].ToString(); string file_path = dr_image[i]["FILE_PATH"].ToString(); string file_full_path = file_root.FilePathCombine(file_path); bool exists = File.Exists(file_full_path); this.MyUtility.WriteLog(context, string.Format("{0},{1},{2}", file_seq, file_full_path, exists)); if (!exists && pdf_exists) { #region PDF 切割 try { using (Document pdfDocument = new Document(pdf_file_full_path)) { Aspose.Pdf.Devices.Resolution resolution = new Aspose.Pdf.Devices.Resolution(150); Aspose.Pdf.Devices.JpegDevice jpegDeviceLarge = new Aspose.Pdf.Devices.JpegDevice(resolution); if (file_seq <= 0 || file_seq > pdfDocument.Pages.Count) { this.MyUtility.WriteLog(Mode.LogMode.ERROR, context, string.Format("PDF.Pages.Count:{0},FILE_SEQ:{1}", pdfDocument.Pages.Count, file_seq)); throw new Utility.ProcessException(string.Format("查無影像檔及無法從PDF內拆檔"), ref code, SysCode.E005); } jpegDeviceLarge.Process(pdfDocument.Pages[file_seq], file_full_path); if (!File.Exists(file_full_path)) { throw new Utility.ProcessException(string.Format("頁次{0}拆檔失敗", file_seq), ref code, SysCode.E005); } } } catch (System.Exception ex) { this.MyUtility.WriteLog(Mode.LogMode.ERROR, context, ex.ToString()); throw new Utility.ProcessException(ex.Message, ref code, SysCode.E005); } #endregion } if (!File.Exists(file_full_path)) { throw new Utility.ProcessException(string.Format("頁次{0}圖檔不存在", file_seq), ref code, SysCode.E001); } image_item_list[i] = new IMAGE_BASE64_CLASS.IMAGE_BASE64_ITEM() { FILE_ID = file_id, BODY = file_full_path.FileSerialize() }; } this.MyUtility.DBLog(context, SysCode.B000, "GetImageBase64", session_key, USERID, session_info); } catch (System.Exception ex) { message = ex.Message; this.MyUtility.WriteLog(Mode.LogMode.ERROR, context, ex.ToString()); code = !code.Equals(SysCode.B000) ? code : SysCode.E999; this.MyUtility.DBLog(context, code, "GetImageBase64", session_key, USERID, ex.Message); this.MyUtility.SendEMail(context, "GetImageBase64", session_key, code); } finally { json = JsonConvert.SerializeObject(new IMAGE_BASE64_RESPOSE() { CHANGINGTEC = new IMAGE_BASE64_SYSTEM_CLASS() { SYSTEM = new IMAGE_BASE64_SYSTEM_INFO_CLASS() { //CODE = code.Equals(SysCode.B000) ? SysCode.A000.ToString() : code.Equals(SysCode.E007) ? SysCode.A003.ToString() : code.ToString(), CODE = code.Equals(SysCode.B000) ? SysCode.A000.ToString() : code.ToString(), MESSAGE = message.EncryptBase64(), CASE_INFO = new IMAGE_BASE64_CLASS() { JPG_ITEM = image_item_list } } } }); dt = null; license = null; xmlDoc = null; para = null; this.MyUtility.CloseConn(); xmlDoc = null; GC.Collect(); GC.WaitForPendingFinalizers(); context.Response.Write(json); context.Response.End(); } }
/// <summary> /// PDF转图片到目录 /// </summary> /// <param name="originFilePath"></param> /// <param name="imageOutputDirPath"></param> /// <param name="startPageNum"></param> /// <param name="endPageNum"></param> /// <param name="imageFormat"></param> /// <param name="resolution"></param> /// <returns></returns> public bool ConvertPDFToImage(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, ImageFormat imageFormat, int resolution) { string extension = Path.GetExtension(originFilePath.Trim()).ToLower(); if (extension != ".pdf") { throw new Exception("文件类型错误"); } ArrayList listimagename = new ArrayList(); try { Aspose.Pdf.Document doc = new Aspose.Pdf.Document(originFilePath); if (doc == null) { throw new Exception("pdf文件无效或者pdf文件被加密!"); } if (imageOutputDirPath.Trim().Length == 0) { imageOutputDirPath = System.IO.Path.GetDirectoryName(originFilePath); } if (!Directory.Exists(imageOutputDirPath)) { Directory.CreateDirectory(imageOutputDirPath); } if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > doc.Pages.Count || endPageNum <= 0) { endPageNum = doc.Pages.Count; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } if (resolution <= 0) { resolution = 128; } string imageNamePrefix = System.IO.Path.GetFileNameWithoutExtension(originFilePath); ImageSaveOptions imageSaveOptions = new ImageSaveOptions(GetSaveFormat(imageFormat)); for (int i = startPageNum; i <= endPageNum; i++) { MemoryStream stream = new MemoryStream(); string imgPath = System.IO.Path.Combine(imageOutputDirPath, imageNamePrefix) + "_" + i.ToString("000") + "." + imageFormat.ToString(); Aspose.Pdf.Devices.Resolution reso = new Aspose.Pdf.Devices.Resolution(resolution); Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(reso, 100); jpegDevice.Process(doc.Pages[i], stream); System.Drawing.Image img = System.Drawing.Image.FromStream(stream); img.Save(imgPath); stream.Close(); listimagename.Add(System.IO.Path.Combine(imageOutputDirPath, imageNamePrefix) + "_" + i.ToString("000") + "." + imageFormat.ToString()); } } catch (Exception ex) { return(false); } return(true); }