Example #1
0
        //, out string newImagePath)
        public static Bitmap ConvertPdfToBitmap(string imagePath)
        {
            string newImagePath = string.Empty;
            string outputFileName = "PdfToImageTest.tiff";
            PDFConvert convert = new PDFConvert();
            convert.FirstPageToConvert = 1;
            convert.LastPageToConvert = 1;
            convert.FitPage = true;
            convert.OutputFormat = "tiff32nc";
            convert.ResolutionX = 400;
            convert.ResolutionY = 400;

            if (File.Exists(outputFileName))
                File.Delete(outputFileName);

            if (!convert.Convert(imagePath, outputFileName))
            {
                MessageBox.Show("File not converted");
                return null;
            }

            Image tempImg = Image.FromFile(outputFileName);
            Bitmap bp = tempImg as Bitmap;

            outputFileName = "PdfToImage.bmp";

            if (File.Exists(outputFileName))
                File.Delete(outputFileName);

            bp.Save(outputFileName);
            newImagePath = outputFileName;

            //return CompressBitmap(outputFileName);
            return bp;
        }
Example #2
0
        public static bool ConvertSingleImage(string filename, string pPastaAtualApresentacao)
        {
            bool Converted = false;
            //Setup the converter
            //if (numericThreads.Value > 0)
            //    converter.RenderingThreads = (int)numericThreads.Value;

            //if (((int)numericTextSampling.Value > 0) && ((int)numericTextSampling.Value != 3))
            //    converter.TextAlphaBit = (int)numericTextSampling.Value;

            //if (((int)numericGraphSampling.Value > 0) && ((int)numericGraphSampling.Value != 3))
            //    converter.TextAlphaBit = (int)numericGraphSampling.Value;

            PDFConvert converter = new PDFConvert();

            converter.OutputToMultipleFile = true;
            converter.FirstPageToConvert = 0;
            converter.LastPageToConvert = 100;
            converter.FitPage = true;
            converter.JPEGQuality = 100;
            converter.OutputFormat = "png16m";
            System.IO.FileInfo input = new FileInfo(filename);


            //string output = string.Format("{0}\\{1}{2}", input.Directory, input.Name, ".png");
            string output = string.Format("{0}\\{1}{2}", pPastaAtualApresentacao, input.Name, ".png");

            //If the output file exist alrady be sure to add a random name at the end until is unique!
            while (File.Exists(output))
            {
                output = output.Replace(".png", string.Format("{1}{0}", ".png", DateTime.Now.Ticks));
            }
            //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 
            Converted = converter.Convert(input.FullName, output);
            //txtArguments.Text = converter.ParametersUsed;

            return Converted;

            //if (Converted)
            //{
            //    renomeiaArquivos(pPastaAtualApresentacao);
                //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;
            //}
        }
        public LatexToImg(string pathToDirectory)
        {
            _converter = new PDFConvert();
            _converter.OutputFormat = "jpeg"; //format
            _converter.ResolutionX = _baseResolution; //dpi
            _converter.ResolutionY = _baseResolution;
            _converter.GraphicsAlphaBit = 4;
            _converter.TextAlphaBit = 4;
            _converter.UseMutex = true;

            _queuedUpdates = new List<string>();
            _isConversionRunning = false;
            _pathToDirectory = pathToDirectory;
        }
Example #4
0
        public GhostScriptRevision GetRevision()
        {
            GS_Revision pGSRevisionInfo = new GS_Revision();
            GCHandle    gcHandle        = GCHandle.Alloc((object)pGSRevisionInfo, GCHandleType.Pinned);

            PDFConvert.gsapi_revision(ref pGSRevisionInfo, 16);
            GhostScriptRevision ghostScriptRevision;

            ghostScriptRevision.intRevision           = pGSRevisionInfo.intRevision;
            ghostScriptRevision.intRevisionDate       = pGSRevisionInfo.intRevisionDate;
            ghostScriptRevision.ProductInformation    = PDFConvert.AnsiZtoString(pGSRevisionInfo.strProduct);
            ghostScriptRevision.CopyrightInformations = PDFConvert.AnsiZtoString(pGSRevisionInfo.strCopyright);
            gcHandle.Free();
            return(ghostScriptRevision);
        }
