/// <summary> /// 将Pdf转换成图片存放在指定的文件夹下面并且返回转换了多少张图片(插件:O2S.Components.PDFRender4NETd) /// (使用:调用此方法传递参数,最后一个参数为模糊度(参考传递30)) /// </summary> /// <param name="pdfInputPath">源PDF路径</param> /// <param name="imageOutpPutPath">PDF转化成图片之后存放的路径</param> /// <param name="imageFormat">转换的图片格式</param> /// <param name="difinition">传递参数模糊度</param> /// <returns>返回转换了多少张图片信息</returns> public static int PdfConvertImageInfo(string pdfInputPath, string imageOutpPutPath, ImageFormat imageFormat, float difinition) { try { //第一步:判断需要转换的PDF是否存在 if (!File.Exists(pdfInputPath)) { throw new System.Exception("PDF的路径不存在"); } //第二步:判断存放转换后图片的地址是否存在 if (!Directory.Exists(imageOutpPutPath)) { throw new System.Exception("存放图片的路径不存在"); } //第三步:进行转换(使用插件O2S.Components.PDFRender4NET) PDFFile pdfFile = PDFFile.Open(pdfInputPath); int pageCount = pdfFile.PageCount; for (int i = 0; i < pageCount; i++) { Bitmap bitmap = pdfFile.GetPageImage(i, difinition); bitmap.Save(Path.Combine(imageOutpPutPath, i + "." + imageFormat), imageFormat); bitmap.Dispose(); } pdfFile.Dispose(); //第四步:返回PDF转换了多少张图片的个数 return(pageCount); } catch (System.Exception exception) { throw new System.Exception("PDF转换图片出现错误了,错误原因:" + exception.Message); } }
/// <summary> /// 将PDF文档转换为图片的方法 /// </summary> /// <param name="pdfInputPath">PDF文件路径</param> /// <param name="imageName">生成图片的名字</param> /// <param name="startPageNum">从PDF文档的第几页开始转换</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param> /// <param name="imageFormat">设置所需图片格式</param> /// <param name="definition">设置图片的清晰度,数字越大越清晰</param> public static Stream ConvertPDF2Image(Stream stream, string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition = Definition.Ten) { PDFFile pdfFile = PDFFile.Open(stream); // validate pageNum if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } var ms = new MemoryStream(); // start to convert each page for (int i = startPageNum; i <= endPageNum; i++) { Bitmap pageImage = pdfFile.GetPageImage(i - 1, 40 * (int)definition); pageImage.Save(ms, imageFormat); pageImage.Dispose(); } pdfFile.Dispose(); return(ms); }
/// <summary> /// 将PDF文档转换为图片的方法 /// </summary> /// <param name="pdfInputPath">PDF文件路径</param> /// <param name="imageOutputPath">图片输出路径</param> /// <param name="imageName">生成图片的名字</param> /// <param name="startPageNum">从PDF文档的第几页开始转换</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param> /// <param name="imageFormat">设置所需图片格式</param> /// <param name="definition">设置图片的清晰度,数字越大越清晰</param> public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath, string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition) { PDFFile pdfFile = PDFFile.Open(pdfInputPath); if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); } // validate pageNum if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } // start to convert each page for (int i = startPageNum; i <= endPageNum; i++) { Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition); pageImage.Save(imageOutputPath + imageName + i.ToString() + "." + imageFormat.ToString(), imageFormat); pageImage.Dispose(); } pdfFile.Dispose(); }
/// <summary> /// 将PDF文档转换为图片的方法 /// </summary> /// <param name="pdfInputPath">PDF文件路径</param> /// <param name="imageOutputPath">图片输出路径</param> /// <param name="imageName">生成图片的名字</param> /// <param name="startPageNum">从PDF文档的第几页开始转换</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param> /// <param name="imageFormat">设置所需图片格式</param> /// <param name="definition">设置图片的清晰度,数字越大越清晰</param> private void ConvertPDF2ImageO2S(string pdfInputPath) { // Is NULL if (pdfInputPath == null) { m_nConvertStatus = EErrorType.PTJ_FILENAME_EMPTY; } PDFFile pdfFile = PDFFile.Open(pdfInputPath); try { m_nTotalPage = pdfFile.PageCount; PrintLog("ConvertStatus:" + (int)ConvertStatus.START + " " + 0 + " " + m_nTotalPage); // start to convert each page for (int i = 0; i < m_nTotalPage; i++) { PrintLog("ConvertStatus:" + (int)ConvertStatus.ING + " " + (i + 1).ToString() + " " + m_nTotalPage); string strJPGName = m_strOutDir + "\\" + Path.GetFileNameWithoutExtension(pdfInputPath) + "_" + m_nTotalPage + "_" + (i + 1).ToString() + ".jpg"; Bitmap pageImage = pdfFile.GetPageImage(i, 56 * (int)m_dQuality); pageImage.Save(strJPGName, ImageFormat.Jpeg); pageImage.Dispose(); } } catch (Exception ex) { PrintLog(ex.Message.ToString()); m_nConvertStatus = EErrorType.PTJ_EXCEPTION_FAILED; } finally { pdfFile.Dispose(); } }
public static bool ToImage(string pdfInputPath, string imageOutputPath, string imageName, ImageFormat imageFormat) { PDFFile pdfFile = PDFFile.Open(pdfInputPath); Data.pageCount = pdfFile.PageCount; int startPageNum = 1; int endPageNum = Data.pageCount; Console.WriteLine(imageOutputPath); if (!Directory.Exists(Data.sourceImageDirpath)) { Directory.CreateDirectory(Data.sourceImageDirpath); } else { Directory.Delete(Data.sourceImageDirpath, true); Directory.CreateDirectory(Data.sourceImageDirpath); } // validate pageNum if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { startPageNum = endPageNum; endPageNum = startPageNum; } Data.OriginalImages = new List <Bitmap>(); // start to convert each page for (int i = startPageNum; i <= endPageNum; i++) { float pageWidth = (float)(pdfFile.GetPageSize(i - 1).Width / 72); //float pageHeight = (float)(pdfFile.GetPageSize(i - 1).Height / 72); float resolution = Data.panelWidth / pageWidth; //Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition); Bitmap pageImage = pdfFile.GetPageImage(i - 1, resolution); //if (!Directory.Exists(imageOutputPath)) // Directory.CreateDirectory(imageOutputPath + "\\images"); pageImage.Save(imageOutputPath + "\\" + imageName + i.ToString() + "." + imageFormat.ToString(), imageFormat); string imgPath = imageOutputPath + "\\" + imageName + i.ToString() + "." + imageFormat.ToString(); Data.OriginalImages.Add(new Bitmap(GetCopyImage(imgPath))); //File.Delete(imgPath); //Console.WriteLine($"page {i} converted, width:{Data.OriginalImages[i - 1].Width} height:{Data.OriginalImages[i - 1].Height}"); } pdfFile.Dispose(); //Data.OriginalImages.Clear(); //File.Delete(imageOutputPath + "\\" + imageName + "1." + imageFormat.ToString()); return(true); }
private int printShow(string url) { int isOK = 0; PDFFile file = PDFFile.Open(url); PrinterSettings settings = new PrinterSettings(); System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument(); settings.PrinterName = "\\\\192.168.2.93\\Brother DCP-7030 Printer"; settings.PrintToFile = false; //设置纸张大小(可以不设置,取默认设置)3.90 in, 8.65 in //PaperSize ps = new PaperSize("test", 4, 9); //ps.RawKind = 9; //如果是自定义纸张,就要大于118,(A4值为9,详细纸张类型与值的对照请看http://msdn.microsoft.com/zh-tw/library/system.drawing.printing.papersize.rawkind(v=vs.85).aspx) O2S.Components.PDFRender4NET.Printing.PDFPrintSettings pdfPrintSettings = new O2S.Components.PDFRender4NET.Printing.PDFPrintSettings(settings); //pdfPrintSettings.PaperSize = ps; pdfPrintSettings.PageScaling = O2S.Components.PDFRender4NET.Printing.PageScaling.FitToPrinterMarginsProportional; pdfPrintSettings.PrinterSettings.Copies = 1; try { file.Print(pdfPrintSettings); isOK = 1; } catch (Exception) { isOK = -1; throw; } finally { file.Dispose(); } return(isOK); }
//选择PDF预览文件 private void comboPDFlist_SelectionChangeCommitted(object sender, EventArgs e) { pdfInputPath = comboPDFlist.SelectedValue.ToString(); PDFFile pdfFile = PDFFile.Open(pdfInputPath); Bitmap pageImage = pdfFile.GetPageImage(0, 56 * 1); pictureBox1.Image = pageImage; imgStartPage = 1; imgPageCount = pdfFile.PageCount; pdfFile.Dispose(); labelPage.Text = imgStartPage + "/" + imgPageCount; float px, py; DataRow[] arrRow = dtPos.Select("Path = '" + pdfInputPath + "' and Page = " + imgStartPage); if (arrRow == null || arrRow.Length == 0) { px = Convert.ToSingle(textPx.Text); //这里根据比例来定位 py = Convert.ToSingle(textPy.Text); //这里根据比例来定位 } else { DataRow dr = arrRow[0]; px = Convert.ToSingle(dr["X"].ToString()); py = Convert.ToSingle(dr["Y"].ToString()); } int X = Convert.ToInt32(pictureBox1.Width * px); int Y = Convert.ToInt32(pictureBox1.Height * py); Point pt1 = pictureBox1.Location; pictureBox2.Location = new Point(pt1.X + X - 10, pt1.Y + Y - 10); }
public static int LeafletPdf2JPG(string pdfPath, string fileID, string taskID) { //Aspose.Pdf.Document pdf = new Aspose.Pdf.Document(pdfPath); curIndex = 1; int highHeightUnit = 0; string root = Path.Combine(OfficeHelper.GetFolderPath(taskID, "Office"), fileID); imgHeight = 0; listBitmaps = new Dictionary <string, Bitmap>(); if (!Directory.Exists(@root)) { Directory.CreateDirectory(@root); } /*O2S.Components.PDFRender4NET.dll方式*/ PDFFile pdfFile = PDFFile.Open(pdfPath); int pageCount = pdfFile.PageCount; List <Bitmap> listImage = new List <Bitmap>(); for (int i = 1; i <= pageCount; i++) { Bitmap bitmap = pdfFile.GetPageImage(i - 1, 56 * (int)Definition.Two); if (bitmap != null) { listImage.Add(bitmap); } } highHeightUnit = MergerImageAndCut(listImage, root, true); /*Aspose.Pdf方式,比较慢*/ //for (int pageCount = 1; pageCount <= pdf.Pages.Count; pageCount++) //{ // string fileName = root + "\\" + pageCount + ".jpg"; // using (FileStream imageStream = new FileStream(fileName, FileMode.Create)) // { // Aspose.Pdf.Devices.Resolution resolution = new Aspose.Pdf.Devices.Resolution(300); // Aspose.Pdf.Devices.PngDevice pngDevice = new Aspose.Pdf.Devices.PngDevice(resolution); // pngDevice.Process(pdf.Pages[pageCount], imageStream); // Image image = Image.FromStream(imageStream); // imageStream.Close(); // if (image != null) // ImgCutSave(image, root, pageCount); //代码截图 // } // if (File.Exists(fileName)) // File.Delete(fileName); //} foreach (KeyValuePair <string, Bitmap> bitmaps in listBitmaps) { Bitmap bitmap = bitmaps.Value; if (bitmap != null) { ImageFormat imageFormat = ImageFormat.Jpeg; bitmap.Save(bitmaps.Key, imageFormat); } } return(highHeightUnit); }
public PdfController(string pdfFileName, PictureConfig config) { this.pdfFileName = pdfFileName; this.picureConfig = config; tempPath = Application.streamingAssetsPath + "/ImageCache/" + Path.GetFileNameWithoutExtension(this.pdfFileName); Directory.CreateDirectory(tempPath); pdfFile = PDFFile.Open(this.pdfFileName); }
public string SilentPrint(string Url, string PostData, string cookieStr, string printerParams, string charset) { string fileName = null; try { Stream stream = HttpUtils.SendRequest(Url, PostData, charset, cookieStr); //创建临时目录 string temp = System.Environment.GetEnvironmentVariable("TEMP"); fileName = Guid.NewGuid().ToString(); fileName = temp + "\\" + fileName + ".pdf"; saveFile(stream, fileName); //读取PDF文件 if (PrintEngine.Equals("exe")) { string exePath = Assembly.GetExecutingAssembly().Location; string exeFile = new FileInfo(exePath).DirectoryName + "\\FR.exe"; // MessageBox.Show(exeFile); Process p = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = true; startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.UseShellExecute = true; startInfo.FileName = exeFile; //startInfo.Verb = "FR.exe"; string cmd = "/p \"" + fileName + "\" \"" + GetPrinter() + "\""; startInfo.Arguments = cmd; p.StartInfo = startInfo; p.Start(); p.WaitForExit(); } else { PDFFile pdf = PDFFile.Open(fileName); // Create a default printer settings to print on the default printer. PrinterSettings settings = new PrinterSettings(); PDFPrintSettings pdfPrintSettings = new PDFPrintSettings(settings); pdfPrintSettings.PageScaling = PageScaling.FitToPrinterMargins; pdf.Print(pdfPrintSettings); pdf.Dispose(); } } catch (Exception ex) { return("{status:'error',msg:'" + ex.Message + "'}"); } finally { try { if (fileName != null) { new FileInfo(fileName).Delete(); } } catch (Exception ee) { } } return("{status:'success'}"); }
public List <List <Bitmap> > ConvertPDF2ListImage(string pdfInputPath, string imageOutputPath, string imageName, int startPageNum, int endPageNum, System.Drawing.Imaging.ImageFormat imageFormat, Definition definition) { List <List <Bitmap> > xList = new List <List <Bitmap> >(); PDFFile pdfFile = PDFFile.Open(pdfInputPath); if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); } // validate pageNum if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } // start to convert each page for (int i = startPageNum; i <= endPageNum; i++) { Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition); var x = _提取表格类.ConvertImage2form(pageImage); //pageImage.Save(imageOutputPath + imageName + i.ToString() + "." + imageFormat.ToString(), imageFormat); xList.Add(x); pageImage.Dispose(); } pdfFile.Dispose(); return(xList); }
/// <summary> /// 生成缩略图,只生成第一张页面的缩略图 /// </summary> /// <param name="fileBuffer">文件的字节数组</param> /// <param name="fileType">文件类型,目前支持:Word、Excel、PDF</param> public static byte[] ConvertToSnap(byte[] fileBuffer, string fileType) { var snapStream = new MemoryStream(); if (fileType == "xls" || fileType == "xlsx") { var book = new Aspose.Cells.Workbook(new MemoryStream(fileBuffer)); var sheet = book.Worksheets[0]; var imgOptions = new Aspose.Cells.Rendering.ImageOrPrintOptions { OnePagePerSheet = true, VerticalResolution = 400, HorizontalResolution = 300, ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg }; var sr = new Aspose.Cells.Rendering.SheetRender(sheet, imgOptions); sr.ToImage(0, snapStream); } else if (fileType == "doc" || fileType == "docx") { var doc = new Aspose.Words.Document(new MemoryStream(fileBuffer)); var imgOptions = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Jpeg) { Resolution = 400, }; doc.Save(snapStream, imgOptions); } else if (fileType == "pdf") { //aspose有性能问题 //var converter = new Aspose.Pdf.Facades.PdfConverter(); //converter.BindPdf(new Aspose.Pdf.Document(new MemoryStream(fileBuffer))); //converter.DoConvert(); //converter.GetNextImage(snapStream, new Aspose.Pdf.PageSize(200, 150), System.Drawing.Imaging.ImageFormat.Jpeg,30); //换用ghostscript //GhostscriptRasterizer rasterizer = new GhostscriptRasterizer(); //rasterizer.Open(new MemoryStream(fileBuffer)); //Image page = rasterizer.GetPage(96, 96, 1); //page.Save(snapStream, ImageFormat.Jpeg); PDFFile pdfFile = PDFFile.Open(new MemoryStream(fileBuffer)); Bitmap bitmap = pdfFile.GetPageImage(0, 56 * (int)Definition.Two); bitmap.Save(snapStream, ImageFormat.Jpeg); } var result = snapStream.ToArray(); snapStream.Close(); return(result); }
/// <summary> /// Convers pdf to images. /// </summary> /// <param name="parm"></param> /// <exception cref="FileNotFoundException"></exception> public static List <string> ToImageList(this PdfParameter parm) { if (parm is null) { throw new ArgumentNullException(nameof(parm)); } var results = new List <string>(); var pdfFile = PDFFile.Open(parm.PdfPath.FullName); if (parm.StartPage <= 0) { parm.StartPage = 1; } if (parm.EndPage > pdfFile.PageCount) { parm.EndPage = pdfFile.PageCount; } if (parm.StartPage > parm.EndPage) { parm.StartPage = parm.EndPage; parm.EndPage = parm.StartPage; } for (var i = parm.StartPage; i <= parm.EndPage; i++) { var withNum = i.ToString().PadLeft(pdfFile.PageCount.ToString().Length, '0'); withNum = parm.StartPage == parm.EndPage ? null : "_" + withNum; var imgPage = pdfFile.GetPageImage(i - 1, 56 * parm.Resolution); var dirPath = parm.PdfPath.DirectoryName ?? throw new InvalidOperationException(); var filePath = Path.Combine(dirPath, parm.ImgName + withNum + "." + parm.Format.ToString().ToLower()); results.Add(filePath); imgPage.Save(filePath, parm.Format); imgPage.Dispose(); } pdfFile.Dispose(); return(results); }
/// <summary> /// 将PDF文档转换为图片的方法 /// </summary> /// <param name="pdfInputPath">PDF文件路径</param> /// <param name="imageOutputPath">图片输出路径</param> /// <param name="imageName">生成图片的名字</param> /// <param name="startPageNum">从PDF文档的第几页开始转换</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param> /// <param name="imageFormat">设置所需图片格式</param> /// <param name="definition">设置图片的清晰度,数字越大越清晰</param> public static int ConvertPDF2Image(string pdfInputPath, string imageOutputPath, string imageName, int?startPageNum, int?endPageNum, ImageFormat imageFormat, Definition definition = Definition.Five) { pdfInputPath = FileBasePath == null ? pdfInputPath : Path.Combine(FileBasePath, pdfInputPath); PDFFile pdfFile = PDFFile.Open(pdfInputPath); if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); } // validate pageNum if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum == null) { startPageNum = 1; } if (endPageNum == null) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { int tempPageNum = (int)startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } // start to convert each page for (int i = (int)startPageNum; i <= endPageNum; i++) { Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition); pageImage.Save(imageOutputPath + imageName + i.ToString() + "." + imageFormat.ToString(), imageFormat); pageImage.Dispose(); } int pagecount = pdfFile.PageCount; pdfFile.Dispose(); return(pagecount); }
private static bool convertPDFToImage(Log4netUtil.LogAppendToForms logAppendToForms, string pdfInputPath, string imageOutputPath, string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition, bool isDebug) { PDFFile pdfFile = PDFFile.Open(pdfInputPath); try { if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); } if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } for (int i = startPageNum; i <= endPageNum; i++) { Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition); string extension = imageFormat.ToString(); if (string.Equals(extension.ToLower(), "jpeg")) { extension = "jpg"; } pageImage.Save(imageOutputPath + imageName + "." + extension, imageFormat); //pageImage.Save(imageOutputPath + imageName + i.ToString() + "." + extension, imageFormat); pageImage.Dispose(); } return(true); } catch (Exception ex) { string logMessage = string.Format("【随货同行下载任务】 PdfInputPath {0} 转换图片失败!原因,{1}", pdfInputPath, ex.Message); Log4netUtil.Log4NetHelper.LogMessage(logAppendToForms, isDebug, logMessage, @"KJJ\DownloadDataBusiness"); return(false); } finally { pdfFile.Dispose(); } }
/*打印pdf*/ // <param name="url">要打印的PDF路径</param> private void printPDF(string url) { //打开pdf文件 PDFFile file = PDFFile.Open(url); PrinterSettings settings = new PrinterSettings(); System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument(); //设置打印机的名称 settings.PrinterName = "HP Officejet Pro X551dw Printer PCL 6 (网络)"; settings.PrintToFile = false; //设置打印的颜色为彩色 if (PrintColor.Equals("1")) { settings.DefaultPageSettings.Color = true; } else { settings.DefaultPageSettings.Color = false; } //设置打印的单双面 if (PrintType.Equals("0")) { settings.Duplex = Duplex.Simplex; } else { //双面 settings.Duplex = Duplex.Vertical; } //设置纸张大小(可以不设置取,取默认设置)3.90 in, 8.65 in // PaperSize ps = new PaperSize("Your Paper Name", config.Width, config.Height); // ps.RawKind = 150; //如果是自定义纸张,就要大于118,(A4值为9,详细纸张类型与值的对照请看http://msdn.microsoft.com/zh-tw/library/system.drawing.printing.papersize.rawkind(v=vs.85).aspx) O2S.Components.PDFRender4NET.Printing.PDFPrintSettings pdfPrintSettings = new O2S.Components.PDFRender4NET.Printing.PDFPrintSettings(settings); //设置打印纸张的大小 //pdfPrintSettings.PaperSize = ps; pdfPrintSettings.PageScaling = O2S.Components.PDFRender4NET.Printing.PageScaling.FitToPrinterMarginsProportional; //设置打印份数 pdfPrintSettings.PrinterSettings.Copies = 1; //打印pdf file.Print(pdfPrintSettings); //关闭文件 file.Dispose(); }
public bool OpenPdfFile(Stream stream) { //if (this.FileName == fileName) //{ // return true; //} CloseFile(); pdfFile = PDFFile.Open(stream); if (pdfFile == null) { return(false); } if (pdfFile.PageCount == 0) { pdfFile.Dispose(); pdfFile = null; return(false); } //this.FileName = fileName; double s = 96.0 / 72.0; for (int i = 0; i < pdfFile.PageCount; i++) { PDFSize size = pdfFile.GetPageSize(i); PdfPageInfo page = new PdfPageInfo(i, (int)(size.Width * s), (int)(size.Height * s)); this.Pages.Add(page); } double scale = (double)this.Height / (double)this.Width; double pdfScale = this.Pages[0].PdfHeight / this.Pages[0].PdfWidth; if (scale < pdfScale) { SetScale((double)this.Height / this.Pages[0].PdfHeight); } else { SetScale((double)this.Width / this.Pages[0].PdfWidth); } MoveToPage(0); return(true); }
/// <summary> /// 转换PDF为指定格式的图片 /// </summary> /// <param name="pdfInputStream"></param> /// <param name="imageFormat"></param> /// <param name="resolution">清晰度,分为10级(数字1-10)</param> /// <returns></returns> public static IList <Stream> ConvertPdfToImage(Stream inputStream, ImageFormat imageFormat, int resolution) { PDFFile pdfFile = PDFFile.Open(inputStream); IList <Stream> result = new List <Stream>(); for (int i = 0; i < pdfFile.PageCount; i++) { Bitmap pageImage = pdfFile.GetPageImage(i, 56 * (int)resolution); result.Add(ConvertBitmap.ToMemoryStream(pageImage, imageFormat)); } pdfFile.Dispose(); return(result); }
/// <summary> /// pdf转bitmap /// </summary> /// <param name="pdfPath">pdf文件路径</param> /// <param name="usedAllPage">全部转换</param> /// <param name="startPageNum">开始页数</param> /// <param name="endPageNum">结束页数</param> /// <param name="definition">转换质量(1~10)</param> /// <returns></returns> private List <Bitmap> PdfConvertBitmap(string pdfPath, bool usedAllPage, int startPageNum, int endPageNum, int definition) { List <Bitmap> bitmaps = new List <Bitmap>(); //打开pdf文件 PDFFile pdfFile = PDFFile.Open(pdfPath); //页数处理 if (usedAllPage) { startPageNum = 1; endPageNum = pdfFile.PageCount; } else { if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } } //转换质量处理 if (definition < 0) { definition = 1; } if (definition > 10) { definition = 10; } //转换图像 for (int i = startPageNum; i <= endPageNum; i++) { Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * definition); bitmaps.Add(pageImage); } pdfFile.Dispose(); return(bitmaps); }
private void ConvertPDF2Image(string pdfInputPath, string imageOutputPath, string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition) { PDFFile pdfFile = PDFFile.Open(pdfInputPath); if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); } for (int i = startPageNum; i <= endPageNum; i++) { Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition); pageImage.Save(imageOutputPath + imageName + "." + imageFormat.ToString(), imageFormat); pageImage.Dispose(); } pdfFile.Dispose(); }
/// <summary> /// 将PDF转换为图片的方法 /// </summary> /// <param name="pdfInputPath">PDF文件路径</param> /// <param name="imageOutputPath">图片输出路径</param> /// <param name="imageName">生成图片的名字</param> /// <param name="startPageNum">从PDF文档的第几页开始转换</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param> /// <param name="imageFormat">设置所需图片格式</param> /// <param name="definition">设置图片的清晰度,数字越大越清晰</param> public string[] PdfToPng(string pdfInputPath, string imageOutputPath, string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, int definition) { List <string> outFileList = new List <string>(); PDFFile pdfFile = PDFFile.Open(pdfInputPath); if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); } // validate pageNum if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } // start to convert each page if (endPageNum == 1) { Bitmap pageImage = pdfFile.GetPageImage(1 - 1, 56 * (int)definition); pageImage.Save(imageOutputPath + imageName + "." + imageFormat, imageFormat); pageImage.Dispose(); outFileList.Add(imageOutputPath + imageName + "." + imageFormat); } else { for (int i = startPageNum; i <= endPageNum; i++) { Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition); pageImage.Save(imageOutputPath + imageName + i + "." + imageFormat, imageFormat); pageImage.Dispose(); outFileList.Add(imageOutputPath + imageName + i + "." + imageFormat); } } pdfFile.Dispose(); return(outFileList.ToArray());; }
/// <summary> /// 将PDF文档转换为图片的方法 /// </summary> /// <param name="pdfInputPath">PDF文件路径</param> /// <param name="imageOutputPath">图片输出路径</param> /// <param name="imageName">生成图片的名字</param> /// <param name="startPageNum">从PDF文档的第几页开始转换</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param> /// <param name="imageFormat">设置所需图片格式</param> /// <param name="definition">设置图片的清晰度,数字越大越清晰</param> public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath, string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, int definition) //Definition definition) { PDFFile pdfFile = PDFFile.Open(pdfInputPath); if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); } // validate pageNum if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } // start to convert each page for (int i = startPageNum; i <= endPageNum; i++) { Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition); string savefile = imageOutputPath + "\\" + imageName + "_" + i.ToString().PadLeft(3, '0') + "." + imageFormat.ToString(); System.Console.WriteLine("savefile:" + savefile); if (!File.Exists(savefile)) { pageImage.Save(savefile, imageFormat); //pageImage.Save(imageOutputPath + imageName , imageFormat); } pageImage.Dispose(); } pdfFile.Dispose(); }
private bool pdf(String filename) { PDFFile file = PDFFile.Open(filename); try { file.Print(this.PrinterSettings()); } catch { return(false); } finally { file.Dispose(); } return(true); }
private async void Window_Loaded(object sender, RoutedEventArgs e) { TbInfo.Text = GetTbInfoText(Dir_SourcePdf, "正在处理"); FileInfo fileInfo = new FileInfo(Dir_SourcePdf); PdfSize = fileInfo.Length; Dir_WorkPlace = App.Dir_File_PDF + $"{fileInfo.Name.Substring(0, fileInfo.Name.Length - 4)}-{PdfSize}/"; Directory.CreateDirectory(Dir_WorkPlace); if (!File.Exists(Dir_WorkPlace + "pdf.jpg")) { await Task.Run(() => { var pdf = PDFFile.Open(Dir_SourcePdf); //List<Bitmap> pics = new List<Bitmap>(); string dir_temp = Dir_WorkPlace + "temp/"; Directory.CreateDirectory(dir_temp); for (int i = 0; i < pdf.PageCount; i++) { TbInfo.Dispatcher.Invoke(() => { TbInfo.Text = GetTbInfoText(Dir_SourcePdf, $"{i + 1}/{pdf.PageCount}"); }); var p = pdf.GetPageImage(i, App.WdSetting.Sharpness); //Console.WriteLine(App.WdSetting.Sharpness); //pics.Add(p); p.Save($@"{dir_temp}{i}.jpg"); p.Dispose(); } //TbInfo.Dispatcher.Invoke(() => { TbInfo.Text = GetTbInfoText(Dir_SourcePdf, "正在合成图片,即将完成", false); }); // var p1 = ImageHelper.CombineImages(pics); var p1 = new Bitmap(1, 1); using (FileStream stream = File.Create($@"{Dir_WorkPlace}pdf.jpg")) { p1.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp); }//使用流进行保存,防止大小宽度超过65536导致报错 p1.Dispose(); // pics.ForEach(item => item.Dispose()); }); } BtnEdit.IsEnabled = true; BtnEdit.Content = "开始编辑"; TbInfo.Text = GetTbInfoText(Dir_SourcePdf, "预处理完成"); }
/// <summary> /// 将PDF文档转换为图片的方法 /// </summary> /// <param name="pdfInputPath">PDF文件路径</param> /// <param name="imageOutputPath">图片输出路径</param> /// <param name="imageName">生成图片的名字</param> /// <param name="startPageNum">从PDF文档的第几页开始转换</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param> /// <param name="imageFormat">设置所需图片格式</param> /// <param name="definition">设置图片的清晰度,数字越大越清晰</param> public static void ConvertPdf2Image(string pdfInputPath, string imageOutputPath, string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition) { if (File.Exists(pdfInputPath)) { PDFFile pdfFile = PDFFile.Open(pdfInputPath); if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); } if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { startPageNum = endPageNum; endPageNum = startPageNum; } for (int i = startPageNum; i <= endPageNum; i++) { Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition); int canKao = pageImage.Width > pageImage.Height ? pageImage.Height : pageImage.Width; int newHeight = canKao > 1080 ? pageImage.Height / 2 : pageImage.Height; int newWidth = canKao > 1080 ? pageImage.Width / 2 : pageImage.Width; Bitmap newPageImage = new Bitmap(newWidth, newHeight); Graphics g = Graphics.FromImage(newPageImage); g.InterpolationMode = InterpolationMode.Default; g.DrawImage(pageImage, new Rectangle(0, 0, newWidth, newHeight), new Rectangle(0, 0, pageImage.Width, pageImage.Height), GraphicsUnit.Pixel); newPageImage.Save(imageOutputPath + imageName + "." + imageFormat, imageFormat); g.Dispose(); newPageImage.Dispose(); pageImage.Dispose(); } pdfFile.Dispose(); } }
public int ConvertPDF2Image(string pdfInputPath, string imageOutputPath, string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition) { PDFFile pdfFile = PDFFile.Open(pdfInputPath); int fileCount = pdfFile.PageCount; if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); } // validate pageNum if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } // start to convert each page for (int i = startPageNum; i <= pdfFile.PageCount; i++) { Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition); Bitmap pageImageNew = ZoomAuto(pageImage, 1280, 1024);//KiResizeImage(pageImage, 1280, 1024); pageImageNew.Save(imageOutputPath + "\\" + imageName + i.ToString() + "." + imageFormat.ToString(), imageFormat); pageImageNew.Dispose(); } pdfFile.Dispose(); return(fileCount); }
/// <summary> /// 将PDF文档转换为图片的方法 /// </summary> /// <param name="pdfInputPath">PDF文件路径</param> /// <param name="imageOutputPath">图片输出路径</param> /// <param name="imageName">生成图片的名字</param> /// <param name="startPageNum">从PDF文档的第几页开始转换</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param> /// <param name="imageFormat">设置所需图片格式</param> /// <param name="definition">设置图片的清晰度,数字越大越清晰</param> public DataTable ConvertPDF2Image(string pdfInputPath, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition) { // pdfInputPath = "\\\\192.168.23.75\\web\\TEMPPDF\\1.pdf"; PDFFile pdfFile = PDFFile.Open(pdfInputPath); DataTable dtImage = new DataTable("ImageData"); dtImage.Columns.Add("PageCount", typeof(System.Int32)); DataColumn ImagePrint = new DataColumn("ImagePrint", typeof(Image)); dtImage.Columns.Add(ImagePrint); if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } for (int i = startPageNum; i <= endPageNum; i++) { Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition); MemoryStream ms = new MemoryStream(); pageImage.Save(ms, imageFormat); Image datatableImage = Image.FromStream(ms); DataRow newRow = dtImage.NewRow(); newRow["PageCount"] = i; newRow["ImagePrint"] = datatableImage; dtImage.Rows.Add(newRow); pageImage.Dispose(); } pdfFile.Dispose(); return(dtImage); }
void PrintPDF(string pdfPath, int copies) { PDFFile file = PDFFile.Open(pdfPath); PrinterSettings setting = new PrinterSettings(); PrintDocument pd = new PrintDocument(); setting.PrinterName = "FUJI XEROX DocuCentre S2110"; setting.Duplex = Duplex.Vertical; setting.PrintToFile = false; setting.Copies = (short)copies; setting.Collate = true; PDFPrintSettings pdfps = new PDFPrintSettings(setting); try { file.Print(pdfps); } finally { file.Dispose(); } }
/// <summary> /// Convers pdf to images. /// </summary> /// <param name="param"></param> /// <exception cref="FileNotFoundException"></exception> public static List <string> ToImages(this PdfParam param) { var results = new List <string>(); var pdfFile = PDFFile.Open(param.PdfPath.FullName); if (param.StartPage <= 0) { param.StartPage = 1; } if (param.EndPage > pdfFile.PageCount) { param.EndPage = pdfFile.PageCount; } if (param.StartPage > param.EndPage) { param.StartPage = param.EndPage; param.EndPage = param.StartPage; } for (var i = param.StartPage; i <= param.EndPage; i++) { var withNum = i.ToString().PadLeft(pdfFile.PageCount.ToString().Length, '0'); withNum = param.StartPage == param.EndPage ? null : "_" + withNum; var imgPage = pdfFile.GetPageImage(i - 1, 56 * param.Resolution); var filePath = Path.Combine(param.PdfPath.DirectoryName, param.ImgName + withNum + "." + param.Format.ToString().ToLower()); results.Add(filePath); imgPage.Save(filePath, param.Format); imgPage.Dispose(); } pdfFile.Dispose(); return(results); }
///// <summary> ///// 将字符串发送到打印机方法 ///// </summary> ///// <param name="szPrinterName">打印机名称</param> ///// <param name="szString">打印的字符串</param> ///// <returns></returns> //public static bool SendStringToPrinter(string szPrinterName, string szString) //{ // bool flag = false; // try // { // IntPtr pBytes; // Int32 dwCount; // // 获取字符串长度 // dwCount = szString.Length; // // 将字符串复制到非托管 COM 任务分配的内存非托管内存块,并转换为 ANSI 文本 // pBytes = Marshal.StringToCoTaskMemAnsi(szString); // // 将已转换的 ANSI 字符串发送到打印机 // flag = SendBytesToPrinter(szPrinterName, pBytes, dwCount); // // 释放先前分配的非托管内存 // Marshal.FreeCoTaskMem(pBytes); // } // catch (Win32Exception ex) // { // Helper.WriteLog(ex.Message); // flag = false; // } // return flag; //} /// <summary> /// PDFRender4Net打印pdf /// </summary> /// <param name="filePath">pdf文件路径</param> /// <param name="printerName">打印机名称</param> /// <param name="paper">纸张大小</param> /// <param name="isVertical">是否竖打</param> /// <param name="copies">份数</param> public static string UsePDFRender4NetToPrintPdf(string filePath, string printerName, PaperSize paper, bool isVertical, int copies) { string errorStr = ""; if (!File.Exists(filePath)) { errorStr += "打印的文件不存在\r\n"; return(errorStr); } PDFFile file = PDFFile.Open(filePath); PrinterSettings settings = new PrinterSettings(); settings.PrinterName = printerName; settings.PrintToFile = false; settings.DefaultPageSettings.Landscape = !isVertical; PDFPrintSettings pdfPrintSettings = new PDFPrintSettings(settings); pdfPrintSettings.PaperSize = paper; pdfPrintSettings.PageScaling = PageScaling.FitToPrinterMarginsProportional; pdfPrintSettings.PrinterSettings.Copies = (short)copies; try { file.Print(pdfPrintSettings); } catch (Exception ex) { errorStr = ex.Message; Helper.WriteLog(ex.Message); } finally { file.Dispose(); } return(errorStr); }