Пример #1
0
        private PdfInfo GetPdfInfo(string path)
        {
            string output;
            string pdfInfoPath           = GetPathInfoResource();
            GhostscriptSettings settings = new GhostscriptSettings
            {
                GhostscriptArgument.NoDisplay,
                GhostscriptArgument.Quiet,
                { GhostscriptArgument.File, path },
                pdfInfoPath
            };

            output = _engine.Execute(settings);

            try
            {
                // remove temporary file
                File.Delete(pdfInfoPath);
            }
            catch
            {
                // ok, it's 4 Kb in the temp folder, not a big deal
            }

            // Deserialize PDF info output from XML
            using (StringReader outputReader = new StringReader(output))
            {
                return((PdfInfo)_pdfInfoSerializer.Deserialize(outputReader));
            }
        }
Пример #2
0
        private void ApplyResizeSettings(ResizeSettings settings, GhostscriptSettings ghostscriptSettings)
        {
            // Parse resize settings

            // - graphicsAlphaBits
            int graphicsAlphaBits = settings.GetValueOrDefault("graphicsbits", 0);

            if (!_validAlphaBitValues.Contains(graphicsAlphaBits))
            {
                // Use default value
                graphicsAlphaBits = _validAlphaBitValues.Last();
            }
            ghostscriptSettings.Add(GhostscriptArgument.GraphicsAlphaBits, graphicsAlphaBits);

            // - textAlphaBits
            int textAlphaBits = settings.GetValueOrDefault("textbits", 0);

            if (!_validAlphaBitValues.Contains(textAlphaBits))
            {
                // Use default value
                textAlphaBits = _validAlphaBitValues.Last();
            }
            ghostscriptSettings.Add(GhostscriptArgument.TextAlphaBits, textAlphaBits);

            ghostscriptSettings[GhostscriptArgument.GridFitTT]     = (settings.Get <bool>("gridfit") == true ? 2 : 0).ToString(NumberFormatInfo.InvariantInfo);
            ghostscriptSettings[GhostscriptArgument.AlignToPixels] = (settings.Get <bool>("subpixels") == true ? 1 : 0).ToString(NumberFormatInfo.InvariantInfo);
            if (settings.Get <bool>("printed", true) == false)
            {
                ghostscriptSettings.Remove(GhostscriptArgument.Printed);
            }
        }
Пример #3
0
        public static void WriteOut(int pJpegWidth = 0, int[] pages = null)
        {
            var OutputPath = AppDomain.CurrentDomain.BaseDirectory;
            var sourceFile = "test.pdf";

            var jpegFile = Path.ChangeExtension(sourceFile, "jpg");

            var settings = new GhostscriptSettings
            {
                Page       = { AllPages = false, Start = 1, End = 1 },
                Size       = { Native = GhostscriptPageSizes.a2 },
                Device     = GhostscriptDevices.png16m,
                Resolution = new Size(150, 122)
            };

            if (pages.Length > 1)
            {
                // PDF contains multiple pages, make each one into a jpg
                var iPageNumber = 0;
                foreach (var page in pages)
                {
                    //FORMAT: GhostscriptWrapper.GenerateOutput(<pdf file path>, <destination jpg path>, <settings>);
                    GhostscriptWrapper.GenerateOutput(OutputPath + sourceFile, OutputPath + jpegFile.Replace(".jpg", "_" + iPageNumber + ".jpg"), settings);      // add page number into jpg string
                    iPageNumber++;
                    settings.Page.Start = settings.Page.End = iPageNumber + 1;
                }
            }
            else
            {
                //FORMAT: GhostscriptWrapper.GenerateOutput(<pdf file path>, <destination jpg path>, <settings>);
                GhostscriptWrapper.GenerateOutput(OutputPath + sourceFile, OutputPath + jpegFile, settings);
            }
        }
        private static GhostscriptSettings GsSettings()
        {
            GhostscriptSettings gsSettings = new GhostscriptSettings
            {
                Device = GhostscriptDevices.jpeg,
                Page   = new GhostscriptPages
                {
                    Start    = 1,
                    End      = 1,
                    AllPages = false
                },
                Resolution = new Size
                {
                    //dpi
                    Height = 20,
                    Width  = 20
                },
                Size = new GhostscriptPageSize
                {
                    Native = GhostscriptPageSizes.a4
                }
            };

            return(gsSettings);
        }