Example #5
0
        public int gsdll_stdout(IntPtr intGSInstanceHandle, IntPtr strz, int intBytes)
        {
            byte[]   numArray = new byte[intBytes];
            GCHandle gcHandle = GCHandle.Alloc((object)numArray, GCHandleType.Pinned);

            PDFConvert.CopyMemory(gcHandle.AddrOfPinnedObject(), strz, (uint)intBytes);
            IntPtr num = IntPtr.Zero;

            gcHandle.Free();
            string str = "";

            for (int index = 0; index < intBytes; ++index)
            {
                str += (string)(object)(char)numArray[index];
            }
            this.output.Append(str);
            return(intBytes);
        }
Example #6
0
 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");
     }
 }
Example #7
0
        public int gsdll_stdin(IntPtr intGSInstanceHandle, IntPtr strz, int intBytes)
        {
            if (intBytes == 0)
            {
                return(0);
            }
            int num1 = Console.Read();

            if (num1 == -1)
            {
                return(0);
            }
            GCHandle gcHandle = GCHandle.Alloc((object)(byte)num1, GCHandleType.Pinned);
            IntPtr   Source   = gcHandle.AddrOfPinnedObject();

            PDFConvert.CopyMemory(strz, Source, 1U);
            IntPtr num2 = IntPtr.Zero;

            gcHandle.Free();
            return(1);
        }
Example #8
0
        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); }
        }
