Represents a Ghostscript version information.
예제 #1
0
        public void Start()
        {
            int desired_x_dpi = 96;
            int desired_y_dpi = 96;

            string inputPdfPath = @"E:\gss_test\test.pdf";
            string outputPath = @"E:\gss_test\output\";

            _lastInstalledVersion = GhostscriptVersionInfo.GetLastInstalledVersion();

            _rasterizer = new GhostscriptRasterizer();

            /* MemoryStream usage sample
              
            byte[] buffer = File.ReadAllBytes(inputPdfPath);
            MemoryStream ms = new MemoryStream(buffer);

            _rasterizer.Open(ms);

            */

            _rasterizer.Open(inputPdfPath, _lastInstalledVersion, false);

            for (int pageNumber = 1; pageNumber <= _rasterizer.PageCount; pageNumber++)
            {
                string pageFilePath = Path.Combine(outputPath, "Page-" + pageNumber.ToString() + ".png");

                Image img = _rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber);
                img.Save(pageFilePath, ImageFormat.Png);
                
                Console.WriteLine(pageFilePath);
            }
        }
        protected List<string> PdfToImages(string file, string outputDir, int dpi)
        {
            try
            {
                List<string> fileNames = new List<string>();

                Ghostscript.NET.Rasterizer.GhostscriptRasterizer rasterizer = null;

                string gsDllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Binaries\gsdll32.dll");
                GhostscriptVersionInfo gvi = new GhostscriptVersionInfo(gsDllPath);

                using (rasterizer = new Ghostscript.NET.Rasterizer.GhostscriptRasterizer())
                {
                    rasterizer.Open(file, gvi, true);

                    for (int i = 1; i <= rasterizer.PageCount; i++)
                    {
                        System.Drawing.Image img = rasterizer.GetPage(dpi, dpi, i);
                        string fileName = Path.Combine(outputDir, string.Format("{0}.jpg", i));
                        img.Save(fileName, ImageFormat.Jpeg);
                        fileNames.Add(fileName);
                    }

                    rasterizer.Close();
                }

                return fileNames;
            }
            catch (Exception ex)
            {
                //potentially log the exception
                throw;
            }
        }
예제 #3
0
        /// <summary>
        /// Gets lastest installed Ghostscript version.
        /// </summary>
        /// <param name="licenseType">L</param>
        /// <param name="licensePriority">If there are a same verio</param>
        /// <returns>GhostscriptVersionInfo object of the last installed Ghostscript version based on priority license.</returns>
        public static GhostscriptVersionInfo GetLastInstalledVersion(GhostscriptLicense licenseType, GhostscriptLicense licensePriority)
        {
            List <GhostscriptVersionInfo> gsVerList = GetInstalledVersions(licenseType);

            int versionsCount = gsVerList.Count;

            if (versionsCount == 1)
            {
                return(gsVerList[0]);
            }
            else if (versionsCount > 1)
            {
                GhostscriptVersionInfo lastGsVer = gsVerList[0];

                for (int index = 1; index < versionsCount; index++)
                {
                    GhostscriptVersionInfo gs = gsVerList[index];
                    if (gs.Version > lastGsVer.Version)
                    {
                        if (gs.LicenseType == licensePriority)
                        {
                            lastGsVer = gsVerList[index];
                        }
                    }
                }

                return(lastGsVer);
            }

            return(null);
        }
        public void Start()
        {
            // there can be multiple Ghostscript versions installed on the system
            // and we can choose which one we will use. In this sample we will use
            // the last installed Ghostscript version. We can choose if we want to
            // use GPL or AFPL (commercial) version of the Ghostscript. By setting
            // the parameters below we told that we want to fetch the last version
            // of the GPL or AFPL Ghostscript and if both are available we prefer
            // to use GPL version.

            _lastInstalledVersion =
                GhostscriptVersionInfo.GetLastInstalledVersion(
                        GhostscriptLicense.GPL | GhostscriptLicense.AFPL,
                        GhostscriptLicense.GPL);

            // create a new instance of the viewer
            _viewer = new GhostscriptViewer();

            // set the display update interval to 10 times per second. This value
            // is milliseconds based and updating display every 100 milliseconds
            // is optimal value. The smaller value you set the rasterizing will
            // take longer as DisplayUpdate event will be raised more often.
            _viewer.ProgressiveUpdateInterval = 100;

            // attach three main viewer events
            _viewer.DisplaySize += new GhostscriptViewerViewEventHandler(_viewer_DisplaySize);
            _viewer.DisplayUpdate += new GhostscriptViewerViewEventHandler(_viewer_DisplayUpdate);
            _viewer.DisplayPage += new GhostscriptViewerViewEventHandler(_viewer_DisplayPage);

            // open PDF file using the last Ghostscript version. If you want to use
            // multiple viewers withing a single process then you need to pass 'true'
            // value as the last parameter of the method below in order to tell the
            // viewer to load Ghostscript from the memory and not from the disk.
            _viewer.Open("E:\test\test.pdf",_lastInstalledVersion, false);
        }
예제 #5
0
        public void Process(GhostscriptVersionInfo ghostscriptVersion, bool fromMemory, GhostscriptStdIO stdIO_callback)
        {
            if (ghostscriptVersion == null)
            {
                throw new ArgumentNullException("ghostscriptVersion");
            }

            using (GhostscriptProcessor processor = new GhostscriptProcessor(ghostscriptVersion, fromMemory))
            {
                processor.StartProcessing(this.GetSwitches(), stdIO_callback);
            }
        }