Пример #5
0
        private void ButtonGenerate_Click(object sender, EventArgs e)
        {
            try
            {
                string               inputPath  = this.textBoxInputPath.Text;
                string               outputPath = this.textBoxOutputPath.Text;
                int                  page       = (int)this.numericUpDownPage.Value;
                int                  resolution = (int)this.numericUpDownResolution.Value;
                GhostscriptDevices   device     = (GhostscriptDevices)this.comboBoxDevice.SelectedItem;
                GhostscriptPageSizes pageSize   = (GhostscriptPageSizes)this.comboBoxPageSize.SelectedItem;

                GhostscriptSettings ghostscriptSettings = new GhostscriptSettings
                {
                    Page = new GhostscriptPages {
                        Start = page, End = page
                    },
                    Device     = device,
                    Resolution = new Size(resolution, resolution),
                    Size       = new GhostscriptPageSize {
                        Native = pageSize
                    }
                };
                GhostscriptWrapper.GenerateOutput(inputPath, outputPath, ghostscriptSettings);

                Process.Start(outputPath);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }
        }
    //用來轉換PDF成一張一張的jpeg圖片
    public void f_ConvertAllPDF(string pdfPath, string savePath)
    {
        GhostscriptSettings ghostscriptSettings = new GhostscriptSettings();

        ghostscriptSettings.Device      = GhostscriptSharp.Settings.GhostscriptDevices.jpeg;    //圖片類型
        ghostscriptSettings.Size.Native = GhostscriptSharp.Settings.GhostscriptPageSizes.legal; //legal為原尺寸
        //ghostscriptSettings.Size.Manual = new System.Drawing.Size(2552, 3579); //此為設定固定尺寸
        ghostscriptSettings.Resolution    = new System.Drawing.Size(150, 150);                  //此為解析度
        ghostscriptSettings.Page.AllPages = true;
        GhostscriptWrapper.GenerateOutput(pdfPath, savePath, ghostscriptSettings);

        Debug.Log("Complete!");
    }
        public void GenerateSinglePageOutput()
        {
            var settings = new GhostscriptSettings
            {
                Page       = { AllPages = false, Start = 1, End = 1 },
                Size       = { Native = GhostscriptPageSizes.a2 },
                Device     = GhostscriptDevices.png16m,
                Resolution = new Size(150, 122)
            };

            GhostscriptWrapper.GenerateOutput(OutputPath + TEST_FILE_LOCATION, OutputPath + SINGLE_FILE_LOCATION, settings);
            Assert.IsTrue(File.Exists(OutputPath + SINGLE_FILE_LOCATION));
        }
