public Image Rasterize(string pdfUri, int pageNumber = 1) { _rasterizer.Open(pdfUri, _lastInstalledVersion, true); var img = _rasterizer.GetPage(_desiredXDpi, _desiredYDpi, pageNumber); _rasterizer.Close(); return(img); }
/// <summary> /// 將Pdf檔匯出成圖檔 /// </summary> /// <param name="outPdfImagePath"></param> /// <param name="file"></param> /// <param name="outImageFileName"></param> /// <param name="outPdfTempImagePath"></param> private static void PdfToImage(string outPdfTempImagePath, string outPdfImagePath, string file, out string outImageFileName) { var tempFiles = new List <string>(); using (var rasterizer = new GhostscriptRasterizer()) { rasterizer.Open(file, GhostScriptVersion, false); for (var i = 1; i <= rasterizer.PageCount; i++) { var fileName = Path.Combine(outPdfTempImagePath, GetUniqueFileName(".png", outPdfTempImagePath)); tempFiles.Add(fileName); var img = rasterizer.GetPage(DesiredXDpi, DesiredYDpi, i); if (i == 1) { img.Save(fileName, ImageFormat.Png); } else { img.RotateFlip(RotateFlipType.Rotate90FlipNone); img.Save(fileName, ImageFormat.Png); } } rasterizer.Close(); } outImageFileName = GetUniqueFileName(".png", outPdfImagePath); MergeImages(tempFiles).Save(Path.Combine(outPdfImagePath, outImageFileName)); }
static string PDFToImage(MemoryStream inputMS, int dpi) { string base64String = ""; GhostscriptRasterizer rasterizer = new GhostscriptRasterizer(); GhostscriptVersionInfo version = new GhostscriptVersionInfo( new Version(0, 0, 0), @"C:\Program Files\gs\gs9.20\bin\gsdll64.dll", string.Empty, GhostscriptLicense.GPL ); try { rasterizer.Open(inputMS, version, false); for (int i = 1; i <= rasterizer.PageCount; i++) { MemoryStream ms = new MemoryStream(); Image img = rasterizer.GetPage(dpi, dpi, 1); img.Save(ms, ImageFormat.Jpeg); ms.Close(); base64String = Convert.ToBase64String((byte[])ms.ToArray()); } rasterizer.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } return(base64String); }
public List <string> ConvertPdfJpg() { Guid guid = Guid.NewGuid(); string oldFileName = tbFileName.Text; string newFileName = tmpPath + "tmp_watermake_" + guid + ".pdf"; File.Copy(oldFileName, newFileName); string outFileName = Path.GetFileName(newFileName); List <string> outFiles = new List <string>(); GhostscriptVersionInfo gvi = new GhostscriptVersionInfo(localGhostscriptDll); using (GhostscriptRasterizer rasterizer = new GhostscriptRasterizer()) { /*rasterizer.CustomSwitches.Add("-r200x300"); * rasterizer.CustomSwitches.Add("-dAutoRotatePages =/ None");*/ rasterizer.Open(newFileName, gvi, false); for (int pageNumber = 1; pageNumber <= rasterizer.PageCount; pageNumber++) { string outNameFile = tmpPath + outFileName.Replace(".pdf", "") + "_" + pageNumber.ToString() + ".jpeg"; outFiles.Add(outNameFile); Image img = rasterizer.GetPage(300, 300, pageNumber); img.Save(outNameFile, ImageFormat.Jpeg); } rasterizer.Close(); } return(outFiles); }
private static void ConvertPdfToImage(ConvertPdfOptions options) { string dll = GetGhostScriptDllPath(); GhostscriptVersionInfo version = new GhostscriptVersionInfo(new System.Version(0, 0, 0), dll, string.Empty, GhostscriptLicense.GPL); using (GhostscriptRasterizer gs = new GhostscriptRasterizer()) { gs.Open(options.inputFile, version, false); if (gs.PageCount > 0) { int dpi = options.quality * 3; using (Image image = gs.GetPage(dpi, dpi, options.pageNumber)) { int imageWidth = image.Width; if (options.maxWidth > 0 && options.maxWidth < imageWidth) { double ratio = (double)options.maxWidth / imageWidth; int maxHeight = Convert.ToInt32(Math.Round(ratio * image.Height)); using (Image thumb = ResizeImage(image, options.maxWidth, maxHeight)) { SaveImage(thumb, options.outputFile); } } else { SaveImage(image, options.outputFile); } } } gs.Close(); } }
//Methode FONCTIONNELLE de conversion de pdf en images public static List <System.Drawing.Image> exportPdfToImages(string file) { string path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); List <System.Drawing.Image> output = new List <System.Drawing.Image>(); System.Drawing.Image img; GhostscriptRasterizer rasterizer = null; GhostscriptVersionInfo vesion = new GhostscriptVersionInfo(new Version(0, 0, 0), path + @"\gsdll32.dll", string.Empty, Ghostscript.NET.GhostscriptLicense.GPL); using (rasterizer = new GhostscriptRasterizer()) { rasterizer.Open(file, vesion, false); for (int i = 1; i <= rasterizer.PageCount; i++) { img = rasterizer.GetPage(200, 200, i); Bitmap b = new Bitmap(img, new System.Drawing.Size(1654, 2339)); output.Add(b); } rasterizer.Close(); } return(output); }
/// <summary> /// Convert a bdf to an array bytes in order to save a picture /// </summary> /// <param name="upload"></param> /// <returns></returns> public static byte[] ConvertPdfToPngBytes(FileUpload upload) { byte[] fileBytes = null; try { int desired_x_dpi = 96; int desired_y_dpi = 96; var _lastInstalledVersion = GhostscriptVersionInfo.GetLastInstalledVersion(GhostscriptLicense.GPL | GhostscriptLicense.AFPL, GhostscriptLicense.GPL); var _rasterizer = new GhostscriptRasterizer(); _rasterizer.Open(upload.File.InputStream, _lastInstalledVersion, true); List <Image> images = new List <Image>(); int maxWidth = 0; int totalHeight = 0; int pageCount = _rasterizer.PageCount > 1 ? 2 : 1; for (int pageNumber = 1; pageNumber <= pageCount; pageNumber++) { Image img = _rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber); maxWidth = maxWidth > img.Width ? maxWidth : img.Width; totalHeight = totalHeight + img.Height + 1; images.Add(img); } _rasterizer.Close(); Bitmap finalImage = new Bitmap(maxWidth, totalHeight, PixelFormat.Format32bppArgb); using (Graphics graphics = Graphics.FromImage(finalImage)) { int startPoint = 0; foreach (Image img in images) { graphics.DrawImage(img, new Rectangle(new Point(0, startPoint), img.Size), new Rectangle(new Point(), img.Size), GraphicsUnit.Pixel); startPoint = startPoint + img.Height + 1; img.Dispose(); } } var imgStream = new MemoryStream(); finalImage.Save(imgStream, ImageFormat.Png); upload.ThumbBytes = GetThumbnailBytes(imgStream, 190); using (var ms = new MemoryStream()) { imgStream.Position = 0; imgStream.CopyTo(ms); fileBytes = ms.ToArray(); } imgStream.Dispose(); finalImage.Dispose(); } catch (Exception e) { Commons.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "UrlPath = " + upload.UploadName); } return(fileBytes); }
private string CreatePicturesFromPdf(string filePath) { List <Image> images = new List <Image>(); GhostscriptVersionInfo gvi = null; GhostscriptRasterizer _rasterizer = null; var finalPath = Common.ModifyPath(filePath, "png"); if (Environment.Is64BitProcess) { gvi = new GhostscriptVersionInfo(Path.GetFullPath(@".\..\..\..\OCR_BusinessLayer\lib\gsdll64.dll")); } else { gvi = new GhostscriptVersionInfo(Path.GetFullPath(@".\..\..\..\OCR_BusinessLayer\lib\gsdll32.dll")); } try { int desired_x_dpi = 200; int desired_y_dpi = 200; _rasterizer = new GhostscriptRasterizer(); _rasterizer.Open(filePath, gvi, true); for (int pageNumber = 1; pageNumber <= _rasterizer.PageCount; pageNumber++) { Image img = _rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber); images.Add(img); } _rasterizer.Close(); MergeImages(images, finalPath); } catch (Exception ex) { finalPath = string.Empty; if (_rasterizer != null) { _rasterizer.Close(); } throw new Exception("Failed to initialize GhostScript!", ex.InnerException); } return(finalPath); }
public static Image Render(Stream pdfStream, int dpixy, int page = 1) { var rastelizer = new GhostscriptRasterizer(); rastelizer.Open(pdfStream); var result = rastelizer.GetPage(dpixy, dpixy, page); rastelizer.Close(); return(result); }
public IEnumerable <Image> Rasterize(string pdfUri) { _rasterizer.Open(pdfUri, _lastInstalledVersion, false); for (var i = 1; i <= _rasterizer.PageCount; i++) { yield return(_rasterizer.GetPage(_desiredXDpi, _desiredYDpi, i)); } _rasterizer.Close(); }
/// <summary> /// Converts PDF to Images and compresses them into a ZIP file /// </summary> /// <param name="formFile"></param> /// <param name="imageFormat"></param> /// <returns>Array of bytes of ZIP file</returns> public async Task <byte[]> PDFToImages(IFormFile formFile, string imageFormat) { _logger.LogInformation("PdfToImages started"); // Gets DLL of GhostScritp string binPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string gsDllPath = Path.Combine(binPath, Environment.Is64BitProcess ? "gsdll64.dll" : "gsdll32.dll"); // Set DPI (User will eventually chose) int xDPI = 300; int yDPI = 300; // Get Image format ImageFormat imageFormatExtension = GetImageFormat(imageFormat); if (imageFormatExtension == null) { _logger.LogInformation("Image format not supported"); return(null); } // PDF to desired image(s) GhostscriptVersionInfo gsVersion = new GhostscriptVersionInfo(gsDllPath); GhostscriptRasterizer rasterizer = new GhostscriptRasterizer(); // Get stream of file MemoryStream memoryStream = new MemoryStream(); await formFile.CopyToAsync(memoryStream); rasterizer.Open(memoryStream, gsVersion, false); // Converts PDF pages into images and compresses them into a ZIP file var archiveStream = new MemoryStream(); var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create, true); for (var i = 1; i <= rasterizer.PageCount; i++) { MemoryStream imageStream = new MemoryStream(); Image img = rasterizer.GetPage(xDPI, yDPI, i); img.Save(imageStream, imageFormatExtension); var zipArchiveEntry = archive.CreateEntry($"Page-{i}.{imageFormatExtension.ToString().ToLower()}", CompressionLevel.Optimal); var zipStream = zipArchiveEntry.Open(); var imageBytes = imageStream.ToArray(); await zipStream.WriteAsync(imageBytes, 0, imageBytes.Length); zipStream.Close(); } // Closes GhostScript Rasterizer and closes Stream for archive _logger.LogInformation("PdfToImage - Zip file created"); rasterizer.Close(); archive.Dispose(); return(archiveStream.ToArray()); }
public void panel1_DragDrop(object sender, DragEventArgs e) { try { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); foreach (string filePath in files) { textBoxAdresPliku.Text = filePath; var localGhostscriptDll = Path.Combine(Environment.CurrentDirectory, "gsdll32.dll"); var localDllInfo = new GhostscriptVersionInfo(localGhostscriptDll); int desired_x_dpi = (int)numericUpDownOsX.Value; int desired_y_dpi = (int)numericUpDownOsY.Value; string inputPdfPath = filePath; string outputPath = Environment.CurrentDirectory; GhostscriptRasterizer _rasterizer = new GhostscriptRasterizer(); _rasterizer.Open(inputPdfPath, localDllInfo, false); string nazwa = Cos(filePath).nazwa; string folder = Cos(filePath).folder + nazwa + "\\"; textBoxFolderOut.Text = folder; ImageFormat formatObrazka = imageFormat(); for (int pageNumber = 1; pageNumber <= _rasterizer.PageCount; pageNumber++) { string pageFilePath = Path.Combine(folder.Remove(folder.Length - 4), nazwa + pageNumber.ToString() + zwrocFormatPliku); Image img = _rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber); if (Directory.Exists(folder)) { img.Save(pageFilePath, formatObrazka); } else { Directory.CreateDirectory(folder.Remove(folder.Length - 4)); img.Save(pageFilePath, formatObrazka); } } _rasterizer.Close(); } } }catch (Exception ex) { MessageBox.Show(ex.Message + ex.Source + ex.InnerException + ex.StackTrace); } }
public System.Drawing.Bitmap GetThumbnail(Stream input, int pageNumber) { try { _rasterizer.Open(input, _versionInfo, true); return(new System.Drawing.Bitmap(_rasterizer.GetPage(200, 200, pageNumber))); } finally { _rasterizer.Close(); } }
public void Convert(string sourceFilename, string destinationFilename) { Trace.TraceInformation("Creating Thumb from PDF for {0}.", sourceFilename); int desired_x_dpi = 96; int desired_y_dpi = 96; _rasterizer.Open(sourceFilename, _lastInstalledVersion, false); if (_rasterizer.PageCount > 0) { Image page = _rasterizer.GetPage(desired_x_dpi, desired_y_dpi, 1); page.Save(destinationFilename, ImageFormat.Jpeg); } _rasterizer.Close(); Trace.TraceInformation("Creating Thumb from PDF for {0} complete.", sourceFilename); }
/// <summary> /// Get an image from a PDF page. /// </summary> /// <param name="pdfPath"></param> /// <param name="pageNumber"></param> /// <returns>The path of the generated image.</returns> private static string GetImageFromPdf(string pdfPath, int pageNumber) { var outputFilePath = GetTempFile(".png"); var ghostscriptRasterizer = new GhostscriptRasterizer(); ghostscriptRasterizer.Open(pdfPath); using (var img = ghostscriptRasterizer.GetPage(pdfToImageDPI, pdfToImageDPI, pageNumber)) { img.Save(outputFilePath, System.Drawing.Imaging.ImageFormat.Png); img.Dispose(); } ghostscriptRasterizer.Close(); return(outputFilePath); }
/// <summary> /// Converts a pdf document in separated .png images /// </summary> /// <param name="file">File to be saved as png Image</param> /// <param name="outputPath">Output path</param> /// <param name="gsdllPath">Path to ghostscript dll</param> /// <param name="page">Page to be rendered, if no page submitted, generates all</param> /// <param name="dpi">Quality of output image, default 100dpi</param> public static void SaveImage(string file, string outputPath, string gsdllPath, int?page = null, int dpi = 100) { //Checks if output exists if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } using (var rasterizer = new GhostscriptRasterizer()) { //Selects the version of dll var dll = Environment.Is64BitProcess ? "gsdll64.dll" : "gsdll32.dll"; var versionInfo = new GhostscriptVersionInfo(new Version(0, 0, 0), gsdllPath + dll, string.Empty, GhostscriptLicense.GPL); rasterizer.Open(file, versionInfo, false); //If no page submitted var pages = page ?? rasterizer.PageCount; var guid = $"{Guid.NewGuid():N}"; for (var i = 1; i <= pages; i++) { //Sets file number in output image var number = page == null ? "_p" + i : string.Empty; //Constructs output image name var pageFilePath = Path.Combine(outputPath, $"thumbnail_{Path.GetFileNameWithoutExtension(file)}{number}_{guid}.png"); //Checks if file already exists if (File.Exists(pageFilePath)) { File.Delete(pageFilePath); } //Save the image in .png format var img = rasterizer.GetPage(dpi, dpi, i); img.Save(pageFilePath, ImageFormat.Png); } rasterizer.Close(); } }
/// HasColor #region HasColor /// <summary> /// Determines if the specified file has color /// </summary> /// <param name="fileName">file to be inspected</param> /// <returns>true if has color; otherwise false</returns> public static bool HasColor(string fileName, int desired_x_dpi = 96, int desired_y_dpi = 96) { LogHelper.LogDebug(fileName); try { GhostscriptVersionInfo gsVersion = new GhostscriptVersionInfo(GetLib()); using (GhostscriptRasterizer rasterizer = new GhostscriptRasterizer()) { rasterizer.Open(fileName, gsVersion, false); for (int pageNumber = 1; pageNumber <= rasterizer.PageCount; pageNumber++) { try { using (Image img = rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber)) { if (img.HasColor()) { LogHelper.LogDebug("Has Color"); return(true); } } } catch (Exception ex) { LogHelper.LogDebug(ex); } } rasterizer.Close(); } } catch (Exception ex) { WPFNotifier.DebugError(ex); } LogHelper.LogDebug("No Color"); return(false); }
public string[] Generate(string pdfFile, int dpi = 100, bool multi = false) { string binPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string gsDllPath = Path.Combine(binPath, "gsdll32.dll"); dll = new Ghostscript.NET.GhostscriptVersionInfo(new Version(9, 2, 2), gsDllPath, string.Empty, Ghostscript.NET.GhostscriptLicense.GPL); using (FileStream stream = new FileStream(pdfFile, FileMode.Open, FileAccess.Read)) { _rasterizer = new GhostscriptRasterizer(); _rasterizer.Open(stream, dll, false); if (multi) { pageCount = _rasterizer.PageCount; } else { pageCount = 1; } string[] tmpPathArr = new string[pageCount]; for (int pageNumber = 1; pageNumber <= pageCount; pageNumber++) { string tmpPath = Path.GetTempFileName(); Image img = _rasterizer.GetPage(dpi, dpi, pageNumber); img.Save(tmpPath, ImageFormat.Png); tmpPathArr[pageNumber - 1] = tmpPath; } _rasterizer.Close(); return(tmpPathArr); } }
public void Close() { _ghostscriptRasterizer.Close(); }
public async Task <IActionResult> Upload(IList <IFormFile> files) { try { if (files.Any(f => !Path.GetExtension(f.FileName).Equals(".pdf"))) { return(Redirect("~/Home")); } if (files.Any(f => f.Length > 31457280)) { return(Redirect("~/Home")); } FileDownloadModel fdm = new FileDownloadModel(); fdm.Files = new List <FileModel>(); long size = files.Sum(f => f.Length); long totalReadBytes = 0; string firstFolderId = Guid.NewGuid().ToString(); string directoryPath = $"{this.HostingEnvironment.WebRootPath}/download/{firstFolderId}"; var filePath = Path.GetTempFileName(); filePath = filePath.Replace(".tmp", ".pdf"); foreach (var formFile in files) { var type = Path.GetExtension(formFile.FileName); if (formFile.Length > 0) { byte[] buffer = new byte[16 * 1024]; using (var stream = new FileStream(filePath, FileMode.Create)) { using (Stream input = formFile.OpenReadStream()) { int readBytes; while ((readBytes = input.Read(buffer, 0, buffer.Length)) > 0) { await stream.WriteAsync(buffer, 0, readBytes); } } await formFile.CopyToAsync(stream); } directoryPath = string.Concat(directoryPath, "/" + formFile.FileName); Directory.CreateDirectory(directoryPath); using (var rasterizer = new GhostscriptRasterizer()) { rasterizer.Open(filePath); for (int i = 1; i <= rasterizer.PageCount; i++) { var page = rasterizer.GetPage(120, 120, i); var savePath = $"{directoryPath}/{formFile.FileName}_{i}.jpg"; page.Save(savePath); } rasterizer.Close(); } string zipPath = $"{this.HostingEnvironment.WebRootPath}/download/{firstFolderId}/{formFile.FileName}.zip"; ZipFile.CreateFromDirectory(directoryPath, zipPath); FileModel fileModel = new FileModel { FileName = formFile.FileName, FilePath = zipPath }; fdm.Files.Add(fileModel); } directoryPath = $"{this.HostingEnvironment.WebRootPath}/download/{firstFolderId}"; } fdm.DownloadAllId = firstFolderId; if (files.Count > 1) { string allZipPath = $"{this.HostingEnvironment.WebRootPath}/download/{firstFolderId}/pdftojpg.zip"; var allToZip = Directory.GetFiles(directoryPath); using (ZipArchive newFile = ZipFile.Open(allZipPath, ZipArchiveMode.Create)) { foreach (string file in allToZip) { newFile.CreateEntryFromFile(file, System.IO.Path.GetFileName(file)); } } } return(View(fdm)); } catch (Exception ex) { log.Error(ex.Message, ex); return(Redirect("~/Home")); } }
public ActionResult CortarImagenPdf() { string folderPath = @"D:/PdfToImages/" + (DateTime.Now.ToString()).Replace(":", "-"); Directory.CreateDirectory(folderPath); string zipPath = folderPath + "/" + "PdfToImages.zip"; try { var file = Request.Files[0]; if (file.ContentType == "application/pdf") { var constructorInfo = typeof(HttpPostedFile).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0]; var obj = (HttpPostedFile)constructorInfo .Invoke(new object[] { file.FileName, file.ContentType, file.InputStream }); HttpPostedFile filePosted = obj; string filePath = ""; if (filePosted != null && filePosted.ContentLength > 0) { string fileNameApplication = System.IO.Path.GetFileName(filePosted.FileName); string fileExtensionApplication = System.IO.Path.GetExtension(fileNameApplication); // generating a random guid for a new file at server for the uploaded file string newFile = fileNameApplication; // getting a valid server path to save filePath = System.IO.Path.Combine(folderPath, newFile); if (fileNameApplication != String.Empty) { filePosted.SaveAs(filePath); } } var xDpi = 192; //set the x DPI var yDpi = 192; //set the y DPI using (var rasterizer = new GhostscriptRasterizer()) //create an instance for GhostscriptRasterizer { rasterizer.Open(filePath); //opens the PDF file for rasterizing int frameNum = rasterizer.PageCount; //set the output image(png's) complete path var outputPNGPath = Path.Combine(filePath, string.Format("{0}.png", folderPath)); //converts the PDF pages to png's for (int i = 1; i < frameNum + 1; i++) { var pdf2PNG = rasterizer.GetPage(xDpi, yDpi, i); //save the png's pdf2PNG.Save(folderPath + "\\" + Convert.ToString(i) + ".jpg", ImageFormat.Jpeg); //pdf2PNG.Save("C:/PdfToImages", ImageFormat.Png); } rasterizer.Close(); using (ZipFile zip = new ZipFile()) { zip.AddDirectory(folderPath); zip.Save(zipPath); } Byte[] bytes = System.IO.File.ReadAllBytes(zipPath); Directory.Delete(folderPath, true); //return RedirectToAction("Index"); return(File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.FileName + ".zip")); } } else { Directory.Delete(folderPath, true); return(RedirectToAction("Index")); } } catch (Exception ex) { Directory.Delete(folderPath, true); return(RedirectToAction("Index")); } }