예제 #6
0
        /// <summary>
        /// Loads Ghostscript library from the GhostscriptVersionInfo object with ability to load it from the memory and not from the disk.
        /// </summary>
        /// <param name="version">GhostscriptVersionInfo object.</param>
        /// <param name="fromMemory"></param>
        public GhostscriptLibrary(GhostscriptVersionInfo version, bool fromMemory)
        {
            _version          = version;
            _loadedFromMemory = fromMemory;

            if (fromMemory)
            {
                _library = new DynamicNativeLibrary(File.ReadAllBytes(version.DllPath));
            }
            else
            {
                _library = new DynamicNativeLibrary(version.DllPath);
            }

            this.Initialize();
        }
        /// <summary>
        /// Gets top installed Ghostscript version.
        /// </summary>
        /// <param name="licenseType">Serch for the specific Ghostscript version based on the Ghostscript license.</param>
        /// <param name="licensePriority">If there are both license types installed, which one should have the prilorty.</param>
        /// <returns>GhostscriptVersionInfo object of the last installed Ghostscript version based on priority license.</returns>
        public static GhostscriptVersionInfo GetLastInstalledVersion(GhostscriptLicense licenseType, GhostscriptLicense licensePriority)
        {
            // gets installed Ghostscript versions list
            List <GhostscriptVersionInfo> gsVerList = GetInstalledVersions(licenseType);

            // cache the list count
            int versionsCount = gsVerList.Count;

            // check if there is only 1 version of the Ghostscript installed
            // if yes, then we don't need a deeper search
            if (versionsCount == 1)
            {
                // simply return the first one
                return(gsVerList[0]);
            }
            else if (versionsCount > 1)
            {
                // get the first one
                GhostscriptVersionInfo lastGsVer = gsVerList[0];

                // loop through all others
                for (int index = 1; index < versionsCount; index++)
                {
                    // get one from the list
                    GhostscriptVersionInfo gs = gsVerList[index];

                    // compare if it's a newer version
                    if (gs.Version > lastGsVer.Version)
                    {
                        // check if this version has license with larger priority
                        if (gs.LicenseType == licensePriority)
                        {
                            // set top version
                            lastGsVer = gsVerList[index];
                        }
                    }
                }

                // return top GhostscriptVersionInfo instance
                return(lastGsVer);
            }

            // inform the user that we didn't find Ghostscript installed on this system
            throw new GhostscriptLibraryNotInstalledException();
        }
예제 #8
0
        public PdfRasterizer(string inputPdfPath, int pointsPerInch)
        {
            _pointsPerInch = pointsPerInch;
            // Extract info from pdf using iTextSharp
            try
            {
            using (Stream newpdfStream = new FileStream(inputPdfPath, FileMode.Open, FileAccess.Read))
            {
                using (PdfReader pdfReader = new PdfReader(newpdfStream))
                {
                    int numPagesToUse = pdfReader.NumberOfPages;
                    for (int pageNum = 1; pageNum <= numPagesToUse; pageNum++)
                    {
                        iTextSharp.text.Rectangle pageRect = pdfReader.GetPageSize(pageNum);
                        _pageSizes.Add(pageRect);
                        int pageRot = pdfReader.GetPageRotation(pageNum);
                        _pageRotationInfo.Add(pageRot);
                    }
                }
            }
            }
            catch (Exception excp)
            {
                logger.Error("Cannot open PDF with iTextSharp {0} excp {1}", inputPdfPath, excp.Message);
            }

            _lastInstalledVersion =
                GhostscriptVersionInfo.GetLastInstalledVersion(
                        GhostscriptLicense.GPL | GhostscriptLicense.AFPL,
                        GhostscriptLicense.GPL);

            try
            {
                _rasterizer.Open(inputPdfPath.Replace("/",@"\"), _lastInstalledVersion, false);
            }
            catch (Exception excp)
            {
                logger.Error("Cannot open PDF with ghostscript {0} excp {1}", inputPdfPath, excp.Message);
            }

            _inputPdfPath = inputPdfPath;
        }
        /// <summary>
        /// Initializes a new instance of the Ghostscript.NET.GhostscriptLibrary class
        /// from the GhostscriptVersionInfo object.
        /// </summary>
        /// <param name="version">GhostscriptVersionInfo instance that tells which Ghostscript library to use.</param>
        /// <param name="fromMemory">Tells if the Ghostscript should be loaded from the memory or directly from the disk.</param>
        public GhostscriptLibrary(GhostscriptVersionInfo version, bool fromMemory)
        {
            // check if Ghostscript version is specified
            if (version == null)
            {
                throw new ArgumentNullException("version");
            }

            // check if specified Ghostscript native library exist on the disk
            if (!File.Exists(version.DllPath))
            {
                throw new DllNotFoundException("Ghostscript native library could not be found.");
            }

            _version          = version;
            _loadedFromMemory = fromMemory;

            // check if library is compatibile with a running process
            if (Environment.Is64BitProcess != NativeLibraryHelper.Is64BitLibrary(version.DllPath))
            {
                // throw friendly gsdll incompatibility message
                this.ThrowIncompatibileNativeGhostscriptLibraryException();
            }

            // check wether we need to load Ghostscript native library from the memory or a disk
            if (fromMemory)
            {
                // load native Ghostscript library into the memory
                byte[] buffer = File.ReadAllBytes(version.DllPath);

                // create DynamicNativeLibrary instance from the memory buffer
                _library = new DynamicNativeLibrary(buffer);
            }
            else
            {
                // create DynamicNativeLibrary instance from the local disk file
                _library = new DynamicNativeLibrary(version.DllPath);
            }

            // get and map native library symbols
            this.Initialize();
        }
예제 #10
0
        internal List<string> CreateImagesFromPDF(string fileName)
        {
            const int desired_x_dpi = 300;
            const int desired_y_dpi = 300;

            //string inputPdfPath = @"C:\Users\mkrue\Desktop\PDFImages\2nhruzqyeft.pdf";
            //string outputPath = @"C:\Users\mkrue\Desktop\PDFImages\";

            string outputPath = AppSettings.UploadFolderPhysicalPath;

            FileInfo fi = new FileInfo(fileName);
            var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);


            _lastInstalledVersion =
                GhostscriptVersionInfo.GetLastInstalledVersion(
                        GhostscriptLicense.GPL | GhostscriptLicense.AFPL,
                        GhostscriptLicense.GPL);

            _rasterizer = new GhostscriptRasterizer();

            _rasterizer.Open(fi.FullName, _lastInstalledVersion, false);

            imageNames = new List<string>();

            //Create a jpeg for each page in the pdf.  File name will be PDF file name + page number
            for (int pageNumber = 1; pageNumber <= _rasterizer.PageCount; pageNumber++)
            {
                string pageFilePath = Path.Combine(outputPath, fileNameWithoutExt + "-" + pageNumber + ".jpeg");

                Image img = _rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber);
                img.Save(pageFilePath, ImageFormat.Jpeg);
                imageNames.Add(fileNameWithoutExt + "-" + pageNumber + ".jpeg");
            }

            return imageNames;
        }
        /// <summary>
        /// Returns Ink coverage for specified page range.
        /// The result is ink coverage for the CMYK inks, separately for each single page (for RGB colors, it does a silent conversion to CMYK color space internally).
        /// This function is supported only in Ghostscript v9.05 or newer.
        /// </summary>
        /// <param name="stream">Stream representing PDF document.</param>
        /// <param name="firstPage">Designated start page of the document. Pages of all documents in PDF collections are numbered sequentionally.</param>
        /// <param name="lastPage">Designated end page of the document. Pages of all documents in PDF collections are numbered sequentionally.</param>
        /// <returns>Dictionary of page numbers with ink coverage.</returns>
        public static Dictionary <int, GhostscriptPageInkCoverage> GetInkCoverage(Stream stream, int firstPage, int lastPage)
        {
            GhostscriptVersionInfo gvi = GhostscriptVersionInfo.GetLastInstalledVersion(GhostscriptLicense.GPL | GhostscriptLicense.AFPL, GhostscriptLicense.GPL);

            return(GetInkCoverage(stream, firstPage, lastPage, gvi));
        }
