/// <summary> /// Convert PDF to PNG format. /// </summary> /// <param name="inputPdfFile"></param> /// <returns>an array of PNG images</returns> public static string[] ConvertPdf2Png(string inputPdfFile) { PDFConvert converter = new PDFConvert(); converter.GraphicsAlphaBit = 4; converter.TextAlphaBit = 4; converter.ResolutionX = 300; // -r300 converter.OutputFormat = "pnggray"; // -sDEVICE converter.ThrowOnlyException = true; // rethrow exceptions string sOutputFile = string.Format("{0}\\workingimage%03d.png", Path.GetDirectoryName(inputPdfFile)); bool success = converter.Convert(inputPdfFile, sOutputFile); if (success) { // find working files string[] workingFiles = Directory.GetFiles(Path.GetDirectoryName(inputPdfFile), "workingimage???.png"); Array.Sort(workingFiles); return(workingFiles); } else { return(new string[0]); } }
/// <summary> /// Convert PDF to PNG format. /// </summary> /// <param name="inputPdfFile"></param> /// <returns>an array of PNG images</returns> public static void SplitPdf(string inputPdfFile, string outputPdfFile, string firstPage, string lastPage) { PDFConvert converter = new PDFConvert(); converter.OutputFormat = "pdfwrite"; // -sDEVICE converter.ThrowOnlyException = true; // rethrow exceptions //gs -sDEVICE=pdfwrite -dNOPAUSE -dQUIET -dBATCH -dFirstPage=m -dLastPage=n -sOutputFile=out.pdf in.pdf if (firstPage.Trim().Length > 0) { converter.FirstPageToConvert = Int32.Parse(firstPage); } if (lastPage.Trim().Length > 0) { converter.LastPageToConvert = Int32.Parse(lastPage); } bool success = converter.Convert(inputPdfFile, outputPdfFile); if (!success) { throw new ApplicationException("Split PDF failed."); } }
public PdfImporterResponse Import(string pdfPath) { if (!Directory.Exists(pdfPath)) { throw new System.ArgumentException($"Path {pdfPath} not exists"); } var lfPath = _appSettings.GetString("lf.path"); var lfVolume = _appSettings.GetString("lf.volume"); var tifPath = Path.Combine(pdfPath, "tif"); if (!Directory.Exists(tifPath)) { Directory.CreateDirectory(tifPath); } foreach (var file in Directory.EnumerateFiles(pdfPath, "*.pdf")) { var fileInfo = new FileInfo(file); var tifFile = Path.Combine(tifPath, fileInfo.Name.Replace(fileInfo.Extension, ".tif")); if (!_converter.Convert(file, tifFile)) { continue; } _laserficheRepository.ImportDocument( $@"{lfPath}\{Path.GetFileNameWithoutExtension(fileInfo.Name)}", lfVolume, tifFile); } return(new PdfImporterResponse()); }
void ConvertPdfToImage(object obj, EventArgs eventArgs) { _converter.Convert( _pathToDirectory + "formula.pdf", _pathToDirectory + "formula.jpg" ); _isConversionRunning = false; if (OnConversionCompletion != null) { OnConversionCompletion.Invoke(); } }
public static List <string> Convert(string filename, string img_filename, OutputFormat output_format, int resolution = 300) { string error = null; List <string> errors = new List <string>(); String gsPath = GetProgramFilePath("gsdll32.dll", out error); if (!System.IO.File.Exists(gsPath)) { File.WriteAllBytes(gsPath, Properties.Resources.gsdll32); } if (error != null) { errors.Add(error); } if (File.Exists(img_filename)) { File.Delete(img_filename); } //This is the object that perform the real conversion! PDFConvert converter = new PDFConvert(); //Ok now check what version is! GhostScriptRevision version = converter.GetRevision(); //lblVersion.Text = version.intRevision.ToString() + " " + version.intRevisionDate; bool Converted = false; //Setup the converter converter.RenderingThreads = -1; converter.TextAlphaBit = -1; converter.TextAlphaBit = -1; converter.FitPage = true; converter.JPEGQuality = mPrintQuality; //80 converter.OutputFormat = output_format.ToString(); converter.OutputToMultipleFile = false; converter.FirstPageToConvert = -1; converter.LastPageToConvert = -1; converter.ResolutionX = converter.ResolutionY = resolution; System.IO.FileInfo input = new FileInfo(filename); if (!string.IsNullOrEmpty(mGSPath)) { converter.GSPath = mGSPath; } Converted = converter.Convert(input.FullName, img_filename); return(errors); }
public string GetRutaImagenDigitalizada(int GuiaID) { string stringConexion = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]; NegociosSisPackFactory.SisPackFactory.setStringConexion(stringConexion); NegociosSisPackFactory.SisPackFactory.Inicializar(stringConexion, Context.Cache); IGuia guia = GuiaFactory.GetGuia(); guia.GuiaID = GuiaID; DataSet dsRuta = guia.GetRutaImagenDigitalizada(); string ruta = string.Empty; if (dsRuta.Tables[0].Rows.Count > 0) { // Buscar la guia digitalizada en origen if (dsRuta.Tables[0].Rows[0]["RutaImagen"].ToString() != String.Empty) { ruta = dsRuta.Tables[0].Rows[0]["RutaImagen"].ToString(); } //Sino buscar la guia digitalizada en destino else if (dsRuta.Tables[0].Rows[0]["RutaImagenDestino"].ToString() != String.Empty) { ruta = dsRuta.Tables[0].Rows[0]["RutaImagenDestino"].ToString(); } // Si encontre datos en origen o destino, convertir el pdf de la guia en imagen para reimprimir en la web de andesmar. if (ruta.Length > 0) { // El parametro "&d=1" es para bajar directamente el pdf desde el proveedor de tsdocs. ruta = ruta + "&d=1"; using (WebClient client = new WebClient()) { string rutaImagen = System.Configuration.ConfigurationSettings.AppSettings["dirImagenes"]; //client.DownloadFile(ruta, @"C:\" + GuiaID + ".pdf"); client.DownloadFile(ruta, rutaImagen + GuiaID + ".pdf"); PDFConvert pp = new PDFConvert(); pp.OutputFormat = "jpeg"; //format pp.JPEGQuality = 100; //100% quality pp.ResolutionX = 300; //dpi pp.ResolutionY = 300; pp.FirstPageToConvert = 1; //pages you want pp.LastPageToConvert = 1; //pp.Convert("C:\\" + GuiaID + ".pdf", "C:\\" + GuiaID + ".jpg"); pp.Convert(rutaImagen + GuiaID + ".pdf", rutaImagen + GuiaID + ".jpg"); string web = System.Configuration.ConfigurationSettings.AppSettings["urlImagenes"]; ruta = web + "?path=" + GuiaID + ".jpg"; } } } return(ruta); }
private string ConvertSingleImage(HtmlInputFile filename) { try { //Setup the converter string strFileName = Path.GetFileName(filename.PostedFile.FileName); var workingDirectory = Server.MapPath("~/pdf/"); filename.PostedFile.SaveAs(workingDirectory + strFileName); converter.FirstPageToConvert = Convert.ToInt32(txtPageNo.Text); converter.LastPageToConvert = Convert.ToInt32(txtPageNo.Text); converter.FitPage = false; //converter.JPEGQuality = (int)numQuality.Value; converter.JPEGQuality = 80; converter.OutputFormat = "jpeg"; System.IO.FileInfo input = new FileInfo(workingDirectory + strFileName); string output = string.Format("{0}\\{1}{2}", input.Directory, input.Name, ".jpg"); //If the output file exist alrady be sure to add a random name at the end until is unique! output = output.Replace(".pdf", ""); while (File.Exists(output)) { output = output.Replace(".jpg", string.Format("{1}{0}", ".jpg", DateTime.Now.Ticks)); } //txtArguments.Text = converter.ParametersUsed; if (converter.Convert(input.FullName, output) == true) { //lblInfo.Text = string.Format("{0}:File converted!", DateTime.Now.ToShortTimeString()); //txtArguments.ForeColor = System.Drawing.Color.Black; imgFile.Visible = true; aImageText.Visible = true; divMessage.Visible = true; } else { divMessage.Visible = false; imgFile.Visible = false; aImageText.Visible = false; lblMessage.Text = "Conversion failed."; //lblInfo.Text = string.Format("{0}:File NOT converted! Check Args!", DateTime.Now.ToShortTimeString()); //txtArguments.ForeColor = System.Drawing.Color.Red; } return(output); } catch (Exception ex) { lblMessage.Text = "Cannot convert because of following error: " + ex.Message.ToString(); imgFile.Visible = false; aImageText.Visible = false; return(""); } }
public static void ConvertPDF(string pathPDF, string pathSave, int firstPage, int lastPage, int width, int height) { Debug.Log("PDF File : " + pathPDF); Debug.Log("Save Folder : " + pathSave); if (Directory.Exists(pathSave)) { Directory.Delete(pathSave, true); } Directory.CreateDirectory(pathSave); PDFConvert converter = new PDFConvert(); converter.Convert(pathPDF, pathSave + "\\%01d.jpg", firstPage, lastPage, "jpeg", width, height); }
public static void FromPDF2TIFF() { Console.WriteLine("\nConverting PDF to TIFF:\n"); using (PDFConvert converter = new PDFConvert()) { //PDFConvert converter = new PDFConvert(); converter.ThrowOnlyException = true; converter.UseMutex = true; converter.TextAlphaBit = 0; converter.FirstPageToConvert = -1; converter.LastPageToConvert = -1; converter.FitPage = false; converter.JPEGQuality = 10; converter.OutputFormat = "tiffg4"; converter.ResolutionX = 300; converter.ResolutionY = 300; converter.Convert("file.pdf", "result.tiff"); } }
//public Image feedtemplate; //public int numItems; //public List<Image> imageList; //public List<Texture2D> textureList; //public Image imageObject; // Use this for initialization void Start() { //readPdfStream(); PDFConvert converter = new PDFConvert(); converter.Convert(@"C:\\Users\\student\\Downloads\\KORACI.pdf", @"C:\\Users\\student\\Documents\\Unity Projects\\SimplePDF Test\\Assets\\Resources\\%01d.jpg", 1, 3, "jpeg", 600, 800); getPDFPages(); //updateScrollViewContent(); //StartCoroutine("CreateItems"); }
/// <summary> /// Convert PDF to PNG format. /// </summary> /// <param name="inputPdfFile"></param> /// <returns>an array of PNG images</returns> public static string[] ConvertPdf2Png(string inputPdfFile) { string tempDirectory = Path.Combine(Path.GetTempPath(), "tessimages" + Path.GetFileNameWithoutExtension(Path.GetRandomFileName())); Directory.CreateDirectory(tempDirectory); PDFConvert converter = new PDFConvert(); converter.GraphicsAlphaBit = 4; converter.TextAlphaBit = 4; converter.ResolutionX = 300; // -r300 converter.OutputFormat = "pnggray"; // -sDEVICE converter.ThrowOnlyException = true; // rethrow exceptions string sOutputFile = string.Format("{0}\\workingimage%04d.png", tempDirectory); try { bool success = converter.Convert(inputPdfFile, sOutputFile); if (success) { // find working files string[] workingFiles = Directory.GetFiles(tempDirectory, "workingimage????.png"); Array.Sort(workingFiles); return(workingFiles); } else { return(new string[0]); } } finally { if (!Directory.EnumerateFileSystemEntries(tempDirectory).Any()) { Directory.Delete(tempDirectory); } } }
private void renderWorker_DoWork(object sender, DoWorkEventArgs e) { renderImage = null; PDFConvert converter = new PDFConvert(); converter.FirstPageToConvert = (int)PageNum.Value; converter.LastPageToConvert = (int)PageNum.Value; converter.OutputFormat = "png16m"; converter.TextAlphaBit = 0; converter.GraphicsAlphaBit = 0; converter.Width = PagePreviewPanel.Width * 4; converter.Height = PagePreviewPanel.Height * 4; converter.FitPage = true; string output = Path.GetTempFileName(); if (converter.Convert(InputFileText.Text, output)) { MemoryStream ms = new MemoryStream(File.ReadAllBytes(output)); renderImage = Image.FromStream(ms); } File.Delete(output); }
static void test2() { string filePath = @"E:\Convert\pdf\"; string filename = "CAR1"; string pdfPath = filePath + filename + ".pdf"; PDFConvert converter = new PDFConvert(); converter.OutputFormat = "jpeg"; converter.JPEGQuality = 800;// mPrintQuality; //80 converter.ResolutionX = 150; converter.ResolutionY = 150; string imgPath = filePath + filename + converter.ResolutionX.ToString() + "_" + converter.ResolutionY.ToString() + ".jpg"; //string imgPath = filePath + "gica1" + converter.ResolutionX.ToString() + "_" + converter.ResolutionY.ToString() + ".jpg"; if (converter.Convert(pdfPath, imgPath, true, null)) { Debug.WriteLine("Seccessed"); } else { Debug.WriteLine("Falid"); } }
public ActionResult UploadImg() { string path = ""; string fileName = ""; string convertpath = ""; string filenamenoext = ""; string fileext = ""; List <int> ResultFormID = new List <int>(); int DocID = 0; List <string> docpage = new List <string>(); int totalpageno = 0; DocID = Convert.ToInt32(Request.Form["DDlDoc"].ToString()); OCRModel imgpath = new OCRModel(); if (Request.Files.Count > 0) { var file = Request.Files[0]; if (file != null && file.ContentLength > 0) { filenamenoext = Path.GetFileNameWithoutExtension(file.FileName); fileName = Path.GetFileName(file.FileName); fileext = Path.GetExtension(file.FileName); path = Path.Combine(Server.MapPath("~/Images/"), fileName); //Save File to destination folder file.SaveAs(path); if (fileext == ".pdf") { //Get pdf total page number FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); StreamReader r = new StreamReader(fs); string pdfText = r.ReadToEnd(); Regex rx1 = new Regex(@"/Type\s*/Page[^s]"); MatchCollection matches = rx1.Matches(pdfText); totalpageno = matches.Count; for (int i = 1; i <= totalpageno; i++) { PdfToImage.PDFConvert pp = new PDFConvert(); pp.OutputFormat = "jpeg"; //format pp.JPEGQuality = 100; //100% quality pp.ResolutionX = 300; //dpi pp.ResolutionY = 300; pp.FirstPageToConvert = i; //pages you want pp.LastPageToConvert = 2; convertpath = Path.Combine(Server.MapPath("~/Images/"), "name_pg" + i + ".jpeg"); pp.Convert(path, convertpath); docpage.Add(convertpath); } } else { //Non Pdf file docpage.Add(path); } //Save sourcefile information to DB ResultFormID = imgpath.insertForm(docpage, DocID); } } if (ResultFormID.Count != 0) { OCRModel obj = new OCRModel(); var PosResult = new List <OCRModel.Position>(); //Get position for each box PosResult = imgpath.retrieveBoxPos(DocID); if (totalpageno == 0) { int passID = ResultFormID[0]; cropImage_Convert(PosResult, path, filenamenoext, passID); } else { //Crop Image base on position and convert to image cropImage_ConvertMulti(PosResult, docpage, filenamenoext, ResultFormID, totalpageno); } } else { } return(RedirectToAction("Upload")); }
private string ConvertPdf2Img(string filename) { if (!System.IO.File.Exists(Application.StartupPath + "\\gsdll32.dll")) { //lblDllInfo.Font = new Font(lblDllInfo.Font.FontFamily, 10, FontStyle.Bold); //lblDllInfo.ForeColor = Color.Red; lblStatus.Text = "Download: http://mirror.cs.wisc.edu/pub/mirrors/ghost/GPL/gs863/gs863w32.exe"; MessageBox.Show("The library 'gsdll32.dll' required to run this program is not present! download GhostScript and copy \"gsdll32.dll\" to this program directory"); return(""); } //This is the object that perform the real conversion! PDFConvert converter = new PDFConvert(); //Ok now check what version is! GhostScriptRevision version = converter.GetRevision(); //lblVersion.Text = version.intRevision.ToString() + " " + version.intRevisionDate; bool Converted = false; //Setup the converter //Setup the converter converter.RenderingThreads = -1; converter.TextAlphaBit = -1; converter.TextAlphaBit = -1; converter.FitPage = false; converter.JPEGQuality = 10; converter.OutputFormat = "png256"; converter.ResolutionX = 500; converter.ResolutionY = 500; converter.OutputToMultipleFile = false; converter.FirstPageToConvert = -1; converter.LastPageToConvert = -1; System.IO.FileInfo input = new FileInfo(filename); //string output = string.Format("{0}\\Images\\tmp\\{1}{2}", Application.StartupPath, DateTime.Now.ToString("yyyyMMddHHmmss"), ".png"); string output = string.Format("{0}\\Images\\tmp\\{1}{2}", Application.StartupPath, DateTime.Now.ToString("yyyyMMddHHmmss"), ".png"); int indexer = 0; while (File.Exists(output)) { output = string.Format("{0}\\Images\\tmp\\{1}{2}{3}", Application.StartupPath, DateTime.Now.ToString("yyyyMMddHHmmss"), indexer++, ".png"); } //If the output file exist alrady be sure to add a random name at the end until is unique! //Just avoid this code, isn't working yet //if (checkRedirect.Checked) //{ // Image newImage = converter.Convert(input.FullName); // Converted = (newImage != null); // if (Converted) // pictureOutput.Image = newImage; //} //else converter.GSPath = string.Format("{0}\\gs", Application.StartupPath); Converted = converter.Convert(input.FullName, output); //txtArguments.Text = converter.ParametersUsed; //if (Converted) //{ // lblInfo.Text = string.Format("{0}:File converted!", DateTime.Now.ToShortTimeString()); // txtArguments.ForeColor = Color.Black; //} //else //{ // lblInfo.Text = string.Format("{0}:File NOT converted! Check Args!", DateTime.Now.ToShortTimeString()); // txtArguments.ForeColor = Color.Red; //} return(output); }
public void ConvertPDFs() { //Erzeugt Items für den Container aus den PDF Datein im Documents/Info Verzeichnis //Der Dateiname bestimmt den Darstellungsnamen, der Unterordner die Kategorie //Da PDFs hier direkt nur über ein ActiveX Steuerelement dargestellt werden könnten, welches dem User Zugriff auf Webbrowser und Dateisystem (Links im Dokument, "Speichern" Dialog) ermöglicht, //werden PDF Dateien vorher in ein png gerendert und diese stattdessen dargestellt. try { string[] PDFDeleteArray = Directory.GetFiles(@"Documents\Info\Aktuelles\", "*.pdf", SearchOption.AllDirectories); MySqlCommand command = myConnection.CreateCommand(); command.CommandText = "SELECT * FROM `contentPDF`"; MySqlDataReader Reader; myConnection.Open(); Reader = command.ExecuteReader(); WebClient wc = new WebClient(); List <string> SQLList = new List <string>(); while (Reader.Read()) { if (!File.Exists(@"Documents\Info\Aktuelles\" + Reader.GetValue(0) + ".pdf")) { try { wc.DownloadFileAsync(new Uri("http://gauss.wi.hm.edu/~mystik/uploadPDF/" + Reader.GetValue(0) + ".pdf"), @"Documents\Info\Aktuelles\" + Reader.GetValue(0) + ".pdf"); } catch { } } SQLList.Add(Reader.GetValue(0).ToString()); } myConnection.Close(); foreach (string file in PDFDeleteArray) { FileInfo fileInfo = new FileInfo(file); bool delete = true; //MessageBox.Show(fileInfo.Name.Replace(fileInfo.Extension, "")); foreach (string SQLName in SQLList) { if (fileInfo.Name.Replace(fileInfo.Extension, "").Equals(SQLName)) { delete = false; } } if (delete) { try { File.Delete(file); } catch { } } } string[] PNGDeleteArray = Directory.GetFiles(@"Documents\Info\Aktuelles", "*.png", SearchOption.AllDirectories); foreach (string file in PNGDeleteArray) { try { this.Dispatcher.Invoke(new Action(delegate { //if (infoItems.Count() > 0) //{ // int j = 0; // do // { // infoItems[j].Bitmap. // infoItems[j].fileInfo // j++; // } while (j < infoItems.Count() - 1); //} infoItems = new ObservableCollection <InfoItem>(); //view = CollectionViewSource.GetDefaultView(infoItems); //docContainer.DataContext = "docContainer"; //view.GroupDescriptions.Add(new PropertyGroupDescription("GroupName")); //docContainer.ItemsSource = view; File.Delete(file); })); } catch (Exception e) { Console.WriteLine("deletepngs: " + e.Message); } } try { string[] PDFArray = Directory.GetFiles(@"Documents\Info", "*.pdf", SearchOption.AllDirectories); PDFConvert converter = new PDFConvert(); foreach (string file in PDFArray) { FileInfo fileInfo = new FileInfo(file); if (!File.Exists(fileInfo.FullName.Replace(".pdf", ".png"))) { converter.RenderingThreads = 1; converter.TextAlphaBit = 4; converter.OutputToMultipleFile = true; converter.GraphicsAlphaBit = 4; converter.FirstPageToConvert = 1; converter.LastPageToConvert = 2; converter.FitPage = true; converter.ResolutionX = 200; converter.ResolutionY = 200; converter.OutputFormat = "png16m"; converter.Convert(fileInfo.FullName, fileInfo.FullName.Replace(".pdf", ".png")); } } } catch { } } catch (Exception e) { Console.WriteLine("CreatePDFS: " + e.Message); } }