GetPage() 공개 메소드

Gets PDF page as System.Drawing.Image.
public GetPage ( int xDpi, int yDpi, int pageNumber ) : Image
xDpi int Desired x DPI.
yDpi int Desired y DPI.
pageNumber int The page number.
리턴 Image
        public void Start()
        {
            int desired_x_dpi = 300;
            int desired_y_dpi = 300;

            string inputPdfPath = @"E:\__test_data\test2.pdf";
            string outputPath = @"E:\__test_data\output\";

            using (GhostscriptRasterizer rasterizer = new GhostscriptRasterizer())
            {
                rasterizer.CustomSwitches.Add("-dUseCropBox");
                rasterizer.CustomSwitches.Add("-c");
                rasterizer.CustomSwitches.Add("[/CropBox [24 72 559 794] /PAGES pdfmark");
                rasterizer.CustomSwitches.Add("-f");

                rasterizer.Open(inputPdfPath);

                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);
                }
            }
        }
예제 #2
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\";

            using (GhostscriptRasterizer rasterizer = new GhostscriptRasterizer())
            {
                /* custom switches can be added before the file is opened
                
                rasterizer.CustomSwitches.Add("-dPrinted");
                 
                */

                byte[] buffer = File.ReadAllBytes(inputPdfPath);
                MemoryStream ms = new MemoryStream(buffer);

                rasterizer.Open(ms);

                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);
                }
            }
        }
예제 #3
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);
            }
        }
예제 #4
0
파일: Pdf.cs 프로젝트: lruckman/DRS
        public override byte[] ExtractThumbnail(int width, int? height, int pageNumber)
        {
            using (var rasterizer = new GhostscriptRasterizer())
            {
                using (var stream = new MemoryStream(Buffer))
                {
                    rasterizer.Open(stream);

                    using (var thumbnail = rasterizer
                        .GetPage(200, 200, pageNumber)
                        .ToFixedSize(width, height))
                    {
                        using (var ms = new MemoryStream())
                        {
                            thumbnail.Save(ms, ImageFormat.Png);

                            return ms.ToArray();
                        }
                    }
                }
            }
        }
예제 #5
0
        public List<string> PathToConvertedImages(string pathToPdf)
        {
            var resultImages = new List<string>();
            try
            {
                const int desiredXDpi = 96;
                const int desiredYDpi = 96;

                string inputPdfPath = pathToPdf;
                var directoryInfo = new FileInfo(inputPdfPath).Directory;
                if (directoryInfo == null) return resultImages;

                string outputPath = directoryInfo.FullName + "\\tempimages\\";
                _oldDirectory = outputPath;
                ClearTempImages();

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

                var rasterizer = new GhostscriptRasterizer();
                rasterizer.Open(inputPdfPath, lastInstalledVersion, false);

                for (int pageNumber = 1; pageNumber <= rasterizer.PageCount; pageNumber++)
                {
                    string pageFilePath = Path.Combine(outputPath + _count + @"\", @"Page-" + pageNumber + @".tiff");
                    Image img = rasterizer.GetPage(desiredXDpi, desiredYDpi, pageNumber);
                    img.Save(pageFilePath, ImageFormat.Tiff);
                    resultImages.Add(pageFilePath);
                }

            }
            catch 
            {
                //ignored    
            }

            return resultImages;
        }
예제 #6
0
        public void Sample1()
        {
            int desired_x_dpi = 96;
            int desired_y_dpi = 96;

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

            using (var rasterizer = new GhostscriptRasterizer())
            {
                rasterizer.Open(inputPdfPath);

                for (var pageNumber = 1; pageNumber <= rasterizer.PageCount; pageNumber++)
                {
                    var pageFilePath = Path.Combine(outputPath, string.Format("Page-{0}.png", pageNumber));

                    var img = rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber);
                    img.Save(pageFilePath, ImageFormat.Png);

                    Console.WriteLine(pageFilePath);
                }
            }
        }
예제 #7
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;
        }