예제 #12
0
        /// <summary>
        /// Returns Ink coverage for specified page range.
        /// The result is ink coverage for the CMYK inks, separately for each single page (for RGB colors, it does a silent conversion to CMYK color space internally).
        /// This function is supported only in Ghostscript v9.05 or newer.
        /// </summary>
        /// <param name="stream">Stream representing PDF document.</param>
        /// <param name="firstPage">Designated start page of the document. Pages of all documents in PDF collections are numbered sequentionally.</param>
        /// <param name="lastPage">Designated end page of the document. Pages of all documents in PDF collections are numbered sequentionally.</param>
        /// <param name="versionInfo">GhostscriptVersionInfo instance that tells which Ghostscript library to use.</param>
        /// <returns>A dictionary of a page numbers with the ink coverage.</returns>
        public static Dictionary<int, GhostscriptPageInkCoverage> GetInkCoverage(Stream stream, int firstPage, int lastPage, GhostscriptVersionInfo versionInfo)
        {
            FileCleanupHelper cleanupHelper = new FileCleanupHelper();

            try
            {
                string path = StreamHelper.WriteToTemporaryFile(stream);
                cleanupHelper.Add(path);

                return GetInkCoverage(path, firstPage, lastPage, versionInfo);
            }
            finally
            {
                cleanupHelper.Cleanup();
            }
        }
        /// <summary>
        /// Returns Ink coverage for all pages.
        /// The result is ink coverage for the CMYK inks, separately for each single page (for RGB colors, it does a silent conversion to CMYK color space internally).
        /// This function is supported only in Ghostscript v9.05 or newer.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="versionInfo">GhostscriptVersionInfo instance that tells which Ghostscript library to use.</param>
        /// <returns>A dictionary of a page numbers with the ink coverage.</returns>
        public static Dictionary <int, GhostscriptPageInkCoverage> GetInkCoverage(string path, GhostscriptVersionInfo versionInfo)
        {
            GhostscriptVersionInfo gvi = GhostscriptVersionInfo.GetLastInstalledVersion(GhostscriptLicense.GPL | GhostscriptLicense.AFPL, GhostscriptLicense.GPL);

            return(GetInkCoverage(path, 0, 0, versionInfo));
        }
        /// <summary>
        /// Returns Ink coverage for specified page range.
        /// The result is ink coverage for the CMYK inks, separately for each single page (for RGB colors, it does a silent conversion to CMYK color space internally).
        /// This function is supported only in Ghostscript v9.05 or newer.
        /// </summary>
        /// <param name="path">PDF file path.</param>
        /// <param name="firstPage">Designated start page of the document. Pages of all documents in PDF collections are numbered sequentionally.</param>
        /// <param name="lastPage">Designated end page of the document. Pages of all documents in PDF collections are numbered sequentionally.</param>
        /// <param name="versionInfo">GhostscriptVersionInfo instance that tells which Ghostscript library to use.</param>
        /// <returns>A dictionary of a page numbers with the ink coverage.</returns>
        public static Dictionary <int, GhostscriptPageInkCoverage> GetInkCoverage(string path, int firstPage, int lastPage, GhostscriptVersionInfo versionInfo)
        {
            GhostscriptPipedOutput gsPipedOutput = new GhostscriptPipedOutput();
            string outputPipeHandle = "%handle%" + int.Parse(gsPipedOutput.ClientHandle).ToString("X2");

            List <string> switches = new List <string>();

            switches.Add("-empty");
            switches.Add("-q");

            if (firstPage != 0 && lastPage != 0)
            {
                switches.Add("-dFirstPage=" + firstPage.ToString());
                switches.Add("-dLastPage=" + lastPage.ToString());
            }

            switches.Add("-o" + outputPipeHandle);
            switches.Add("-sDEVICE=inkcov");
            switches.Add(path);

            GhostscriptProcessor proc = new GhostscriptProcessor(versionInfo, false);

            proc.StartProcessing(switches.ToArray(), null);

            byte[] data = gsPipedOutput.Data;

            gsPipedOutput.Dispose(); gsPipedOutput = null;

            string output = Encoding.ASCII.GetString(data);

            if (output.Length > 0)
            {
                Dictionary <int, GhostscriptPageInkCoverage> result = new Dictionary <int, GhostscriptPageInkCoverage>();

                string[] outputLines = output.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

                int pageNumber = firstPage == 0 ? 1 : firstPage;

                foreach (string line in outputLines)
                {
                    GhostscriptPageInkCoverage pic = new GhostscriptPageInkCoverage();
                    pic.Page    = pageNumber;
                    pic.IsValid = false;

                    string[] lineParts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    if (lineParts.Length == 6)
                    {
                        pic.C = Math.Round(float.Parse(lineParts[0], CultureInfo.InvariantCulture) * 100, 4);
                        pic.M = Math.Round(float.Parse(lineParts[1], CultureInfo.InvariantCulture) * 100, 4);
                        pic.Y = Math.Round(float.Parse(lineParts[2], CultureInfo.InvariantCulture) * 100, 4);
                        pic.K = Math.Round(float.Parse(lineParts[3], CultureInfo.InvariantCulture) * 100, 4);

                        if (lineParts[5] == "OK")
                        {
                            pic.IsValid = true;
                        }
                    }

                    result.Add(pageNumber, pic);

                    pageNumber++;
                }

                return(result);
            }
            else
            {
                return(null);
            }
        }
 /// <summary>
 /// Returns Ink coverage for all pages.
 /// The result is ink coverage for the CMYK inks, separately for each single page (for RGB colors, it does a silent conversion to CMYK color space internally).
 /// This function is supported only in Ghostscript v9.05 or newer.
 /// </summary>
 public static Dictionary<int, GhostscriptPageInkCoverage> GetInkCoverage(string path)
 {
     GhostscriptVersionInfo gvi = GhostscriptVersionInfo.GetLastInstalledVersion(GhostscriptLicense.GPL | GhostscriptLicense.AFPL, GhostscriptLicense.GPL);
     gvi = new GhostscriptVersionInfo(new Version(0, 0, 0), @"F:\gs_src\ghostscript-9.10\debugbin\gsdll32.dll", null, GhostscriptLicense.GPL);
     return GetInkCoverage(path, 0, 0, gvi);
 }
        /// <summary>
        /// Returns Ink coverage for specified page range.
        /// The result is ink coverage for the CMYK inks, separately for each single page (for RGB colors, it does a silent conversion to CMYK color space internally).
        /// This function is supported only in Ghostscript v9.05 or newer.
        /// </summary>
        /// <param name="stream">Stream representing PDF document.</param>
        /// <param name="firstPage">Designated start page of the document. Pages of all documents in PDF collections are numbered sequentionally.</param>
        /// <param name="lastPage">Designated end page of the document. Pages of all documents in PDF collections are numbered sequentionally.</param>
        /// <param name="versionInfo">GhostscriptVersionInfo instance that tells which Ghostscript library to use.</param>
        /// <returns>A dictionary of a page numbers with the ink coverage.</returns>
        public static Dictionary <int, GhostscriptPageInkCoverage> GetInkCoverage(Stream stream, int firstPage, int lastPage, GhostscriptVersionInfo versionInfo)
        {
            FileCleanupHelper cleanupHelper = new FileCleanupHelper();

            try
            {
                string path = StreamHelper.WriteToTemporaryFile(stream);
                cleanupHelper.Add(path);

                return(GetInkCoverage(path, firstPage, lastPage, versionInfo));
            }
            finally
            {
                cleanupHelper.Cleanup();
            }
        }
 /// <summary>
 /// Initializes a new instance of the Ghostscript.NET.GhostscriptLibrary class
 /// from the GhostscriptVersionInfo object.
 /// </summary>
 /// <param name="version">GhostscriptVersionInfo instance that tells which Ghostscript library to use.</param>
 public GhostscriptLibrary(GhostscriptVersionInfo version) : this(version, false)
 {
 }