Пример #8
0
        private static void PdfToJpg(string path, string fileName, GhostscriptDevices devise, GhostscriptPageSizes pageFormat, int qualityX, int qualityY)
        {
            var settingsForConvert = new GhostscriptSettings {
                Device = devise
            };
            var pageSize = new GhostscriptPageSize {
                Native = pageFormat
            };

            settingsForConvert.Size       = pageSize;
            settingsForConvert.Resolution = new System.Drawing.Size(qualityX, qualityY);

            GhostscriptWrapper.GenerateOutput(path, @"C:\YR\Receipt\" + fileName + "_" + ".jpg", settingsForConvert); // here you could set path and name for out put file.
        }
        public static GhostscriptSettings Default()
        {
            // FG20131016: Verificare come si comporta con documenti con formato di pagina non omogeneo.
            var settings = new GhostscriptSettings()
            {
                Device     = GhostscriptDevices.png256,
                Resolution = new Size(300, 300),
                Size       = new GhostscriptPageSize()
                {
                    Native = GhostscriptPageSizes.a4
                }
            };

            settings.Page.AllPagesWorkaround();
            return(settings);
        }
Пример #10
0
        private PdfInfo GetPdfInfo(string path)
        {
            string output;
            GhostscriptSettings settings = new GhostscriptSettings
            {
                GhostscriptArgument.NoDisplay,
                GhostscriptArgument.Quiet,
                { GhostscriptArgument.File, path },
                PdfInfoPath
            };

            output = _engine.Execute(settings);

            // Deserialize PDF info output from XML
            using (StringReader outputReader = new StringReader(output))
            {
                return((PdfInfo)_pdfInfoSerializer.Deserialize(outputReader));
            }
        }
        //Pdfから画像を取得する
        private string getImageFromPdf(string baseFilePass, string pdfFielName)
        {
            //拡張子無しでファイル名を取得する
            string imgFileName = Path.GetFileNameWithoutExtension(pdfFielName) + ".png";

            try
            {
                //Pdfから画像を取得
                GhostscriptSettings settings = new GhostscriptSettings();
                settings.Page.AllPages = true;                                                //全ページ出力
                settings.Page.Start    = 1;                                                   //出力開始ページ
                settings.Page.End      = 1;                                                   //出力終了ページ
                settings.Size.Native   = GhostscriptSharp.Settings.GhostscriptPageSizes.a0;   //出力サイズ指定
                settings.Device        = GhostscriptSharp.Settings.GhostscriptDevices.png256; //出力ファイルフォーマット指定(pngで指定)
                settings.Resolution    = new Size(600, 600);                                  //出力Dpi

                string inputPath  = baseFilePass + "\\" + pdfFielName;
                string outputPath = baseFilePass + "\\" + imgFileName;
                GhostscriptWrapper.GenerateOutput(inputPath, outputPath, settings); // Create the initial thumbnail

                //ファイルが生成されない場合はパスを返さない
                if (!System.IO.File.Exists(outputPath))
                {
                    imgFileName = "";
                    outLogMsg(pdfFielName, "Pdf埋め込み画像なし");
                }
                else
                {
                    outLogMsg(pdfFielName, "Pdf画像変換完了");
                }
            }
            catch (Exception exp)
            {
                imgFileName = "";
                outLogMsg(pdfFielName, "Pdf画像取得実施エラー : " + exp.Message);
            }

            return(imgFileName);
        }
Пример #12
0
        public static string GetDeviceExtension(this GhostscriptSettings source)
        {
            switch (source.Device)
            {
            case GhostscriptDevices.bmpgray:
                return(".bmp");

            case GhostscriptDevices.jpeg:
            case GhostscriptDevices.jpeggray:
                return(".jpg");

            case GhostscriptDevices.pnggray:
            case GhostscriptDevices.pngmono:
            case GhostscriptDevices.png256:
                return(".png");

            default:
                break;
            }

            throw new NotImplementedException("Estensione non implementata per il GhostscriptDevices specificato.");
        }
Пример #13
0
        private PdfInfo GetPdfInfo(string path)
        {
            string output;
            GhostscriptSettings settings = new GhostscriptSettings
                                           {
                                               GhostscriptArgument.NoDisplay,
                                               GhostscriptArgument.Quiet,
                                               {GhostscriptArgument.File, path},
                                               PdfInfoPath
                                           };
            output = _engine.Execute(settings);

            // Deserialize PDF info output from XML
            using(StringReader outputReader = new StringReader(output))
            {
                return (PdfInfo)_pdfInfoSerializer.Deserialize(outputReader);
            }
        }
Пример #14
0
        private PdfInfo GetPdfInfo(string path)
        {
            string output;
            string pdfInfoPath = GetPathInfoResource();
            GhostscriptSettings settings = new GhostscriptSettings
                                           {
                                               GhostscriptArgument.NoDisplay,
                                               GhostscriptArgument.Quiet,
                                               { GhostscriptArgument.File, path },
                                               pdfInfoPath
                                           };
            output = _engine.Execute(settings);

            try
            {
                // remove temporary file
                File.Delete(pdfInfoPath);
            }
            catch
            {
                // ok, it's 4 Kb in the temp folder, not a big deal
            }

            // Deserialize PDF info output from XML
            using(StringReader outputReader = new StringReader(output))
            {
                return (PdfInfo)_pdfInfoSerializer.Deserialize(outputReader);
            }
        }
Пример #15
0
        private void ApplyResizeSettings(ResizeSettings settings, GhostscriptSettings ghostscriptSettings)
        {
            // Parse resize settings

            // - graphicsAlphaBits
            int graphicsAlphaBits = settings.GetValueOrDefault("graphicsbits", 0);
            if(!_validAlphaBitValues.Contains(graphicsAlphaBits))
            {
                // Use default value
                graphicsAlphaBits = _validAlphaBitValues.Last();
            }
            ghostscriptSettings.Add(GhostscriptArgument.GraphicsAlphaBits, graphicsAlphaBits);

            // - textAlphaBits
            int textAlphaBits = settings.GetValueOrDefault("textbits", 0);
            if(!_validAlphaBitValues.Contains(textAlphaBits))
            {
                // Use default value
                textAlphaBits = _validAlphaBitValues.Last();
            }
            ghostscriptSettings.Add(GhostscriptArgument.TextAlphaBits, textAlphaBits);

            ghostscriptSettings[GhostscriptArgument.GridFitTT] = (settings.Get<bool>("gridfit") == true ? 2 : 0).ToString(NumberFormatInfo.InvariantInfo);
            ghostscriptSettings[GhostscriptArgument.AlignToPixels] = (settings.Get<bool>("subpixels") == true ? 1 : 0).ToString(NumberFormatInfo.InvariantInfo);
            if (settings.Get<bool>("printed",true) == false) ghostscriptSettings.Remove(GhostscriptArgument.Printed);
        }
Пример #16
0
        public override Bitmap DecodeStream(Stream s, ResizeSettings settings, string optionalPath)
        {
            if(string.IsNullOrEmpty(optionalPath))
            {
                if (s.CanSeek) {
                    //Check the header instead if no filename is present.
                    byte[] header = new byte[4];
                    s.Read(header, 0, 4);
                    bool isPdf = (header[0] == '%' && header[1] == 'P' && header[2] == 'D' && header[3] == 'F');
                    s.Seek(-4, SeekOrigin.Current); //Restore position.

                    if (!isPdf) return null;
                } else {
                    return null; //It's not seekable, we can't check the header.
                }
            } else if(!_supportedExtensions.Contains(Path.GetExtension(optionalPath), StringComparer.OrdinalIgnoreCase))
            {
                // Not a supported format
                return null;
            }

            // Do not allow decoding if Ghostscript there are issues with performing this decode
            IIssue[] issues = GetIssues().ToArray();
            if(issues.Length > 0)
            {
                string message = string.Join(Environment.NewLine, issues.Select(x => x.Summary).ToArray());
                throw new InvalidOperationException(message);
            }

            // Must write input stream to a temporary file for Ghostscript to process.
            FileInfo tempInputPathInfo = new FileInfo(Path.GetTempFileName());
            try
            {
                using(FileStream tempInputStream = tempInputPathInfo.Create())
                {
                    StreamExtensions.CopyToStream(s, tempInputStream);
                }

                // Get information about the PDF such as page count and media boxes
                // Although this creates a second trip to Ghostscript engine, it's not possible to generate a rendered image in exact
                // dimensions requested. Skipping this step will cause a rendered image, of some size, to be resized further.
                PdfInfo pdfInfo = GetPdfInfo(tempInputPathInfo.FullName);

                // Extract the requested page number from resize settings, or default to first page
                int pageNumber = settings.GetValueOrDefault("page", 1);

                // Try to get the page number from PDF info. If not available, abort. This is caused by
                // requesting a page that does not exist.
                PageInfo pageInfo = pdfInfo.Pages.SingleOrDefault(x => x.Number == pageNumber);
                if(pageInfo == null)
                {
                    return null;
                }

                // We only support media box (as opposed to clip, bleed, art, etc.) If this is not available, abort.
                if(pageInfo.MediaBox == null)
                {
                    return null;
                }

                // Get the output size of the generated bitmap by applying the resize settings and media box.
                Size outputSize = (pageInfo.Rotate == -90 || pageInfo.Rotate == 90) ?
                    GetOutputSize(settings, pageInfo.MediaBox.Height,pageInfo.MediaBox.Width)
                    : GetOutputSize(settings, pageInfo.MediaBox.Width, pageInfo.MediaBox.Height) ;

                // Create default Ghostscript settings and apply the resize settings.
                GhostscriptSettings ghostscriptSettings = new GhostscriptSettings
                                                          {
                                                              GhostscriptArgument.NoPause,
                                                              GhostscriptArgument.Quiet,
                                                              GhostscriptArgument.Safer,
                                                              GhostscriptArgument.Batch,
                                                              {GhostscriptArgument.OutputDevice, "pngalpha"},
                                                              {GhostscriptArgument.MaxBitmap, 24000000},
                                                              {GhostscriptArgument.RenderingThreads, 4},
                                                              {GhostscriptArgument.GridFitTT, 0},
                                                              {GhostscriptArgument.AlignToPixels, 0}, //Subpixel rendering depends on output device... perhaps testing would help determine if 1 would be better?
                                                              {GhostscriptArgument.FirstPage, pageNumber},
                                                              {GhostscriptArgument.LastPage, pageNumber},
                                                              GhostscriptArgument.Printed,
                                                              GhostscriptArgument.PdfFitPage,
                                                              GhostscriptArgument.FixedMedia,
                                                              {GhostscriptArgument.Height, outputSize.Height},
                                                              {GhostscriptArgument.Width, outputSize.Width}
                                                          };
                ApplyResizeSettings(settings, ghostscriptSettings);

                // Have Ghostscript process the input to a PNG file with transparency.
                // The PNG will be reloaded and further processed by the resizer pipeline.
                FileInfo tempOutputPathInfo = new FileInfo(Path.GetTempFileName());
                try
                {
                    // Add output file and input file. The input file must be the very last argument.
                    ghostscriptSettings.Add(GhostscriptArgument.OutputFile, tempOutputPathInfo.FullName);
                    ghostscriptSettings.Add(tempInputPathInfo.FullName);
                    _engine.Execute(ghostscriptSettings);

                    // NOTE: Do not dispose of memory stream because it is used as the backing source for the loaded bitmap.
                    MemoryStream memoryStream = new MemoryStream((int)tempOutputPathInfo.Length);
                    using(FileStream fileStream = tempOutputPathInfo.Open(FileMode.Open))
                    {
                        StreamExtensions.CopyToStream(fileStream, memoryStream);
                    }

                    // Per ImagerResizer plugin example source code:
                    // NOTE: If the Bitmap class is used for decoding, read gdi-bugs.txt and make sure you set b.Tag to new BitmapTag(optionalPath,stream);
                    BitmapTag bitmapTag = new BitmapTag("ghostscript.png", memoryStream);
                    return new Bitmap(memoryStream) { Tag = bitmapTag };
                }
                //catch(GhostscriptException)
                //{
                //    // Conversion failed
                //    return null; //or maybe we should show details? If it's a valid PDF?
                //}
                finally
                {
                    tempOutputPathInfo.Delete();
                }
            }
            finally
            {
                tempInputPathInfo.Delete();
            }
        }
Пример #17
0
        public string Execute(GhostscriptSettings settings)
        {
            if(settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            // Flatten settings into Ghostscript arguments
            string[] arguments = GetArguments(settings);

            // Use callback handlers to capture stdout and stderr.
            // NOTE: Delegates do not need to be pinned.
            StringBuilder outputBuilder = new StringBuilder();
            StringBuilder errorBuilder = new StringBuilder();
            GhostscriptMessageEventHandler outputHandler = (i, s, l) => HandleOutputMessage(outputBuilder, s, l);
            GhostscriptMessageEventHandler errorHandler = (i, s, l) => HandleOutputMessage(errorBuilder, s, l);
            GhostscriptMessageEventHandler inputHandler = (i, s, l) => l;

            // NOTE: Ghostscript supports only one instance per process
            int result;
            lock(_syncObject)
            {
                // Create a new instance of Ghostscript. This instance is passed to most other gsapi functions.
                // The caller_handle will be provided to callback functions.
                IntPtr instance;
                GhostscriptNativeMethods.NewInstance(out instance, IntPtr.Zero);

                // Set the callback functions for stdio.
                GhostscriptNativeMethods.SetMessageHandlers(instance, inputHandler, outputHandler, errorHandler);

                // Initialise the interpreter.
                // This calls gs_main_init_with_args() in imainarg.c. See below for return codes.
                // The arguments are the same as the "C" main function: argv[0] is ignored and the user supplied arguments are
                // argv[1] to argv[argc-1].
                result = GhostscriptNativeMethods.InitializeWithArguments(instance, arguments.Length, arguments);

                // Exit the interpreter.
                // This must be called on shutdown if gsapi_init_with_args() has been called, and just before gsapi_delete_instance().
                GhostscriptNativeMethods.Exit(instance);

                // Destroy an instance of Ghostscript.
                // Before you call this, Ghostscript must have finished.
                // If Ghostscript has been initialised, you must call gsapi_exit before gsapi_delete_instance.
                GhostscriptNativeMethods.DeleteInstance(instance);
            }

            // Check for errors. Zero and e_Quit(-101) are not errors.
            string output = outputBuilder.ToString();
            if(result != 0 && result != -101)
            {
                // Use error as message if output is empty
                string error = errorBuilder.ToString();
                if(string.IsNullOrEmpty(output))
                {
                    output = error;
                }

                GhostscriptException exception = new GhostscriptException(output);
                exception.Data["args"] = arguments;
                exception.Data["stderr"] = error;
                throw exception;
            }

            // Return the output message
            return output;
        }
Пример #18
0
 private static string[] GetArguments(GhostscriptSettings settings)
 {
     // Flatten Ghostscript engine settings into string array
     // - first argument ignore (argv[0])
     // - input path as last argument
     string[] arguments;
     List<string> argumentItems = new List<string> { string.Empty };
     foreach(string key in settings.AllKeys)
     {
         string[] values = settings.GetValues(key);
         if(values == null)
         {
             // No value
             argumentItems.Add(key);
         }
         else
         {
             IEnumerable<string> items = values.Select(value => string.Concat(key, value));
             argumentItems.AddRange(items);
         }
     }
     arguments = argumentItems.ToArray();
     return arguments;
 }
Пример #19
0
        public override Bitmap DecodeStream(Stream s, ResizeSettings settings, string optionalPath)
        {
            if (string.IsNullOrEmpty(optionalPath))
            {
                if (s.CanSeek)
                {
                    //Check the header instead if no filename is present.
                    byte[] header = new byte[4];
                    s.Read(header, 0, 4);
                    bool isPdf = (header[0] == '%' && header[1] == 'P' && header[2] == 'D' && header[3] == 'F');
                    s.Seek(-4, SeekOrigin.Current); //Restore position.

                    if (!isPdf)
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null); //It's not seekable, we can't check the header.
                }
            }
            else if (!_supportedExtensions.Contains(Path.GetExtension(optionalPath), StringComparer.OrdinalIgnoreCase))
            {
                // Not a supported format
                return(null);
            }

            // Do not allow decoding if Ghostscript there are issues with performing this decode
            IIssue[] issues = GetIssues().ToArray();
            if (issues.Length > 0)
            {
                string message = string.Join(Environment.NewLine, issues.Select(x => x.Summary).ToArray());
                throw new InvalidOperationException(message);
            }

            // Must write input stream to a temporary file for Ghostscript to process.
            FileInfo tempInputPathInfo = new FileInfo(Path.GetTempFileName());

            try
            {
                using (FileStream tempInputStream = tempInputPathInfo.Create())
                {
                    StreamExtensions.CopyToStream(s, tempInputStream);
                }

                // Get information about the PDF such as page count and media boxes
                // Although this creates a second trip to Ghostscript engine, it's not possible to generate a rendered image in exact
                // dimensions requested. Skipping this step will cause a rendered image, of some size, to be resized further.
                PdfInfo pdfInfo = GetPdfInfo(tempInputPathInfo.FullName);

                // Extract the requested page number from resize settings, or default to first page
                int pageNumber = settings.GetValueOrDefault("page", 1);

                // Try to get the page number from PDF info. If not available, abort. This is caused by
                // requesting a page that does not exist.
                PageInfo pageInfo = pdfInfo.Pages.SingleOrDefault(x => x.Number == pageNumber);
                if (pageInfo == null)
                {
                    return(null);
                }

                // We only support media box (as opposed to clip, bleed, art, etc.) If this is not available, abort.
                if (pageInfo.MediaBox == null)
                {
                    return(null);
                }

                // Get the output size of the generated bitmap by applying the resize settings and media box.
                Size outputSize = (pageInfo.Rotate == -90 || pageInfo.Rotate == 90) ?
                                  GetOutputSize(settings, pageInfo.MediaBox.Height, pageInfo.MediaBox.Width)
                    : GetOutputSize(settings, pageInfo.MediaBox.Width, pageInfo.MediaBox.Height);



                // Create default Ghostscript settings and apply the resize settings.
                GhostscriptSettings ghostscriptSettings = new GhostscriptSettings
                {
                    GhostscriptArgument.NoPause,
                    GhostscriptArgument.Quiet,
                    GhostscriptArgument.Safer,
                    GhostscriptArgument.Batch,
                    { GhostscriptArgument.OutputDevice, "pngalpha" },
                    { GhostscriptArgument.MaxBitmap, 24000000 },
                    { GhostscriptArgument.RenderingThreads, 4 },
                    { GhostscriptArgument.GridFitTT, 0 },
                    { GhostscriptArgument.AlignToPixels, 0 },                                         //Subpixel rendering depends on output device... perhaps testing would help determine if 1 would be better?
                    { GhostscriptArgument.FirstPage, pageNumber },
                    { GhostscriptArgument.LastPage, pageNumber },
                    GhostscriptArgument.Printed,
                    GhostscriptArgument.PdfFitPage,
                    GhostscriptArgument.FixedMedia,
                    { GhostscriptArgument.Height, outputSize.Height },
                    { GhostscriptArgument.Width, outputSize.Width }
                };
                ApplyResizeSettings(settings, ghostscriptSettings);

                // Have Ghostscript process the input to a PNG file with transparency.
                // The PNG will be reloaded and further processed by the resizer pipeline.
                FileInfo tempOutputPathInfo = new FileInfo(Path.GetTempFileName());
                try
                {
                    // Add output file and input file. The input file must be the very last argument.
                    ghostscriptSettings.Add(GhostscriptArgument.OutputFile, tempOutputPathInfo.FullName);
                    ghostscriptSettings.Add(tempInputPathInfo.FullName);
                    _engine.Execute(ghostscriptSettings);

                    // NOTE: Do not dispose of memory stream because it is used as the backing source for the loaded bitmap.
                    MemoryStream memoryStream = new MemoryStream((int)tempOutputPathInfo.Length);
                    using (FileStream fileStream = tempOutputPathInfo.Open(FileMode.Open))
                    {
                        StreamExtensions.CopyToStream(fileStream, memoryStream);
                    }

                    // Per ImagerResizer plugin example source code:
                    // NOTE: If the Bitmap class is used for decoding, read gdi-bugs.txt and make sure you set b.Tag to new BitmapTag(optionalPath,stream);
                    BitmapTag bitmapTag = new BitmapTag("ghostscript.png", memoryStream);
                    return(new Bitmap(memoryStream)
                    {
                        Tag = bitmapTag
                    });
                }
                //catch(GhostscriptException)
                //{
                //    // Conversion failed
                //    return null; //or maybe we should show details? If it's a valid PDF?
                //}
                finally
                {
                    tempOutputPathInfo.Delete();
                }
            }
            finally
            {
                tempInputPathInfo.Delete();
            }
        }