예제 #8
0
        public static System.Drawing.Image GetImageOfPage(string fileName, int pageNum)
        {
            int desired_x_dpi = 150;
            int desired_y_dpi = 150;

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

            GhostscriptRasterizer rasterizer = new GhostscriptRasterizer();

            rasterizer.Open(fileName, lastInstalledVersion, false);

            if (pageNum > rasterizer.PageCount)
                return null;

            System.Drawing.Image img = rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNum);

            rasterizer = null;

            return img;
        }
예제 #9
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
        }
		/// <summary>
		/// Converts PDF file to OneNote by including an image for each page in the document
		/// </summary>
		/// <param name="inputFile">PDF document path</param>
		/// <param name="outputDir">Directory of the output OneNote Notebook</param>
		/// <returns></returns>
		public virtual bool ConvertPdfToOneNote(string inputFile, string outputDir)
		{
			//Get the name of the file
			string inputFileName = Path.GetFileNameWithoutExtension(inputFile);

			//Create a new OneNote Notebook
			var note = new OneNoteGenerator(outputDir);
			string notebookId = note.CreateNotebook(GetSupportedInputFormat());
			string sectionId = note.CreateSection(inputFileName, notebookId);

			using (var rasterizer = new GhostscriptRasterizer())
			{
				rasterizer.Open(inputFile);
				for (var i = 1; i <= rasterizer.PageCount; i++)
				{
					Image img = rasterizer.GetPage(160, 160, i);
					MemoryStream stream = new MemoryStream();
					img.Save(stream, ImageFormat.Png);
					img = Image.FromStream(stream);

					string pageId = note.CreatePage(String.Format("Page{0}", i), sectionId);
					note.AddImageToPage(pageId, img);
				}
			}

			note.CreateTableOfContentPage(sectionId);

			return true;
		}
예제 #11
0
        public IHttpActionResult GetAnswers(string fileKey, string name)
        {
            GhostscriptVersionInfo lastInstalledVersion = GhostscriptVersionInfo.GetLastInstalledVersion(GhostscriptLicense.GPL | GhostscriptLicense.AFPL, GhostscriptLicense.GPL);
            Dictionary<string, List<List<bool>>> answers = new Dictionary<string, List<List<bool>>>();
            byte[] file;

            string[] extentions = { ".pdf", ".jpg", ".bmp", ".jpeg", ".png", ".tiff" };
            if (!extentions.Contains(Path.GetExtension(name)))
            {
                return Ok(new { err = "noPDForIMGFile" });
            }

            using (MemoryStream m1 = new MemoryStream())
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                {
                    connection.Open();

                    using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", fileKey))
                    {
                        blobStream.CopyTo(m1);
                    }
                }

                Bitmap bitmapImg;
                if (Path.GetExtension(name) == ".pdf")
                {
                    using (GhostscriptRasterizer rasterizer = new GhostscriptRasterizer())
                    {
                        rasterizer.Open(m1, lastInstalledVersion, true);

                        //Copied, because rasterizer disposes itself
                        bitmapImg = new Bitmap(rasterizer.GetPage(300, 300, 1));
                    }
                }
                else
                {
                    bitmapImg = new Bitmap(m1);
                }

                OMRConfiguration conf = new OMRConfiguration();
                conf.AdjustmentBlock = new OMRAdjustmentBlock(1572, 3075, 425, 106);
                conf.WhiteBlock = new OMRAdjustmentBlock(1997, 3075, 106, 106);
                conf.DarkFactor = 0.90;
                conf.FillFactor = 1.60;
                conf.ImageWidth = 2182;
                conf.ImageHeight = 3210;
                conf.Blocks.Add(new OMRQuestionBlock("commonQuestions1", 387, 1059, 425, 530, 5));
                conf.Blocks.Add(new OMRQuestionBlock("commonQuestions2", 1312, 1059, 425, 530, 5));
                conf.Blocks.Add(new OMRQuestionBlock("specializedQuestions1", 387, 1798, 425, 1060, 10));
                conf.Blocks.Add(new OMRQuestionBlock("specializedQuestions2", 1312, 1798, 425, 1060, 10));

                using (var omr = new OMRReader(conf))
                using (bitmapImg)
                {
                    answers = omr.Read(bitmapImg);

                    using (Bitmap bitmapImgResized = OMRReader.ResizeImage(bitmapImg, 580, 800))
                    {
                        using (MemoryStream m2 = new MemoryStream())
                        {
                            bitmapImgResized.Save(m2, System.Drawing.Imaging.ImageFormat.Jpeg);
                            file = m2.ToArray();
                        }
                    }
                }
            }

            if (answers != null)
            {
                return Ok(new { answ = answers, file = file });
            }
            else
            {
                return Ok(new { err = "failedRecognition" });
            }
        }