예제 #18
0
 public void Process(GhostscriptStdIO stdIO_callback)
 {
     this.Process(GhostscriptVersionInfo.GetLastInstalledVersion(GhostscriptLicense.GPL | GhostscriptLicense.AFPL, GhostscriptLicense.GPL),
                  true,
                  stdIO_callback);
 }
예제 #19
0
        /// <summary>
        /// Returns Ink coverage for specified page range.
        /// The result is ink coverage for the CMYK inks, separately for each single page (for RGB colors, it does a silent conversion to CMYK color space internally).
        /// This function is supported only in Ghostscript v9.05 or newer.
        /// </summary>
        /// <param name="path">PDF file path.</param>
        /// <param name="firstPage">Designated start page of the document. Pages of all documents in PDF collections are numbered sequentionally.</param>
        /// <param name="lastPage">Designated end page of the document. Pages of all documents in PDF collections are numbered sequentionally.</param>
        /// <param name="versionInfo">GhostscriptVersionInfo instance that tells which Ghostscript library to use.</param>
        /// <returns>A dictionary of a page numbers with the ink coverage.</returns>
        public static Dictionary<int, GhostscriptPageInkCoverage> GetInkCoverage(string path, int firstPage, int lastPage, GhostscriptVersionInfo versionInfo)
        {
            GhostscriptPipedOutput gsPipedOutput = new GhostscriptPipedOutput();
            string outputPipeHandle = "%handle%" + int.Parse(gsPipedOutput.ClientHandle).ToString("X2");

            List<string> switches = new List<string>();
            switches.Add("-empty");
            switches.Add("-q");

            if (firstPage != 0 && lastPage != 0)
            {
                switches.Add("-dFirstPage=" + firstPage.ToString());
                switches.Add("-dLastPage=" + lastPage.ToString());
            }

            switches.Add("-o" + outputPipeHandle);
            switches.Add("-sDEVICE=inkcov");
            switches.Add(path);

            GhostscriptProcessor proc = new GhostscriptProcessor(versionInfo, false);
            proc.StartProcessing(switches.ToArray(), null);

            byte[] data = gsPipedOutput.Data;

            gsPipedOutput.Dispose(); gsPipedOutput = null;

            string output = Encoding.ASCII.GetString(data);

            if (output.Length > 0)
            {
                Dictionary<int, GhostscriptPageInkCoverage> result = new Dictionary<int, GhostscriptPageInkCoverage>();

                string[] outputLines = output.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

                int pageNumber = firstPage == 0 ? 1 : firstPage;

                foreach(string line in outputLines)
                {
                    GhostscriptPageInkCoverage pic = new GhostscriptPageInkCoverage();
                    pic.Page = pageNumber;
                    pic.IsValid = false;

                    string[] lineParts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    if (lineParts.Length == 6)
                    {
                        pic.C = Math.Round(float.Parse(lineParts[0], CultureInfo.InvariantCulture) * 100, 2);
                        pic.M = Math.Round(float.Parse(lineParts[1], CultureInfo.InvariantCulture) * 100, 2);
                        pic.Y = Math.Round(float.Parse(lineParts[2], CultureInfo.InvariantCulture) * 100, 2);
                        pic.K = Math.Round(float.Parse(lineParts[3], CultureInfo.InvariantCulture) * 100, 2);

                        if (lineParts[5] == "OK")
                        {
                            pic.IsValid = true;
                        }
                    }

                    result.Add(pageNumber, pic);

                    pageNumber++;
                }

                return result;
            }
            else
            {
                return null; 
            }
        }
        private void SetupStationaryFields_Load(object sender, System.EventArgs e)
        {
            if (_hideform) {
                //  Me.Hide()
                loadtemplate();

                if (string.IsNullOrEmpty((string) _dtt.Select("setting = true and fieldname = 'username'")[0]["misc"])) {
                    MessageBox.Show("You have not setup this Print Document Yet.");
                    openform();
                }
                badaddress = "";
                XMLDOC = null;
                if (_loadtype == loadtype.singledoc) {
                    System.Threading.Thread x = new System.Threading.Thread(verifySingleItem);
                    x.IsBackground = false;
                    x.Start();
                } else if (_loadtype == loadtype.templatemulti) {
                    verifydocument(true);
                }
            }
            gvi = new GhostscriptVersionInfo(sDLLPath);
            rasterizer = new GhostscriptRasterizer();

            FileSystemWatcher1.Path = _path;
            if (_hideform == false) {
                startload();
            }

            updatefiles();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }
