コード例 #1
0
 public static void Main()
 {
     // The path to the documents directory.
     string dataDir = Path.GetFullPath("../../../Data/");
     // instantiate PdfPageEditor class to get particular page region
     Aspose.Pdf.Facades.PdfPageEditor editor = new Aspose.Pdf.Facades.PdfPageEditor();
     // bind the source PDF file
     editor.BindPdf(dataDir + "SampleInput.pdf");
     // move the origin of PDF file to particular point
     editor.MovePosition(0, 700);
     // create a memory stream object
     MemoryStream ms = new MemoryStream();
     // save the updated document to stream object
     editor.Save(ms);
     //create PdfConverter object
     PdfConverter objConverter = new PdfConverter();
     //bind input pdf file
     objConverter.BindPdf(ms);
     //set StartPage and EndPage properties to the page number to
     //you want to convert images from
     objConverter.StartPage = 1;
     objConverter.EndPage = 1;
     //Counter
     int page = 1;
     //initialize the converting process
     objConverter.DoConvert();
     //check if pages exist and then convert to image one by one
     while (objConverter.HasNextImage())
         objConverter.GetNextImage(dataDir+ "Specific_Region-Image" + page++ + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
     //close the PdfConverter object
     objConverter.Close();
     // close MemoryStream object holding the updated document
     ms.Close();
 }
コード例 #2
0
        public static void Run()
        {
            // ExStart:ConvertPDFPages
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Images();

            // Create PdfConverter object
            PdfConverter objConverter = new PdfConverter();

            // Bind input pdf file
            objConverter.BindPdf(dataDir + "ConvertPDFPages.pdf");

            // Initialize the converting process
            objConverter.DoConvert();

            objConverter.CoordinateType = PageCoordinateType.CropBox;

            // Check if pages exist and then convert to image one by one
            while (objConverter.HasNextImage())
            {
                objConverter.GetNextImage(dataDir + DateTime.Now.Ticks.ToString() + "_out_.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            }

            // Close the PdfConverter object
            objConverter.Close();
            // ExEnd:ConvertPDFPages
        }
コード例 #3
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Images();

            //create PdfConverter object
            PdfConverter objConverter = new PdfConverter();

            //bind input pdf file
            objConverter.BindPdf(dataDir+ "ConvertPDFPages.pdf");

            //initialize the converting process
            objConverter.DoConvert();

            objConverter.CoordinateType = PageCoordinateType.CropBox;

            //check if pages exist and then convert to image one by one
            while (objConverter.HasNextImage())
                objConverter.GetNextImage(dataDir+ DateTime.Now.Ticks.ToString() + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

            //close the PdfConverter object
            objConverter.Close();
 
            
        }
コード例 #4
0
        internal void DoSplit()
        {
            string[] files       = Directory.GetFiles(sPath, "*.pdf", SearchOption.AllDirectories);
            int      fileCount   = files.Length;
            int      fileCounter = 0;

            foreach (string sourceFile in files)
            {
                Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(sourceFile);
                //Create a PdfConverter object
                PdfConverter converter = new PdfConverter();
                //Bind the input PDF file
                converter.BindPdf(sourceFile);
                // Specify the start page to be processed
                converter.StartPage = 1;
                // Specify the end page for processing
                converter.EndPage = pdfDocument.Pages.Count;
                // Create a Resolution object to specify the resolution of resultant image
                converter.Resolution = new Aspose.Pdf.Devices.Resolution(300);
                //Initialize the convertion process
                converter.DoConvert();

                string docPath = Path.Combine(Path.GetDirectoryName(sourceFile),
                                              Path.GetFileNameWithoutExtension(sourceFile) + ".docx");
                Aspose.Words.Document doc     = new Aspose.Words.Document();
                DocumentBuilder       builder = new DocumentBuilder(doc);

                int pageCount = 0;
                //Check if pages exist and then convert to image one by one
                while (converter.HasNextImage())
                {
                    pageCount++;
                    string filePath = Path.Combine(Path.GetDirectoryName(sourceFile),
                                                   Path.GetFileNameWithoutExtension(sourceFile) + "_" + pageCount.ToString() + ".png");
                    using (MemoryStream imageStream = new MemoryStream())
                    {
                        converter.GetNextImage(imageStream, System.Drawing.Imaging.ImageFormat.Png);
                        imageStream.Position = 0;
                        System.IO.File.WriteAllBytes(filePath, imageStream.ToArray());
                    }
                    builder.InsertImage(filePath);
                }
                // Close the PdfConverter instance and release the resources
                doc.Save(docPath);
                converter.Close();
                // Close the stream holding the image object
                fileCounter++;
                Program.mainWindow.updateProgress(Convert.ToInt32(Math.Floor(Convert.ToDouble(fileCounter) * (100 / Convert.ToDouble(fileCount)))));
            }

            Program.mainWindow.updateProgress(100);
        }
コード例 #5
0
        public static void Run()
        {
            // ExStart:ConvertPageRegion
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Images();

            // Instantiate PdfPageEditor class to get particular page region
            Aspose.Pdf.Facades.PdfPageEditor editor = new Aspose.Pdf.Facades.PdfPageEditor();
            // Bind the source PDF file
            editor.BindPdf(dataDir + "Convert-PageRegion.pdf");
            // Move the origin of PDF file to particular point
            editor.MovePosition(0, 700);
            // Create a memory stream object
            MemoryStream ms = new MemoryStream();

            // Save the updated document to stream object
            editor.Save(ms);
            // Create PdfConverter object
            PdfConverter objConverter = new PdfConverter();

            // Bind input pdf file
            objConverter.BindPdf(ms);
            // Set StartPage and EndPage properties to the page number to
            // You want to convert images from
            objConverter.StartPage = 1;
            objConverter.EndPage   = 1;
            // Counter
            int page = 1;

            // Initialize the converting process
            objConverter.DoConvert();
            // Check if pages exist and then convert to image one by one
            while (objConverter.HasNextImage())
            {
                objConverter.GetNextImage(dataDir + "Specific_Region-Image" + page++ + "_out_.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            // Close the PdfConverter object
            objConverter.Close();
            // Close MemoryStream object holding the updated document
            ms.Close();
            // ExEnd:ConvertPageRegion
        }
コード例 #6
0
        public static void Main()
        {
            // The path to the documents directory.
            string dataDir = Path.GetFullPath("../../../Data/");
            //create PdfConverter object
            PdfConverter objConverter = new PdfConverter();

            //bind input pdf file
            objConverter.BindPdf(dataDir+ "input.pdf");

            //initialize the converting process
            objConverter.DoConvert();
            objConverter.ShowHiddenAreas = true;

            //check if pages exist and then convert to image one by one
            while (objConverter.HasNextImage())
                objConverter.GetNextImage(dataDir+ DateTime.Now.Ticks.ToString() + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

            //close the PdfConverter object
            objConverter.Close();
        }
        public static void Run()
        {
            //ExStart:ExportPDFPagesToImagesAndRecognizeBarCode
            // For complete examples and data files, please go to https://github.com/aspose-barcode/Aspose.BarCode-for-.NET

            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_TechnicalArticles();

            try
            {
                Document pdfDocument = new Document(dataDir + "document.pdf");
                int      pageCount   = pdfDocument.Pages.Count;
                for (var i = 1; i <= pageCount; i++)
                {
                    var converter = new PdfConverter();
                    converter.BindPdf(dataDir + @"document.pdf");
                    converter.StartPage = i;
                    converter.EndPage   = i;
                    converter.DoConvert();
                    MemoryStream stream = new MemoryStream();
                    converter.GetNextImage(stream, ImageFormat.Png);

                    using (BarCodeReader reader = new BarCodeReader(stream, DecodeType.Code93Standard))
                    {
                        foreach (BarCodeResult result in reader.ReadBarCodes())
                        {
                            Console.WriteLine("Codetext found: " + result.CodeType + ", Symbology: " + result.CodeText);
                        }
                    }
                    converter.Close();
                    converter.Dispose();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            //ExEnd:ExportPDFPagesToImagesAndRecognizeBarCode
            Console.WriteLine(Environment.NewLine + "Export PDF Pages To Images And Recognize BarCode Finished.");
        }
コード例 #8
0
        public static void Main()
        {
            // The path to the documents directory.
            string dataDir = Path.GetFullPath("../../../Data/");

            // instantiate PdfPageEditor class to get particular page region
            Aspose.Pdf.Facades.PdfPageEditor editor = new Aspose.Pdf.Facades.PdfPageEditor();
            // bind the source PDF file
            editor.BindPdf(dataDir + "SampleInput.pdf");
            // move the origin of PDF file to particular point
            editor.MovePosition(0, 700);
            // create a memory stream object
            MemoryStream ms = new MemoryStream();

            // save the updated document to stream object
            editor.Save(ms);
            //create PdfConverter object
            PdfConverter objConverter = new PdfConverter();

            //bind input pdf file
            objConverter.BindPdf(ms);
            //set StartPage and EndPage properties to the page number to
            //you want to convert images from
            objConverter.StartPage = 1;
            objConverter.EndPage   = 1;
            //Counter
            int page = 1;

            //initialize the converting process
            objConverter.DoConvert();
            //check if pages exist and then convert to image one by one
            while (objConverter.HasNextImage())
            {
                objConverter.GetNextImage(dataDir + "Specific_Region-Image" + page++ + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            //close the PdfConverter object
            objConverter.Close();
            // close MemoryStream object holding the updated document
            ms.Close();
        }
コード例 #9
0
        public string ExtactImagesFromFile(EmpModel model)
        {
            try
            {
                string LData = "PExpY2Vuc2U+CjxEYXRhPgo8TGljZW5zZWRUbz5BdmVQb2ludDwvTGljZW5zZWRUbz4KPEVtYWlsVG8+aXRfYmlsbGluZ0BhdmVwb2ludC5jb208L0VtYWlsVG8+CjxMaWNlbnNlVHlwZT5EZXZlbG9wZXIgT0VNPC9MaWNlbnNlVHlwZT4KPExpY2Vuc2VOb3RlPkxpbWl0ZWQgdG8gMSBkZXZlbG9wZXIsIHVubGltaXRlZCBwaHlzaWNhbCBsb2NhdGlvbnM8L0xpY2Vuc2VOb3RlPgo8T3JkZXJJRD4xOTA1MjAwNzE1NDY8L09yZGVySUQ+CjxVc2VySUQ+MTU0ODI2PC9Vc2VySUQ+CjxPRU0+VGhpcyBpcyBhIHJlZGlzdHJpYnV0YWJsZSBsaWNlbnNlPC9PRU0+CjxQcm9kdWN0cz4KPFByb2R1Y3Q+QXNwb3NlLlRvdGFsIGZvciAuTkVUPC9Qcm9kdWN0Pgo8L1Byb2R1Y3RzPgo8RWRpdGlvblR5cGU+RW50ZXJwcmlzZTwvRWRpdGlvblR5cGU+CjxTZXJpYWxOdW1iZXI+Y2JmMzVkNWYtOWE2Ni00ZTI4LTg1ZGQtM2ExN2JiZTM0MTNhPC9TZXJpYWxOdW1iZXI+CjxTdWJzY3JpcHRpb25FeHBpcnk+MjAyMDA2MDQ8L1N1YnNjcmlwdGlvbkV4cGlyeT4KPExpY2Vuc2VWZXJzaW9uPjMuMDwvTGljZW5zZVZlcnNpb24+CjxMaWNlbnNlSW5zdHJ1Y3Rpb25zPmh0dHBzOi8vcHVyY2hhc2UuYXNwb3NlLmNvbS9wb2xpY2llcy91c2UtbGljZW5zZTwvTGljZW5zZUluc3RydWN0aW9ucz4KPC9EYXRhPgo8U2lnbmF0dXJlPnpqZDMrdWgzNTdiZHhqR3JWTTZCN3I2c250TkRBTlRXU2MyQi9RWS9hdmZxTnA0VHk5Z0kxR2V1NUdOaWVwRHArY1JrRFBMdjBDRTZ2MHNjYVZwK1JNTkF5SzdiUzdzeGZSL205Z0NtekFNUlptdUxQTm1laEtZVTNvOGJWVDJvWmRJeEY2dVRTMDhIclJxUnk5SWt6c3BxYmRrcEZFY0lGcHlLbDF2NlF2UT08L1NpZ25hdHVyZT4KPC9MaWNlbnNlPg==";

                Stream stream = new MemoryStream(Convert.FromBase64String(LData));

                stream.Seek(0, SeekOrigin.Begin);
                new Aspose.Pdf.License().SetLicense(stream);


                //// file license in app_code folder
                //Aspose.Pdf.License license = new Aspose.Pdf.License();
                //license.SetLicense(Server.MapPath("~/app_code/license.lic"));
                string rootFolder = Directory.GetCurrentDirectory();

                Stream fileStream = model.files.OpenReadStream();

                string       outPutFilePath = rootFolder + "\\wwwroot\\ExtractedImages\\";
                PdfConverter objConverter   = new PdfConverter();
                objConverter.BindPdf(fileStream);
                objConverter.DoConvert();
                objConverter.CoordinateType = PageCoordinateType.CropBox;
                var stamp = DateTime.Now.Ticks.ToString() + "_1.jpg";
                if (objConverter.HasNextImage())
                {
                    objConverter.GetNextImage(outPutFilePath + model.files.FileName + stamp, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                objConverter.Close();

                return("Image Extracted Succesfully in this path :- " + System.IO.Path.Combine(outPutFilePath, model.files.FileName + stamp));
            }
            catch (Exception ex)
            {
            }
            return("Some error occured, try after some time");
        }
コード例 #10
0
        public static void Main()
        {
            // The path to the documents directory.
            string dataDir = Path.GetFullPath("../../../Data/");
            //create PdfConverter object
            PdfConverter objConverter = new PdfConverter();

            //bind input pdf file
            objConverter.BindPdf(dataDir + "input.pdf");

            //initialize the converting process
            objConverter.DoConvert();
            objConverter.ShowHiddenAreas = true;

            //check if pages exist and then convert to image one by one
            while (objConverter.HasNextImage())
            {
                objConverter.GetNextImage(dataDir + DateTime.Now.Ticks.ToString() + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            }

            //close the PdfConverter object
            objConverter.Close();
        }
コード例 #11
0
        private OperationResult ValidatePageCounts(string pathTofile)
        {
            OperationResult operationResult = new OperationResult();
            bool foundBarCode = false;
            string currentUser = Utility.GetUserName();
            int testCounter = 1;
            string currentPatientID = string.Empty;
            string currentTabID = string.Empty;

            Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(pathTofile);
            barCodeText = new List<ScannedDocument>();

            int pageCount = pdfDocument.Pages.Count;

            for (var i = 1; i <= pageCount; i++)
            {
                var converter = new PdfConverter();
                converter.BindPdf(pathTofile);
                converter.StartPage = i;
                converter.EndPage = i;
                converter.RenderingOptions.BarcodeOptimization = true;
                converter.Resolution = new Aspose.Pdf.Devices.Resolution(300);
                converter.DoConvert();
                MemoryStream stream = new MemoryStream();
                converter.GetNextImage(stream, ImageFormat.Png);
                using (BarCodeReader reader = new BarCodeReader(stream, BarCodeReadType.Code39Standard))
                {
                    while (reader.Read())
                    {
                        string[] barCodeDocument = reader.GetCodeText().Split('-');
                        ScannedDocument scannedDocument = new ScannedDocument();
                        scannedDocument.PatientID = barCodeDocument[0];
                        scannedDocument.TabID = barCodeDocument[1];
                        scannedDocument.CurrentPageNumber = int.Parse(barCodeDocument[2]);
                        scannedDocument.PageCount = int.Parse(barCodeDocument[3]);
                        scannedDocument.Text = reader.GetCodeText();
                        scannedDocument.FullPath = pathTofile;
                        scannedDocument.User = currentUser;
                        barCodeText.Add(scannedDocument);
                        foundBarCode = true;
                    }
                }
                converter.Close();
                converter.Dispose();

                if (foundBarCode != true)
                {
                    operationResult.Success = false;
                    operationResult.ErrorMessage = "Job Failed: Could not Read Bar Code";
                    return operationResult;
                }
                foundBarCode = false;
            }

            //Step 1 Check to be sure the number of pages in the document
            //matches the number of pages in the bar code
            int pdfPageCount = 0;
            int pdfPageCountCheck = 0;
            Aspose.Pdf.Document pdfDocumentPageCount = new Aspose.Pdf.Document(barCodeText[0].FullPath);
            pdfPageCount = pdfDocumentPageCount.Pages.Count;

            currentPatientID = barCodeText[0].PatientID;
            currentTabID = barCodeText[0].TabID;

            for (int i = 0; i < barCodeText.Count; i++)
            {
                try
                {
                    if (int.Parse(barCodeText[i].PatientID) < 1)
                    {
                        operationResult.Success = false;
                        operationResult.ErrorMessage = "Patient ID Invalid";
                        return operationResult;
                    }
                }
                catch 
                {
                    operationResult.Success = false;
                    operationResult.ErrorMessage = "Patient ID Invalid";
                    return operationResult;
                }
                try
                {
                    if (int.Parse(barCodeText[i].TabID) < 1)
                    {
                        operationResult.Success = false;
                        operationResult.ErrorMessage = "Tab ID Invalid";
                        return operationResult;
                    }
                }
                catch
                {
                    operationResult.Success = false;
                    operationResult.ErrorMessage = "Tab ID Invalid";
                    return operationResult;
                }

                if (testCounter == barCodeText[i].CurrentPageNumber && barCodeText[i].PageCount == barCodeText[i].CurrentPageNumber && barCodeText[i].PatientID == currentPatientID && barCodeText[i].TabID == currentTabID)
                {
                    //string[] barCodePageCount = barCodeText[i].Text.Split('-');
                    pdfPageCountCheck = pdfPageCountCheck + barCodeText[i].PageCount;
                    testCounter = 1;

                    if (barCodeText[i].PageCount == barCodeText[i].CurrentPageNumber)
                    {

                        try
                        {
                            currentPatientID = barCodeText[i + 1].PatientID;
                            currentTabID = barCodeText[i + 1].TabID;
                        }
                        catch { }
                    }
                }
                else
                {
                    if (testCounter == barCodeText[i].CurrentPageNumber && barCodeText[i].PatientID == currentPatientID && barCodeText[i].TabID == currentTabID)
                    {
                        testCounter++;
                    }
                    else
                    {
                        operationResult.Success = false;
                        operationResult.ErrorMessage = "Job Failed: Documents out of Order";
                        return operationResult;
                    }
                }
            }

            if (pageCount != pdfPageCountCheck)
            {
                operationResult.Success = false;
                operationResult.ErrorMessage = "Job Failed: Documents out of Order";
                return operationResult;
            }

            operationResult.Success = true;
            operationResult.ErrorMessage = "Job Confirmed";
            return operationResult;
        }
コード例 #12
0
        public static void Run()
        {
            try
            {
                // ExStart:HighlightCharacterInPDF
                // The path to the documents directory.
                string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

                int resolution = 150;

                Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(dataDir + "input.pdf");

                using (MemoryStream ms = new MemoryStream())
                {
                    PdfConverter conv = new PdfConverter(pdfDocument);
                    conv.Resolution = new Resolution(resolution, resolution);
                    conv.GetNextImage(ms, System.Drawing.Imaging.ImageFormat.Png);

                    Bitmap bmp = (Bitmap)Bitmap.FromStream(ms);

                    using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp))
                    {
                        float scale = resolution / 72f;
                        gr.Transform = new System.Drawing.Drawing2D.Matrix(scale, 0, 0, -scale, 0, bmp.Height);

                        for (int i = 0; i < pdfDocument.Pages.Count; i++)
                        {
                            Page page = pdfDocument.Pages[1];
                            // Create TextAbsorber object to find all words
                            TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(@"[\S]+");
                            textFragmentAbsorber.TextSearchOptions.IsRegularExpressionUsed = true;
                            page.Accept(textFragmentAbsorber);
                            // Get the extracted text fragments
                            TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
                            // Loop through the fragments
                            foreach (TextFragment textFragment in textFragmentCollection)
                            {
                                if (i == 0)
                                {
                                    gr.DrawRectangle(
                                        Pens.Yellow,
                                        (float)textFragment.Position.XIndent,
                                        (float)textFragment.Position.YIndent,
                                        (float)textFragment.Rectangle.Width,
                                        (float)textFragment.Rectangle.Height);

                                    for (int segNum = 1; segNum <= textFragment.Segments.Count; segNum++)
                                    {
                                        TextSegment segment = textFragment.Segments[segNum];

                                        for (int charNum = 1; charNum <= segment.Characters.Count; charNum++)
                                        {
                                            CharInfo characterInfo = segment.Characters[charNum];

                                            Aspose.Pdf.Rectangle rect = page.GetPageRect(true);
                                            Console.WriteLine("TextFragment = " + textFragment.Text + "    Page URY = " + rect.URY +
                                                              "   TextFragment URY = " + textFragment.Rectangle.URY);

                                            gr.DrawRectangle(
                                                Pens.Black,
                                                (float)characterInfo.Rectangle.LLX,
                                                (float)characterInfo.Rectangle.LLY,
                                                (float)characterInfo.Rectangle.Width,
                                                (float)characterInfo.Rectangle.Height);
                                        }

                                        gr.DrawRectangle(
                                            Pens.Green,
                                            (float)segment.Rectangle.LLX,
                                            (float)segment.Rectangle.LLY,
                                            (float)segment.Rectangle.Width,
                                            (float)segment.Rectangle.Height);
                                    }
                                }
                            }
                        }
                    }
                    dataDir = dataDir + "HighlightCharacterInPDF_out.png";
                    bmp.Save(dataDir, System.Drawing.Imaging.ImageFormat.Png);
                }
                // ExEnd:HighlightCharacterInPDF
                Console.WriteLine("\nCharacters highlighted successfully in pdf document.\nFile saved at " + dataDir);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
            }
        }
コード例 #13
0
        private List <string> GetDocumentPages(string file, string folderName, int currentPage)
        {
            List <string> lstOutput   = new List <string>();
            string        outfileName = "page_{0}";
            string        outPath     = Config.Configuration.OutputDirectory + folderName + "/" + outfileName;

            currentPage = currentPage - 1;
            Directory.CreateDirectory(Config.Configuration.OutputDirectory + folderName);
            string imagePath = string.Format(outPath, currentPage) + ".jpeg";

            if (System.IO.File.Exists(imagePath) && currentPage > 0)
            {
                lstOutput.Add(imagePath);
                return(lstOutput);
            }

            int i = currentPage;

            var filename = System.IO.File.Exists(Config.Configuration.WorkingDirectory + folderName + "/" + file)
                                ? Config.Configuration.WorkingDirectory + folderName + "/" + file
                                : Config.Configuration.OutputDirectory + folderName + "/" + file;

            using (FilePathLock.Use(filename))
            {
                try
                {
                    if (!System.IO.File.Exists(Config.Configuration.OutputDirectory + folderName + "/" + "outputPDF.pdf"))
                    {
                        Aspose.Page.Live.Demos.UI.Models.License.SetAsposePageLicense();
                        System.IO.FileStream pdfStream = new System.IO.FileStream(Config.Configuration.OutputDirectory + folderName + "/" + "outputPDF.pdf", System.IO.FileMode.CreateNew, System.IO.FileAccess.Write);
                        System.IO.FileStream psStream  = new System.IO.FileStream(Config.Configuration.WorkingDirectory + folderName + "/" + file, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                        try
                        {
                            if (file.ToLower().EndsWith(".xps"))
                            {
                                Page.XPS.XpsDocument document = new XpsDocument(psStream, new Page.XPS.XpsLoadOptions());
                                Aspose.Page.XPS.Presentation.Pdf.PdfSaveOptions options = new Aspose.Page.XPS.Presentation.Pdf.PdfSaveOptions();
                                Aspose.Page.XPS.Presentation.Pdf.PdfDevice      device  = new Aspose.Page.XPS.Presentation.Pdf.PdfDevice(pdfStream, new Size(595, 842));
                                document.Save(device, options);
                            }
                            else
                            {
                                PsDocument document = new PsDocument(psStream);
                                Aspose.Page.EPS.Device.PdfSaveOptions options = new Aspose.Page.EPS.Device.PdfSaveOptions(true);
                                Aspose.Page.EPS.Device.PdfDevice      device  = new Aspose.Page.EPS.Device.PdfDevice(pdfStream, new Size(595, 842));
                                document.Save(device, options);
                            }
                        }
                        finally
                        {
                            psStream.Close();
                            pdfStream.Close();
                        }
                    }


                    PdfConverter objConverter = new PdfConverter();
                    objConverter.BindPdf(Config.Configuration.OutputDirectory + folderName + "/" + "outputPDF.pdf");
                    objConverter.DoConvert();
                    objConverter.CoordinateType = PageCoordinateType.CropBox;
                    if (currentPage < objConverter.PageCount)
                    {
                        lstOutput.Add(objConverter.PageCount.ToString());
                        i = 0;
                        while (objConverter.HasNextImage() && i < objConverter.PageCount)
                        {
                            objConverter.StartPage = (currentPage + 1);
                            objConverter.GetNextImage(imagePath, System.Drawing.Imaging.ImageFormat.Png);
                            lstOutput.Add(imagePath);
                            break;
                        }
                    }
                    objConverter.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                return(lstOutput);
            }
        }
コード例 #14
0
        public static void Run()
        {
            try
            {
                // ExStart:HighlightCharacterInPDF
                // The path to the documents directory.
                string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

                int resolution = 150;

                Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(dataDir + "input.pdf");

                using (MemoryStream ms = new MemoryStream())
                {
                    PdfConverter conv = new PdfConverter(pdfDocument);
                    conv.Resolution = new Resolution(resolution, resolution);
                    conv.GetNextImage(ms, System.Drawing.Imaging.ImageFormat.Png);

                    Bitmap bmp = (Bitmap)Bitmap.FromStream(ms);

                    using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp))
                    {
                        float scale = resolution / 72f;
                        gr.Transform = new System.Drawing.Drawing2D.Matrix(scale, 0, 0, -scale, 0, bmp.Height);

                        for (int i = 0; i < pdfDocument.Pages.Count; i++)
                        {
                            Page page = pdfDocument.Pages[1];
                            // Create TextAbsorber object to find all words
                            TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(@"[\S]+");
                            textFragmentAbsorber.TextSearchOptions.IsRegularExpressionUsed = true;
                            page.Accept(textFragmentAbsorber);
                            // Get the extracted text fragments
                            TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
                            // Loop through the fragments
                            foreach (TextFragment textFragment in textFragmentCollection)
                            {
                                if (i == 0)
                                {
                                    gr.DrawRectangle(
                                    Pens.Yellow,
                                    (float)textFragment.Position.XIndent,
                                    (float)textFragment.Position.YIndent,
                                    (float)textFragment.Rectangle.Width,
                                    (float)textFragment.Rectangle.Height);

                                    for (int segNum = 1; segNum <= textFragment.Segments.Count; segNum++)
                                    {
                                        TextSegment segment = textFragment.Segments[segNum];

                                        for (int charNum = 1; charNum <= segment.Characters.Count; charNum++)
                                        {
                                            CharInfo characterInfo = segment.Characters[charNum];

                                            Aspose.Pdf.Rectangle rect = page.GetPageRect(true);
                                            Console.WriteLine("TextFragment = " + textFragment.Text + "    Page URY = " + rect.URY +
                                                              "   TextFragment URY = " + textFragment.Rectangle.URY);

                                            gr.DrawRectangle(
                                            Pens.Black,
                                            (float)characterInfo.Rectangle.LLX,
                                            (float)characterInfo.Rectangle.LLY,
                                            (float)characterInfo.Rectangle.Width,
                                            (float)characterInfo.Rectangle.Height);
                                        }

                                        gr.DrawRectangle(
                                        Pens.Green,
                                        (float)segment.Rectangle.LLX,
                                        (float)segment.Rectangle.LLY,
                                        (float)segment.Rectangle.Width,
                                        (float)segment.Rectangle.Height);
                                    }
                                }
                            }
                        }
                    }
                    dataDir = dataDir + "HighlightCharacterInPDF_out.png";
                    bmp.Save(dataDir, System.Drawing.Imaging.ImageFormat.Png);
                }
                // ExEnd:HighlightCharacterInPDF            
                Console.WriteLine("\nCharacters highlighted successfully in pdf document.\nFile saved at " + dataDir);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
            }
        }
コード例 #15
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage httpRequestMessage, ILogger log)
        {
            log.LogInformation($"ImageConverterFunction :HTTP trigger function processed request at : { DateTime.Now}");
            //Binding file content from httpRequestMessage
            var    fileContent = httpRequestMessage.Content;
            string jsonContent = fileContent.ReadAsStringAsync().Result;
            //Get headers from httpRequestMessage
            var         headers      = httpRequestMessage.Headers;
            var         jsonToReturn = string.Empty;
            string      errormessage = string.Empty;
            HeaderModel headerModel  = new HeaderModel();

            try
            {
                //Validating headers from httprequestMessage
                if (HeaderValidation.ValidateHeader(headers, ref errormessage))
                {
                    headerModel.FileExtension = headers.GetValues(Constants.FILE_EXTENSION).First();
                    headerModel.FileType      = headers.GetValues(Constants.FILE_TYPE).First();
                    log.LogInformation($"HeaderValidation success for File extension and FileType");
                }
                else
                {
                    //Header values has empty or null return badrequest response
                    log.LogInformation($"HeaderValidation Failure for File extension and FileType :{errormessage}");
                    return(new HttpResponseMessage(HttpStatusCode.BadRequest)
                    {
                        Content = new StringContent($"{errormessage}")
                    });
                }

                #region ImageToThumbnail
                //Converting Image file to Thumbnail image
                if (headerModel.FileExtension == Constants.PNG || headerModel.FileExtension == Constants.JPEG)
                {
                    try
                    {
                        //Validating Image specific headers
                        if (HeaderValidation.ValidateImageHeader(headers, ref errormessage))
                        {
                            headerModel.ThumnailImageHeight = headers.GetValues(Constants.THUMBNAIL_HEIGHT).First();
                            headerModel.ThumnailImageWidth  = headers.GetValues(Constants.THUMBNAIL_WIDTH).First();
                            headerModel.InlineImageHeight   = headers.GetValues(Constants.INLINE_HEIGHT).First();
                            headerModel.InlineImageWidth    = headers.GetValues(Constants.INLINE_WIDTH).First();
                            log.LogError($"HeaderValidation Success for Image to thumbnail conversion");
                        }
                        else
                        {
                            //Header values has empty or null return badrequest response
                            log.LogInformation($"HeaderValidation Failure in Image to thumbnail conversion: {errormessage}");
                            return(new HttpResponseMessage(HttpStatusCode.BadRequest)
                            {
                                Content = new StringContent($"{ errormessage }", Encoding.UTF8, Constants.JSON)
                            });
                        }
                        //Convert file content to memorystream
                        var memoryStream = new MemoryStream(Convert.FromBase64String(jsonContent));
                        var imageObj     = new { thumbnail = ConvertToThumbnail(memoryStream, Convert.ToInt32(headerModel.ThumnailImageHeight), Convert.ToInt32(headerModel.ThumnailImageWidth), log), inline = ConvertToThumbnail(memoryStream, Convert.ToInt32(headerModel.InlineImageHeight), Convert.ToInt32(headerModel.InlineImageWidth), log) };
                        jsonToReturn = JsonConvert.SerializeObject(imageObj);
                    }
                    catch (Exception ex)
                    {
                        log.LogError($"Exception occurred in Image file conversion to thumbnail, Error : {ex.Message},Details:{ex.InnerException}");
                        return(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                        {
                            Content = new StringContent(ex.Message, Encoding.UTF8, Constants.JSON)
                        });
                    }
                }
                #endregion

                #region PDFToThumbnail
                //Converting Pdf first page to Thumbnail image
                if (headerModel.FileExtension == Constants.PDF)
                {
                    try
                    {
                        //To include license
                        Aspose.Pdf.License license = new Aspose.Pdf.License();
                        license.SetLicense("Aspose.Pdf.lic");
                        log.LogInformation("Aspose SetLicense Success");
                        ImageFormat  format       = GetImageFormat(headerModel.FileType, log);
                        PdfConverter pdfConverter = new PdfConverter();
                        //Validating pdf file specific headers
                        if (HeaderValidation.ValidatePdfFileHeader(headers, ref errormessage))
                        {
                            headerModel.Height = headers.GetValues(Constants.HEIGHT).First();
                            headerModel.Width  = headers.GetValues(Constants.WIDTH).First();
                            log.LogInformation($"HeaderValidation Success for PDF to thumbnail conversion");
                        }
                        else
                        {
                            //Header values has empty or null return badrequest response
                            log.LogError($"HeaderValidation Failure for PDF to thumbnail conversion : {errormessage}");
                            return(new HttpResponseMessage(HttpStatusCode.BadRequest)
                            {
                                Content = new StringContent($"{errormessage}", Encoding.UTF8, Constants.JSON)
                            });
                        }

                        var streamContent = httpRequestMessage.Content.ReadAsStreamAsync();
                        pdfConverter.BindPdf(streamContent.Result);
                        //To convert first page of PDF
                        pdfConverter.StartPage  = 1;
                        pdfConverter.EndPage    = 1;
                        pdfConverter.Resolution = new Aspose.Pdf.Devices.Resolution(100);
                        pdfConverter.DoConvert();
                        MemoryStream imageStream = new MemoryStream();
                        while (pdfConverter.HasNextImage())
                        {
                            // Save the image in the given image Format
                            pdfConverter.GetNextImage(imageStream, format);
                            // Set the stream position to the beginning of the stream
                            imageStream.Position = 0;
                        }
                        var imageObj = new { content = ConvertToThumbnail(imageStream, Convert.ToInt32(headerModel.Width), Convert.ToInt32(headerModel.Height), log), contentType = "image/" + headerModel.FileType };
                        jsonToReturn = JsonConvert.SerializeObject(imageObj);
                        pdfConverter.Close();
                        imageStream.Close();
                    }
                    catch (Exception ex)
                    {
                        log.LogError($"Exception occurred in pdf file conversion to thumbnail,Error : {ex.Message},Details:{ex.InnerException}");
                        return(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                        {
                            Content = new StringContent(ex.Message, Encoding.UTF8, Constants.JSON)
                        });
                    }
                }

                #endregion
                log.LogInformation("ImageConverterFunction successfully processed.");
                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(jsonToReturn, Encoding.UTF8, Constants.JSON)
                });
            }
            catch (Exception ex)
            {
                log.LogError($"Exception occurred in ImageConverterFunction,Error: { ex.Message},Details: { ex.InnerException}");
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(ex.Message, Encoding.UTF8, Constants.JSON)
                });
            }
        }