예제 #12
0
        public IHttpActionResult PostExtractPages(string fileKey, string name)
        {
            using (var transaction = this.unitOfWork.BeginTransaction())
            {
                GhostscriptVersionInfo lastInstalledVersion = GhostscriptVersionInfo.GetLastInstalledVersion(GhostscriptLicense.GPL | GhostscriptLicense.AFPL, GhostscriptLicense.GPL);
                List<GvaFile> gvaFiles = new List<GvaFile>();
                int pageCount;

                using (MemoryStream m1 = new MemoryStream())
                {
                    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                    {
                        connection.Open();

                        using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", fileKey))
                        {
                            blobStream.CopyTo(m1);
                        }
                    }

                    using (GhostscriptRasterizer rasterizer = new GhostscriptRasterizer())
                    {
                        rasterizer.Open(m1, lastInstalledVersion, false);
                        pageCount = rasterizer.PageCount;

                        for (int i = 1; i <= pageCount; i++)
                        {
                            using (var ms = new MemoryStream())
                            {
                                GvaFile file = null;

                                Image img = rasterizer.GetPage(300, 300, i);
                                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                                {
                                    connection.Open();
                                    using (var blobWriter = new BlobWriter(connection))
                                    using (var stream = blobWriter.OpenStream())
                                    {
                                        stream.Write(ms.ToArray(), 0, (int)ms.Length);

                                        file = new GvaFile()
                                        {
                                            Filename = Path.Combine(Path.GetFileNameWithoutExtension(name) + "-" + i.ToString() + ".jpg"),
                                            MimeType = "image/jpeg",
                                            FileContentId = blobWriter.GetBlobKey()
                                        };

                                        this.unitOfWork.DbContext.Set<GvaFile>().Add(file);
                                        gvaFiles.Add(file);
                                    }
                                }
                            }
                        }
                    }
                }

                this.unitOfWork.Save();
                transaction.Commit();

                List<int> gvaFileIds = gvaFiles.Select(e => e.GvaFileId).ToList();

                return Ok(new { pageCount = pageCount, gvaFileIds = gvaFileIds });
            }
        }
예제 #13
0
        public IHttpActionResult GetImage(string fileKey, string name)
        {
            GhostscriptVersionInfo lastInstalledVersion = GhostscriptVersionInfo.GetLastInstalledVersion(GhostscriptLicense.GPL | GhostscriptLicense.AFPL, GhostscriptLicense.GPL);
            byte[] image;

            string[] extentions = { ".pdf", ".jpg", ".bmp", ".jpeg", ".png", ".tiff" };
            if (!extentions.Contains(Path.GetExtension(name)))
            {
                return Ok(new { err = "noPDForIMGFile" });
            }

            using (MemoryStream m1 = new MemoryStream())
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                {
                    connection.Open();

                    using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", fileKey))
                    {
                        blobStream.CopyTo(m1);
                    }
                }

                Bitmap bitmapImg;
                if (Path.GetExtension(name) == ".pdf")
                {
                    using (GhostscriptRasterizer rasterizer = new GhostscriptRasterizer())
                    {
                        rasterizer.Open(m1, lastInstalledVersion, false);

                        //Copied, because rasterizer disposes itself
                        bitmapImg = new Bitmap(rasterizer.GetPage(300, 300, 1));
                    }
                }
                else
                {
                    bitmapImg = new Bitmap(m1);
                }

                using (bitmapImg)
                {
                    using (Bitmap bitmapImgResized = OMRReader.ResizeImage(bitmapImg, 580, 800))
                    {
                        using (MemoryStream m2 = new MemoryStream())
                        {
                            bitmapImgResized.Save(m2, ImageFormat.Jpeg);
                            image = m2.ToArray();
                        }
                    }
                }
            }

            return Ok(new { image = image });
        }