예제 #21
0
        public void Process(GhostscriptVersionInfo ghostscriptVersion, bool fromMemory, GhostscriptStdIO stdIO_callback)
        {
            if (ghostscriptVersion == null)
            {
                throw new ArgumentNullException("ghostscriptVersion");
            }

            using (GhostscriptProcessor processor = new GhostscriptProcessor(ghostscriptVersion, fromMemory))
            {
                processor.StartProcessing(this.GetSwitches(), stdIO_callback);
            }
        }
        /// <summary>
        /// Loads native Ghostscript library from the GhostscriptVersionInfo.
        /// </summary>
        /// <param name="version">GhostscriptVersionInfo object.</param>
        /// <param name="fromMemory">Load Ghostscript from the memory or directly from a disk.</param>
        public GhostscriptLibrary(GhostscriptVersionInfo version, bool fromMemory)
        {
            if (version == null)
            {
                throw new ArgumentNullException("version", "Cannot be null.");
            }

            _version = version;
            _loadedFromMemory = fromMemory;

            if (fromMemory)
            {
                _library = new DynamicNativeLibrary(File.ReadAllBytes(version.DllPath));
            }
            else
            {
                _library = new DynamicNativeLibrary(version.DllPath);
            }

            this.Initialize();
        }
예제 #23
0
        /// <summary>
        /// Returns Ink coverage for specified page range.
        /// The result is ink coverage for the CMYK inks, separately for each single page (for RGB colors, it does a silent conversion to CMYK color space internally).
        /// This function is supported only in Ghostscript v9.05 or newer.
        /// </summary>
        /// <param name="path">PDF file path.</param>
        /// <param name="firstPage">Designated start page of the document. Pages of all documents in PDF collections are numbered sequentionally.</param>
        /// <param name="lastPage">Designated end page of the document. Pages of all documents in PDF collections are numbered sequentionally.</param>
        /// <param name="versionInfo">GhostscriptVersionInfo instance that tells which Ghostscript library to use.</param>
        /// <param name="fromMemory">Whether the library should be loaded in memory</param>
        /// <returns>A dictionary of a page numbers with the ink coverage.</returns>
        public static Dictionary <int, GhostscriptPageInkCoverage> GetInkCoverage(string path, int firstPage, int lastPage, GhostscriptVersionInfo versionInfo, bool fromMemory = false)
        {
            GhostscriptProcessor proc = new GhostscriptProcessor(versionInfo, fromMemory);

            return(GetInkCoverage(path, firstPage, lastPage, new GhostscriptProcessor(versionInfo, fromMemory)));
        }