Example #9
0
        private string[] GetGeneratedArgs(string inputFile, string outputFile, string[] presetParameters)
        {
            ArrayList arrayList = new ArrayList();

            string[] strArray;
            if (presetParameters == null || presetParameters.Length == 0)
            {
                if (this._sDeviceFormat == "jpeg" && this._iJPEGQuality > 0 && this._iJPEGQuality < 101)
                {
                    arrayList.Add((object)string.Format("-dJPEGQ={0}", (object)this._iJPEGQuality));
                }
                if (this._iWidth > 0 && this._iHeight > 0)
                {
                    arrayList.Add((object)string.Format("-g{0}x{1}", (object)this._iWidth, (object)this._iHeight));
                }
                else if (!string.IsNullOrEmpty(this._sDefaultPageSize))
                {
                    arrayList.Add((object)string.Format("-sPAPERSIZE={0}", (object)this._sDefaultPageSize));
                    if (this._bForcePageSize)
                    {
                        arrayList.Add((object)"-dFIXEDMEDIA");
                    }
                }
                if (this._iGraphicsAlphaBit > 0)
                {
                    arrayList.Add((object)string.Format("-dGraphicsAlphaBits={0}", (object)this._iGraphicsAlphaBit));
                }
                if (this._iTextAlphaBit > 0)
                {
                    arrayList.Add((object)string.Format("-dTextAlphaBits={0}", (object)this._iTextAlphaBit));
                }
                if (this._bFitPage)
                {
                    arrayList.Add((object)"-dPDFFitPage");
                }
                if (this._iResolutionX > 0)
                {
                    if (this._iResolutionY > 0)
                    {
                        arrayList.Add((object)string.Format("-r{0}x{1}", (object)this._iResolutionX, (object)this._iResolutionY));
                    }
                    else
                    {
                        arrayList.Add((object)string.Format("-r{0}", (object)this._iResolutionX));
                    }
                }
                if (this._iFirstPageToConvert > 0)
                {
                    arrayList.Add((object)string.Format("-dFirstPage={0}", (object)this._iFirstPageToConvert));
                }
                if (this._iLastPageToConvert > 0)
                {
                    if (this._iFirstPageToConvert > 0 && this._iFirstPageToConvert > this._iLastPageToConvert)
                    {
                        throw new ArgumentOutOfRangeException(string.Format("The 1st page to convert ({0}) can't be after then the last one ({1})", (object)this._iFirstPageToConvert, (object)this._iLastPageToConvert));
                    }
                    arrayList.Add((object)string.Format("-dLastPage={0}", (object)this._iLastPageToConvert));
                }
                if (this._iRenderingThreads > 0)
                {
                    arrayList.Add((object)string.Format("-dNumRenderingThreads={0}", (object)this._iRenderingThreads));
                }
                if (!this._bRedirectIO)
                {
                    ;
                }
                if (this._sFontPath != null && this._sFontPath.Count > 0)
                {
                    arrayList.Add((object)string.Format("-sFONTPATH={0}", (object)string.Join(";", this._sFontPath.ToArray())));
                }
                if (this._bDisablePlatformFonts)
                {
                    arrayList.Add((object)"-dNOPLATFONTS");
                }
                if (this._bDisableFontMap)
                {
                    arrayList.Add((object)"-dNOFONTMAP");
                }
                if (this._sFontMap != null && this._sFontMap.Count > 0)
                {
                    arrayList.Add((object)string.Format("-sFONTMAP={0}", (object)string.Join(";", this._sFontMap.ToArray())));
                }
                if (!string.IsNullOrEmpty(this._sSubstitutionFont))
                {
                    arrayList.Add((object)string.Format("-sSUBSTFONT={0}", (object)this._sSubstitutionFont));
                }
                if (!string.IsNullOrEmpty(this._sFCOFontFile))
                {
                    arrayList.Add((object)string.Format("-sFCOfontfile={0}", (object)this._sFCOFontFile));
                }
                if (!string.IsNullOrEmpty(this._sFAPIFontMap))
                {
                    arrayList.Add((object)string.Format("-sFAPIfontmap={0}", (object)this._sFAPIFontMap));
                }
                if (this._bDisablePrecompiledFonts)
                {
                    arrayList.Add((object)"-dNOCCFONTS");
                }
                int num   = 7;
                int count = arrayList.Count;
                strArray    = new string[num + arrayList.Count];
                strArray[1] = "-dNOPAUSE";
                strArray[2] = "-dBATCH";
                strArray[3] = "-dSAFER";
                strArray[4] = string.Format("-sDEVICE={0}", (object)this._sDeviceFormat);
                for (int index = 0; index < count; ++index)
                {
                    strArray[5 + index] = (string)arrayList[index];
                }
            }
            else
            {
                strArray = new string[presetParameters.Length + 3];
                for (int index = 1; index <= presetParameters.Length; ++index)
                {
                    strArray[index] = presetParameters[index - 1];
                }
            }
            strArray[0] = "pdf2img";
            if (this._didOutputToMultipleFile && !outputFile.Contains("%"))
            {
                int startIndex = outputFile.LastIndexOf('.');
                if (startIndex > 0)
                {
                    outputFile = outputFile.Insert(startIndex, "%d");
                }
            }
            this._sParametersUsed = string.Empty;
            for (int index = 1; index < strArray.Length - 2; ++index)
            {
                PDFConvert pdfConvert = this;
                string     str        = pdfConvert._sParametersUsed + " " + strArray[index];
                pdfConvert._sParametersUsed = str;
            }
            strArray[strArray.Length - 2] = string.Format("-sOutputFile={0}", (object)outputFile);
            strArray[strArray.Length - 1] = string.Format("{0}", (object)inputFile);
            PDFConvert pdfConvert1 = this;
            string     str1        = pdfConvert1._sParametersUsed + " " + string.Format("-sOutputFile={0}", (object)string.Format("\"{0}\"", (object)outputFile)) + " " + string.Format("\"{0}\"", (object)inputFile);

            pdfConvert1._sParametersUsed = str1;
            return(strArray);
        }