예제 #24
0
        /// <summary>
        /// Returns Ink coverage for specified page range.
        /// The result is ink coverage for the CMYK inks, separately for each single page (for RGB colors, it does a silent conversion to CMYK color space internally).
        /// This function is supported only in Ghostscript v9.05 or newer.
        /// </summary>
        /// <param name="path">PDF file path.</param>
        /// <param name="firstPage">Designated start page of the document. Pages of all documents in PDF collections are numbered sequentionally.</param>
        /// <param name="lastPage">Designated end page of the document. Pages of all documents in PDF collections are numbered sequentionally.</param>
        /// <returns>A dictionary of a page numbers with the ink coverage.</returns>
        public static Dictionary <int, GhostscriptPageInkCoverage> GetInkCoverage(string path, int firstPage, int lastPage)
        {
            GhostscriptVersionInfo gvi = GhostscriptVersionInfo.GetLastInstalledVersion();

            return(GetInkCoverage(path, firstPage, lastPage, gvi));
        }
예제 #25
0
        /// <summary>
        /// Returns Ink coverage for all pages.
        /// The result is ink coverage for the CMYK inks, separately for each single page (for RGB colors, it does a silent conversion to CMYK color space internally).
        /// This function is supported only in Ghostscript v9.05 or newer.
        /// </summary>
        /// <param name="stream">Stream representing PDF document.</param>
        /// <param name="versionInfo">GhostscriptVersionInfo instance that tells which Ghostscript library to use.</param>
        /// <returns>A dictionary of a page numbers with the ink coverage.</returns>
        public static Dictionary <int, GhostscriptPageInkCoverage> GetInkCoverage(Stream stream, GhostscriptVersionInfo versionInfo)
        {
            GhostscriptVersionInfo gvi = GhostscriptVersionInfo.GetLastInstalledVersion();

            return(GetInkCoverage(stream, 0, 0, versionInfo));
        }
예제 #26
0
 /// <summary>
 /// Returns Ink coverage for all pages.
 /// The result is ink coverage for the CMYK inks, separately for each single page (for RGB colors, it does a silent conversion to CMYK color space internally).
 /// This function is supported only in Ghostscript v9.05 or newer.
 /// </summary>
 /// <param name="stream">Stream representing PDF document.</param>
 /// <param name="versionInfo">GhostscriptVersionInfo instance that tells which Ghostscript library to use.</param>
 /// <returns>A dictionary of a page numbers with the ink coverage.</returns>
 public static Dictionary<int, GhostscriptPageInkCoverage> GetInkCoverage(Stream stream, GhostscriptVersionInfo versionInfo)
 {
     GhostscriptVersionInfo gvi = GhostscriptVersionInfo.GetLastInstalledVersion(GhostscriptLicense.GPL | GhostscriptLicense.AFPL, GhostscriptLicense.GPL);
     return GetInkCoverage(stream, 0, 0, versionInfo);
 }
        public void Generate(Indulgence indulgence, string fontsDirectory, string contentDirectory, string bkFilename,
            string pdfFilename, string imageThumbnailFileName_1, string imageThumbnailFileName_2,
            string imageThumbnailFileName_3, string imageThumbnailFileName_4)
        {
            string thumb1Filename = imageThumbnailFileName_1;
            string thumb2Filename = imageThumbnailFileName_2;
            string thumb3Filename = imageThumbnailFileName_3;
            string thumb4Filename = imageThumbnailFileName_4;

            Rectangle background = PageSize.LETTER.Rotate();
            background.BackgroundColor = new BaseColor(0, 0, 0, 0);
            Document doc = new Document(PageSize.LETTER.Rotate(), 20, 20, 0, 0); // 70, 70, 130, 70

            byte[] pdfData = null;
            using (var ms = new System.IO.MemoryStream())
            {
                var pdfWriter = PdfWriter.GetInstance(doc, ms);
                pdfWriter.PageEvent = new ParchmentPageEventHelper(_storage, contentDirectory, bkFilename);

                BaseFont uechiGothicBase = BaseFont.CreateFont(System.IO.Path.Combine(fontsDirectory, "UECHIGOT.ttf"),
                    BaseFont.CP1252, BaseFont.EMBEDDED);
                BaseFont trajanProBase =
                    BaseFont.CreateFont(System.IO.Path.Combine(fontsDirectory, "TrajanPro-Regular.otf"), BaseFont.CP1252,
                        BaseFont.EMBEDDED);
                Font uechiGothic = new Font(uechiGothicBase, 150, iTextSharp.text.Font.NORMAL, new BaseColor(139, 0, 0));

                Font trajanProConfession = new Font(trajanProBase, 45, iTextSharp.text.Font.BOLDITALIC,
                    new BaseColor(139, 0, 0));

                Font trajanProBoldSmall = new Font(trajanProBase, 24, Font.BOLD, new BaseColor(139, 54, 38));
                Font trajanProAttribution = new Font(trajanProBase, 24, iTextSharp.text.Font.NORMAL,
                    new BaseColor(139, 54, 38));

                doc.Open();

                var t = new PdfPTable(1);
                t.WidthPercentage = 100;
                var c = new PdfPCell();
                c.VerticalAlignment = Element.ALIGN_MIDDLE;
                c.MinimumHeight = doc.PageSize.Height - (doc.BottomMargin + doc.TopMargin);

                // confession
                Phrase firstLetterPhrase = new Phrase(indulgence.Confession.Substring(0, 1).ToUpper(), uechiGothic);
                Phrase confessionPhrase = new Phrase(indulgence.Confession.Substring(1), trajanProConfession);
                var confessionParagraph = new Paragraph(firstLetterPhrase);
                confessionParagraph.Add(confessionPhrase);
                confessionParagraph.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
                confessionParagraph.Leading = 45;

                // attribution
                List<Phrase> phrases = new List<Phrase>();
                phrases.Add(new Phrase("On this ", trajanProAttribution));
                phrases.Add(new Phrase(TextUtils.DayOfMonth(indulgence.DateConfessed), trajanProBoldSmall));
                phrases.Add(new Phrase(" day of ", trajanProAttribution));
                phrases.Add(new Phrase(string.Format("{0:MMMM}", indulgence.DateConfessed), trajanProBoldSmall));
                phrases.Add(new Phrase(" in the year of our Lord ", trajanProAttribution));
                phrases.Add(new Phrase(indulgence.DateConfessed.Year.ToString(), trajanProBoldSmall));
                phrases.Add(new Phrase(", ", trajanProAttribution));
                var attributionName = indulgence.Name;
                if (string.IsNullOrWhiteSpace(attributionName))
                {
                    attributionName = "An Anonymous Believer";
                }
                phrases.Add(new Phrase(attributionName, trajanProBoldSmall));
                phrases.Add(new Phrase(" selflessly gave the sum of ", trajanProAttribution));
                phrases.Add(new Phrase(string.Format("{0:c}", indulgence.AmountDonated), trajanProBoldSmall));
                phrases.Add(new Phrase(" to the deserving organisation ", trajanProAttribution));
                phrases.Add(new Phrase(indulgence.CharityName, trajanProBoldSmall));
                phrases.Add(new Phrase(" and received this plenary indulgence", trajanProAttribution));

                var attribution = new Paragraph();
                confessionParagraph.Add(Environment.NewLine);
                foreach (var phrase in phrases)
                    confessionParagraph.Add(phrase);
                attribution.Leading = 24;
                /*attribution.Insert(0, attributionName);
            attribution.Add(attributionDonation);
            attribution.Add(attributionTo);
            attribution.Add(attributionCharity);*/
                attribution.SpacingBefore = 30;
                c.AddElement(confessionParagraph);
                t.AddCell(c);
                doc.Add(t);

                doc.Close();
                pdfData = ms.ToArray();
            }

            _storage.Store(pdfFilename, pdfData, true);

            System.Drawing.Image img = null;
            using (MemoryStream pdfStream = new MemoryStream(pdfData))
            using (MemoryStream pngStream = new MemoryStream())
            {
                GhostscriptVersionInfo gvi =
                    new GhostscriptVersionInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"gsdll32.dll"));
                using (var rasterizer = new Ghostscript.NET.Rasterizer.GhostscriptRasterizer())
                {
                    rasterizer.Open(pdfStream, gvi, true);
                    rasterizer.EPSClip = false;
                    img = rasterizer.GetPage(96, 96, 1);
                    img.RotateFlip(RotateFlipType.Rotate90FlipNone);
                    img.Save(pngStream, ImageFormat.Png);
                    _storage.Store(thumb1Filename, pngStream.ToArray(), true);
                }
            }

            float ratio = (float)img.Height/(float)img.Width;
            SaveThumbnail(img, new SizeF(800, 800*ratio), thumb2Filename);
            SaveThumbnail(img, new SizeF(300, 300*ratio), thumb3Filename);
            SaveThumbnail(img, new SizeF(150, 150*ratio), thumb4Filename);

            // TODO: generate thumbnails as byte arrays and store to IFileStorage
        }