Example #10
0
        private bool ExecuteGhostscriptCommand(string[] sArgs)
        {
            IntPtr pinstance = IntPtr.Zero;
            int    length    = sArgs.Length;

            object[]   objArray  = new object[length];
            IntPtr[]   numArray  = new IntPtr[length];
            GCHandle[] aGCHandle = new GCHandle[length];
            for (int index = 0; index < length; ++index)
            {
                objArray[index]  = (object)PDFConvert.StringToAnsiZ(sArgs[index]);
                aGCHandle[index] = GCHandle.Alloc(objArray[index], GCHandleType.Pinned);
                numArray[index]  = aGCHandle[index].AddrOfPinnedObject();
            }
            GCHandle gchandleArgs = GCHandle.Alloc((object)numArray, GCHandleType.Pinned);
            IntPtr   argv         = gchandleArgs.AddrOfPinnedObject();
            int      num1         = -1;

            try
            {
                if (PDFConvert.gsapi_new_instance(out pinstance, this._objHandle) < 0)
                {
                    this.ClearParameters(ref aGCHandle, ref gchandleArgs);
                    throw new ApplicationException("I can't create a new istance of Ghostscript please verify no other istance are running!");
                }
            }
            catch (BadImageFormatException ex)
            {
                this.ClearParameters(ref aGCHandle, ref gchandleArgs);
                if (IntPtr.Size == 8)
                {
                    throw new ApplicationException(string.Format("The gsdll32.dll you provide is not compatible with the current architecture that is 64bit,Please download any version above version 8.64 from the original website in the 64bit or x64 or AMD64 version!"));
                }
                if (IntPtr.Size == 4)
                {
                    throw new ApplicationException(string.Format("The gsdll32.dll you provide is not compatible with the current architecture that is 32bit,Please download any version above version 8.64 from the original website in the 32bit or x86 or i386 version!"));
                }
            }
            catch (DllNotFoundException ex)
            {
                this.ClearParameters(ref aGCHandle, ref gchandleArgs);
                throw new ApplicationException("The gsdll32.dll wasn't found in default dlls search pathor is not in correct version (doesn't expose the required methods). Please download at least the version 8.64 from the original website");
            }
            IntPtr num2 = IntPtr.Zero;

            if (this._bRedirectIO)
            {
                StdioCallBack gsdll_stdin  = new StdioCallBack(this.gsdll_stdin);
                StdioCallBack gsdll_stdout = new StdioCallBack(this.gsdll_stdout);
                StdioCallBack gsdll_stderr = new StdioCallBack(this.gsdll_stderr);
                num1 = PDFConvert.gsapi_set_stdio(pinstance, gsdll_stdin, gsdll_stdout, gsdll_stderr);
                if (this.output == null)
                {
                    this.output = new StringBuilder();
                }
                else
                {
                    this.output.Remove(0, this.output.Length);
                }
                this.myProcess = Process.GetCurrentProcess();
                this.myProcess.OutputDataReceived += new DataReceivedEventHandler(this.SaveOutputToImage);
            }
            int num3 = -1;

            try
            {
                num3 = PDFConvert.gsapi_init_with_args(pinstance, length, argv);
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message, ex);
            }
            finally
            {
                this.ClearParameters(ref aGCHandle, ref gchandleArgs);
                PDFConvert.gsapi_exit(pinstance);
                PDFConvert.gsapi_delete_instance(pinstance);
                if (this.myProcess != null && this._bRedirectIO)
                {
                    this.myProcess.OutputDataReceived -= new DataReceivedEventHandler(this.SaveOutputToImage);
                }
            }
            return(num3 == 0 | num3 == -101);
        }
Example #11
0
        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);
        }
Example #12
0
        public void AddPdfDownload(FileInfo p)
        {
            if (Pdfs == null) Pdfs = new Queue<FileInfo>();
            Pdfs.Enqueue(p);

            if (gsBusy) return;
            gsBusy = true;
            ThreadPool.QueueUserWorkItem(delegate
            {
                while (Pdfs.Count > 0)
                {
                    try
                    {
                        var pdf = Pdfs.Dequeue();
                        var nd = pdf.DirectoryName + "\\^" + pdf.Name;
                        Directory.CreateDirectory(nd);
                        var converter = new PDFConvert
                        {
                            OutputToMultipleFile = true,
                            FirstPageToConvert   = -1,
                            LastPageToConvert    = -1,
                            FitPage              = false,
                            JPEGQuality          = 10,
                            OutputFormat         = "png16m",
                            Width                = pdfImageWidth,
                            ResolutionX          = pdfResolution,
                            ResolutionY          = pdfResolution
                        };

                        var input = new FileInfo(pdf.FullName);
                        var output = string.Format("{0}\\{1}{2}", nd, input.Name, ".png");
                        //If the output file exist alrady be sure to add a random name at the end until is unique!
                        while (File.Exists(output))
                        {
                            output = output.Replace(".png", string.Format("{1}{0}", ".png", DateTime.Now.Ticks));
                        }
                        //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.Convert(input.FullName, output);
                    }
                    catch (Exception e)
                    {
                        Logger.Log("Presenter", "Error creating pdf", e.Message, Logger.Level.Error);
                    }
                    //Reload();
                }
                gsBusy = false;
                Reload();
            });
        }