예제 #28
0
        /// <summary>
        /// Initializes a new instance of the Ghostscript.NET.GhostscriptLibrary class
        /// from the GhostscriptVersionInfo object.
        /// </summary>
        /// <param name="version">GhostscriptVersionInfo instance that tells which Ghostscript library to use.</param>
        /// <param name="fromMemory">Tells if the Ghostscript should be loaded from the memory or directly from the disk.</param>
        public GhostscriptLibrary(GhostscriptVersionInfo version, bool fromMemory)
        {
            // check if Ghostscript version is specified
            if (version == null)
            {
                throw new ArgumentNullException("version");
            }

            // check if specified Ghostscript native library exist on the disk
            if (!File.Exists(version.DllPath))
            {
                throw new DllNotFoundException("Ghostscript native library could not be found.");
            }

            _version = version;
            _loadedFromMemory = fromMemory;

            // check if library is compatibile with a running process
            if (Environment.Is64BitProcess != NativeLibraryHelper.Is64BitLibrary(version.DllPath))
            {
                // throw friendly gsdll incompatibility message
                this.ThrowIncompatibileNativeGhostscriptLibraryException();
            }

            // check wether we need to load Ghostscript native library from the memory or a disk
            if (fromMemory)
            {
                // load native Ghostscript library into the memory
                byte[] buffer = File.ReadAllBytes(version.DllPath);

                // create DynamicNativeLibrary instance from the memory buffer
                _library = new DynamicNativeLibrary(buffer);
            }
            else
            {
                // create DynamicNativeLibrary instance from the local disk file
                _library = new DynamicNativeLibrary(version.DllPath);
            }

            // get and map native library symbols
            this.Initialize();
        }
예제 #29
0
 /// <summary>
 /// Initializes a new instance of the Ghostscript.NET.GhostscriptLibrary class
 /// from the GhostscriptVersionInfo object.
 /// </summary>
 /// <param name="version">GhostscriptVersionInfo instance that tells which Ghostscript library to use.</param>
 public GhostscriptLibrary(GhostscriptVersionInfo version) : this(version, false) 
 { }
 public void Process(GhostscriptStdIO stdIO_callback)
 {
     this.Process(GhostscriptVersionInfo.GetLastInstalledVersion(),
                  true,
                  stdIO_callback);
 }
예제 #31
0
        //Methods
        //88888888888888888888888888888888888888888888888888888888888888888888888
        /// <summary>
        /// Divide the source pdf by QR code seperatorrs into chunks that
        /// can be ripped and saved from the source.
        /// </summary>
        public void FindPdfChunks()
        {
            GhostscriptVersionInfo Gvi;                 //Ghostscript info object
            GhostscriptRasterizer Rasterizer = null;    //Rasterizer
            Bitmap pageImg; //Image of one PDF page.
            string docType; //Value of document-type property in QR code json.
            int qrCodeGap = 0;

            //Only process PDFs
            if (SrcIsPdf())
            {
                try
                {
                    //TEST_OUTPUT
                    //Console.WriteLine("BASE DIRECTORY{0}{1}", AppDomain.CurrentDomain.BaseDirectory + "gsdll64.dll", Environment.NewLine);

                    //Init GhostScript and Rasterize
                    Gvi = new GhostscriptVersionInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "gsdll64.dll"));
                    Rasterizer = new GhostscriptRasterizer();
                    Rasterizer.Open(SrcPdf.FullName, Gvi, false); //Raserize the source PDF.

                    totalPages = Rasterizer.PageCount; //Total pages

                    //Loop from page 1 to page n-1 (No need to read the last page).
                    //Note: 1 page PDF will automatically be skipped.
                    for (int i = 1; i < Rasterizer.PageCount; i++)
                    {
                        pageImg = (Bitmap)Rasterizer.GetPage(72, 72, i);
                        docType = getDocTypeStr(QrReader.ReadQr(pageImg));

                        //Assert that page has a doc type
                        if (!isBlankOrNullStr(docType))
                        {
                            qrCount++; //Increment found qr code count.

                            //Throw exception if more than one QR code is found
                            //and QR Gap is less than 1 (Double Feed)
                            if (qrCount > 1 && qrCodeGap < 1)
                            {
                                throw new ApplicationException("File: " + SrcPdf.Name + " has two consecutive QR code pages. "
                                                                + "QR code double feed will result with an empty document.");
                            }
                            else
                            {
                                qrCodeGap = 0;  //Reset Gap//
                            }

                            //Console.WriteLine("DOC TYPE: {0}{1}", docType, Environment.NewLine); //TEST OUTPUT

                            //Create chunk with src page # for first page (The one after QR page) and name (srcFileName_docType_qr#).
                            initChunk(i + 1, Path.GetFileNameWithoutExtension(SrcPdf.Name) + "_" + docType + "_" + qrCount);

                            updatePreviousChunk(i - 1); //Update the previous chunks last page.
                        }
                        else if(i == 1 && isBlankOrNullStr(docType))
                        {
                            //Exit loop if the first page is not a QR code seperator page
                            Console.WriteLine("SKIPPED: {0}{1}", SrcPdf.Name, Environment.NewLine); //TEST OUTPUT
                            break;
                        }
                        else
                        {
                            //Else count as a content page
                            contentCount++;

                            //Increment QR gap//
                            qrCodeGap++;
                        }
                    }
                    //END LOOP

                    contentCount++; //Loop ends before the last page which is assumed to be content.

                    //Assert that we have some chuncks
                    if (Chunks.Count > 0)
                    {
                        //Set last page of the last chunk to the last page of the source document.
                        Chunks[Chunks.Count - 1].lastPage = Rasterizer.PageCount;
                    }
                }
                catch (Exception ex)
                {
                    throw new ApplicationException("Unable to complete chunk search. " + ex.Message);
                }
                finally
                {
                    //Dispose raterizer resource.
                    if (Rasterizer != null)
                    {
                        Rasterizer.Close();
                        Rasterizer.Dispose();
                    }
                }
            }
            //End outer if
        }