Наследование: ITextExtractionStrategy
Пример #1
7
        private static String GetPdfContent(string path)
        {
            var text = new StringBuilder();

            using (var pdfReader = new PdfReader(path))
            {
                for (var page = 1; page <= pdfReader.NumberOfPages; page++)
                {
                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy(); //  LocationTextExtractionStrategy();

                    var currentText = PdfTextExtractor.GetTextFromPage(
                        pdfReader,
                        page,
                        strategy);

                    currentText =
                        Encoding.UTF8.GetString(Encoding.Convert(
                            Encoding.Default,
                            Encoding.UTF8,
                            Encoding.Default.GetBytes(currentText)));

                    text.Append(currentText);
                }
            }
            return text.ToString();
        }
Пример #2
3
        public static string ExtractTextFromPdf(string path)
        {
            ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();

            using (PdfReader reader = new PdfReader(path))
            {
                StringBuilder text = new StringBuilder();

                for (int page = 1; page <= reader.NumberOfPages; page++)
                {
                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();

                    string currentText = PdfTextExtractor.GetTextFromPage(reader, page, strategy);

                    currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                    text.Append(currentText);
                }

                System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
                file.WriteLine(text);

                file.Close();

                return text.ToString();
            }
        }
Пример #3
0
        //[Dependency]
        //public IF0413Repository F0413Repository { get; set; }
        //[Dependency]
        //public IF0413Business F0413Business { get; set; }
        //[Dependency]
        //public IF0414Business F0414Business { get; set; }

        public String BuscarDatosPdf(string nombreArchivo)
        {
            /*path = path + “/ extjs.pdf”;
             * string salida = ReadPdfFile(path);
             *
             * y luego defino el método*/
            try
            {
                PdfReader reader2 = new PdfReader(nombreArchivo);
                string    strText = string.Empty;

                for (int page = 1; page <= reader2.NumberOfPages; page++)
                {
                    ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                    PdfReader reader            = new PdfReader(nombreArchivo);
                    String    s = PdfTextExtractor.GetTextFromPage(reader, page, its);

                    s       = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
                    strText = strText + s;
                    reader.Close();
                }
                reader2.Close();
                return(strText);
            }
            catch (IOException ex)
            {
                throw new ExportException("Error: No se encuentra el archivo o recurso: " + nombreArchivo + ". --> Traza Original: " + ex.StackTrace);
            }
        }
Пример #4
0
        private int searchThroughFile(string path)
        {
            int count = 0;

            string[] temp = null;
            using (PdfReader reader = new PdfReader(path))
            {
                ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();

                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    string text = null;
                    try
                    {
                        text = (PdfTextExtractor.GetTextFromPage(reader, i, its));
                    }
                    catch (Exception e)
                    {
                    }
                    if (text != null && text.Contains(word))
                    {
                        count++;
                        text = null;
                    }
                }
            }
            return(count);
        }
Пример #5
0
        //Este metodo lee el PDF
        public string ReadPdfFile(object Filename)
        {
            string strText = string.Empty;

            //try para obtener el error en caso de que ocurra
            try
            {
                PdfReader readerPdf = new PdfReader((string)Filename);

                for (int page = 1; page <= readerPdf.NumberOfPages; page++)
                {
                    ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                    PdfReader reader            = new PdfReader((string)Filename);
                    String    s = PdfTextExtractor.GetTextFromPage(reader, page, its);

                    s       = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
                    strText = strText + s;
                    reader.Close();
                }
            }
            //Manejo de errores
            catch (Exception ex)
            {
                //Muestro el error en caso de que ocurra
                lblMsjs.ForeColor = Color.Crimson;
                lblMsjs.Text      = ex.Message.ToString();
            }
            //retorno el texto
            return(strText);
        }
        private List <InvoiceItem> GetFaturaItems(string fileName)
        {
            var result = new List <InvoiceItem>();

            try
            {
                PdfReader reader = new PdfReader(fileName);

                var its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();

                String rawTextV = PdfTextExtractor.GetTextFromPage(reader, 1, its);

                var pageVencimento = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(rawTextV)));

                var vencimento = GetVencimento(pageVencimento);


                for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++)
                {
                    its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();

                    String rawText = PdfTextExtractor.GetTextFromPage(reader, pageNumber, its);

                    var page = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(rawText)));
                    result.AddRange(ParsePage(page, vencimento));
                }
                reader.Close();
            }
            catch (Exception)
            {
                //TODO: Bug Hidden
            }
            return(result);
        }
Пример #7
0
        public string ReadTextPDF(string path)
        {
            try
            {
                PdfReader reader     = new PdfReader(path);
                int       numberPage = reader.NumberOfPages;

                StringBuilder textPages = new StringBuilder();

                for (int i = 0; i < numberPage; i++)
                {
                    ITextExtractionStrategy textExtractionStrategy = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();

                    string textPage = PdfTextExtractor.GetTextFromPage(reader, i + 1, textExtractionStrategy);

                    textPage = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(textPage)));

                    textPages.Append(textPage);
                }
                reader.Close();

                string txt = textPages.ToString();

                return(txt);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Пример #8
0
        public String readTextData(String readText)
        {
            String str = null;

            if (readText.Substring(readText.Length - 3, 3).Equals("pdf"))
            {
                PdfReader reader = new PdfReader((string)readText);

                for (int page = 1; page <= reader.NumberOfPages; page++)
                {
                    ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                    String s = PdfTextExtractor.GetTextFromPage(reader, page, its);

                    s   = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
                    str = str + s;
                }
                reader.Close();
            }
            else
            {
                str = System.IO.File.ReadAllText(@readText);
            }
            str.Replace("\n", " ");
            return(str);
        }
Пример #9
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string    firstLine = null;
        string    strText   = null;
        String    str       = Request.QueryString["file"];
        PdfReader reader    = new PdfReader(Server.MapPath("Uploads\\Documents") + "\\" + str);

        for (int page = 1; page <= reader.NumberOfPages; page++)
        {
            ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();

            String s = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, page, its);

            strText = strText + s;
            //string firstLine = string.Empty;
            if (s.Contains("\n"))
            {
                firstLine += s.Split('\n')[1] + "<br>";
            }
            else
            {
                firstLine += s;
            }
            continue;
        }
        divMainContent.InnerHtml = firstLine;

        reader.Close();
    }
Пример #10
0
		public static void ExtractText(string sourceFilePath, string destinationPath)
		{
			var text = new StringBuilder();
			var pdfReader = new PdfReader(sourceFilePath);
			for (int page = 1; page <= pdfReader.NumberOfPages; page++)
			{
				ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
				var currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
				currentText = Encoding.UTF8.GetString(
					Encoding.Convert(
						Encoding.Default, 
						Encoding.UTF8, 
						Encoding.Default.GetBytes(currentText))
					);
				text.Append(currentText);
			}
			pdfReader.Close();

			var temp = text.ToString();
			var regexp = new Regex(@"[ ]{2,}", RegexOptions.None);
			temp = regexp.Replace(temp, @" ");
			temp = Regex.Replace(temp, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);

			File.WriteAllText(destinationPath, temp);
		}
Пример #11
0
        public IDictionary <int, string> LeerPdf()
        //Metodo que lee y devuelve el contenido de un archivo Pdf
        {
            Dictionary <int, string> datosPdf = new Dictionary <int, string>();


            PdfReader archivo = new PdfReader(this.rutaArchivo);
            string    strText = string.Empty;

            for (int pagina = 1; pagina <= archivo.NumberOfPages; pagina++)
            {
                ITextExtractionStrategy conte = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                PdfReader lectura             = new PdfReader(this.rutaArchivo);
                string    s = PdfTextExtractor.GetTextFromPage(lectura, pagina, conte);

                s = System.Text.Encoding.UTF8.GetString(ASCIIEncoding.Convert(System.Text.Encoding.Default, System.Text.Encoding.UTF8,
                                                                              System.Text.Encoding.Default.GetBytes(s)));

                strText = strText + s;
                datosPdf.Add(pagina, strText);
                lectura.Close();
            }

            return(datosPdf);
        }
Пример #12
0
        /**************************           FINAL        *****************************/
        public string pdf2Text(string pdfFile)
        {
            PdfReader reader = new PdfReader(pdfFile);
            //ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
            ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();

            string txt   = "";
            int    pages = reader.NumberOfPages;

            for (int page = 1; page <= reader.NumberOfPages; page++)
            {
                txt = PdfTextExtractor.GetTextFromPage(reader, page, its);
                txt = txt.Replace("\n", " ");
                // Replace multi spaces with single
                RegexOptions options = RegexOptions.None;
                Regex        regex   = new Regex("[ ]{2,}", options);

                txt = regex.Replace(txt, " ");
                Console.WriteLine("Slide #" + page + "\n-----------------------\n" + txt + "\n-----------------------\n");
            }
            // txt = txt.Replace("\n", " ").Replace("  ", " "); ;


            return(txt);
        }
Пример #13
0
        private static IEnumerable<string> GetLinesFrom(PdfReader pdfReader)
        {
            var strategy = new SimpleTextExtractionStrategy();

            return Enumerable
                .Range(1, pdfReader.NumberOfPages)
                .Select(p => PdfTextExtractor.GetTextFromPage(pdfReader, p, strategy));
        }
Пример #14
0
        public static String Extract(String url, String saveTo = null)
        {
            try
            {
                WebClient wc = new WebClient();
                byte[] data = wc.DownloadData(url);

                // 如果设置了保存到文件,则写入文件
                if (!String.IsNullOrWhiteSpace(saveTo) && data != null && data.Length > 0)
                {
                    if (!Directory.Exists(saveTo))
                    {
                        Directory.CreateDirectory(saveTo);
                    }
                    String file = GeneratePath(saveTo, url);
                    try
                    {
                        using (FileStream fs = new FileStream(file, FileMode.CreateNew))
                        {
                            fs.Write(data, 0, data.Length);
                        }
                    }
                    catch (IOException ioe)
                    {
                    }
                }

                using (PdfReader reader = new PdfReader(data))
                {
                    try
                    {
                        StringBuilder sb = new StringBuilder();
                        ITextExtractionStrategy extract = new SimpleTextExtractionStrategy();
                        for (int i = 1; i <= reader.NumberOfPages; i++)
                        {
                            sb.Append(PdfTextExtractor.GetTextFromPage(reader, i, extract));
                            reader.ReleasePage(i);
                        }                                            
                        return sb.ToString();
                    }
                    finally
                    {
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return String.Empty;
            }
        }
Пример #15
0
 /**
  * Parses the PDF using PRTokeniser
  * @param src  the path to the original PDF file
  * @param dest the path to the resulting text file
  */
 public string[] parsePdfToHtml(string src)
 {
     iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(src);
     //StreamWriter output = new StreamWriter();
     SimpleTextExtractionStrategy strategy = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
     List<string> text = new List<string>(); ;
     int pageCount = reader.NumberOfPages;
     for (int pg = 1; pg <= pageCount; pg++)
     {
         text.Add(PdfTextExtractor.GetTextFromPage(reader, pg, strategy));
     }
     return text.ToArray();
 }
Пример #16
0
        /// <summary>
        /// function to read and process pdf file
        /// </summary>
        /// <param name="pdf_file">name of the pdf file to be processed</param>
        public static void ReadPDF(string pdf_file, BasePDFExtractor pdf_extractor)
        {
            /*
             * Console.Write() - display extended ascii chars?
             * https://stackoverflow.com/questions/3948089/console-write-display-extended-ascii-chars
             */
            Console.OutputEncoding = Encoding.UTF8;

            /*
             *  How to extract text line by line when using iTextSharp
             *  https://stackoverflow.com/questions/15748800/extract-text-by-line-from-pdf-using-itextsharp-c-sharp
             */

            // ITextExtractionStrategy Strategy = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();

            /*
             * https://stackoverflow.com/questions/83152/reading-pdf-documents-in-net
             * ITextExtractionStrategy Strategy = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
             */


            using (PdfReader reader = new PdfReader(pdf_file))
            {
                //Schedule3Extractor page_reader = new Schedule3Extractor();


                // break the whole pdf into pages and then process page by page
                string page_content;
                for (int page_count = 0; page_count < reader.NumberOfPages;)
                {
                    page_count++;

                    /* Why are GetTextFromPage from iTextSharp returning longer and longer strings?
                     * https://stackoverflow.com/questions/35911062/why-are-gettextfrompage-from-itextsharp-returning-longer-and-longer-strings
                     */

                    //ITextExtractionStrategy Strategy = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
                    ITextExtractionStrategy Strategy = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();

                    // get the whole page content
                    page_content = PdfTextExtractor.GetTextFromPage(reader, page_count, Strategy);

                    pdf_extractor.ProcessPage(page_content);

                    // Debug :
                    //if (page_count == 1) break;
                }
            }
        }
Пример #17
0
        public string ReadPdfFile(object Filename)
        {
            PdfReader reader2 = new PdfReader((string)Filename);
            string    strText = string.Empty;

            for (int page = 1; page <= reader2.NumberOfPages; page++)
            {
                ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                PdfReader reader            = new PdfReader((string)Filename);
                String    s = PdfTextExtractor.GetTextFromPage(reader, page, its);
                s       = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
                strText = strText + s;
                reader.Close();
            }
            return(strText);
        }
Пример #18
0
        /// <summary>
        /// Not really useful since wkhtmltopdf build an image pdf...
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public bool PdfContains(string text)
        {
            //var textbuilder = new StringBuilder();
            for (int page = 1; page <= pdfReader.NumberOfPages; page++)
            {
                var strategy = new SimpleTextExtractionStrategy();
                string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

                currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                //textbuilder.Append(currentText);
                if (currentText.Contains(text))
                    return true;
                pdfReader.Close();
            }
            return false;
        }
Пример #19
0
        public string Go(string url)
        {
            var text = new StringBuilder();
            try
            {
                using (var pdfReader = new PdfReader(url))
                {
                    // Loop through each page of the document
                    for (var page = 1; page <= 10; page++)
                    {
                        ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                        try
                        {
                            var currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
                            currentText =
                                Encoding.UTF8.GetString(
                                    Encoding.Convert(
                                        Encoding.Default,
                                        Encoding.UTF8,
                                        Encoding.Default.GetBytes(currentText)));
                            text.Append(currentText);
                        }
                        catch (ArgumentException)
                        {
                            Logger.Log.Error(string.Format("Can't parse PDF {0}, only images and no text.", url));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new BookieException(ex.Message, ex);
            }

            var rFileIsbn = Regex.Match(text.ToString(), @"ISBN.*?([X\d\-_ .]{10,20})");
            if (!rFileIsbn.Success)
            {
                return null;
            }
            _isbn = rFileIsbn.Groups[1].ToString();
            _isbn = _isbn.Replace(".", string.Empty);
            _isbn = _isbn.Replace(" ", string.Empty);
            _isbn = _isbn.Replace("-", string.Empty);
            _isbn = _isbn.Replace("_", string.Empty);
            return _isbn;
        }
Пример #20
0
        static string SearchText()
        {
            string    name    = @"C:\Users\DELL\Documents\Proyectopdfing\BIO-Alan-Munoz.pdf";
            PdfReader reader2 = new PdfReader(name);
            string    strText = string.Empty;

            for (int page = 1; page <= reader2.NumberOfPages; page++)
            {
                ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                PdfReader reader            = new PdfReader(name);
                String    s = PdfTextExtractor.GetTextFromPage(reader, page, its);
                s       = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
                strText = strText + s;
                reader.Close();
            }
            return(strText);
        }
Пример #21
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usa: pdf2text [nomre pdf] [nombre txt]");
                return;
            }
            else
            {
                foreach (string s in args){
                    System.Console.WriteLine(s);
                }

                String ficheroEntrada = args[0];
                String ficheroSalida = args[1];

                StringBuilder text = new StringBuilder();

                if (File.Exists(ficheroEntrada))
                {
                    PdfReader pdfReader = new PdfReader(ficheroEntrada);

                    int paginaInicio = 1;
                    int numberOfPages = pdfReader.NumberOfPages;

                    for (int page = paginaInicio; page <= numberOfPages; page++)
                    {
                        ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                        string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

                        currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                        text.Append(currentText);
                    }
                    pdfReader.Close();
                }
                try
                {
                    File.WriteAllText(ficheroSalida, text.ToString(), Encoding.UTF8);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("error escribiendo fichero de salida" + ex.Message);
                }

            }
        }
Пример #22
0
        public string ReadPdfFile()
        {
            PdfReader reader2 = new PdfReader("c:\\prueba.pdf");
            string strText = string.Empty;

            for (int page = 1; page <= reader2.NumberOfPages; page++)
            {
                ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                PdfReader reader = new PdfReader("c:\\prueba.pdf");
                String s = PdfTextExtractor.GetTextFromPage(reader, page, its);

                s = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
                strText = strText + s;
                reader.Close();
            }
            return strText;
        }
Пример #23
0
        private string GetPDFContents(PdfReader reader)
        {
            string strText     = string.Empty;
            int    intNumPages = reader.NumberOfPages;

            for (int page = 1; page <= intNumPages; page++)
            {
                ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                using (PdfReader pReader = new PdfReader(reader))
                {
                    String pageContents = PdfTextExtractor.GetTextFromPage(pReader, page, its);
                    pageContents = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(pageContents)));
                    strText     += pageContents;
                }
            }
            return(strText);
        }
        public void TestUnicodeEmptyString()  {
            StringBuilder sb = new StringBuilder();
            String inFile = "japanese_text.pdf";

    
            PdfReader p = TestResourceUtils.GetResourceAsPdfReader(TEST_RESOURCES_PATH, inFile);
            ITextExtractionStrategy strat = new SimpleTextExtractionStrategy();

            sb.Append(PdfTextExtractor.GetTextFromPage(p, FIRST_PAGE, strat));

            String result = sb.ToString(0, sb.ToString().IndexOf('\n'));
            String origText =
                    "\u76f4\u8fd1\u306e\u0053\uff06\u0050\u0035\u0030\u0030"
                    + "\u914d\u5f53\u8cb4\u65cf\u6307\u6570\u306e\u30d1\u30d5"
                    + "\u30a9\u30fc\u30de\u30f3\u30b9\u306f\u0053\uff06\u0050"
                    + "\u0035\u0030\u0030\u6307\u6570\u3092\u4e0a\u56de\u308b";
            Assert.AreEqual(result, origText);
        }
Пример #25
0
        public string Text()
        {
            if (_pageText != null) 
                return _pageText;
            
            using (var pdfReader = new PdfReader(_content.Buffer))
            {
                var strategy = new SimpleTextExtractionStrategy();
                var pageText = PdfTextExtractor.GetTextFromPage(pdfReader, _number, strategy);
                pageText =
                    Encoding.UTF8.GetString(Encoding.Convert(Encoding.Default, Encoding.UTF8,
                        Encoding.Default.GetBytes(pageText)));

                _pageText = pageText;
            }

            return _pageText;
        }
Пример #26
0
        static void Main(string[] args)
        {
            string ReadPdfFile(object Filename)
            {
                PdfReader reader2 = new PdfReader((string)Filename);
                string    strText = string.Empty;

                //for (int page = 1; page <= reader2.NumberOfPages; page++)
                for (int page = 1; page <= 1; page++)
                {
                    ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                    PdfReader reader            = new PdfReader((string)Filename);
                    String    s = PdfTextExtractor.GetTextFromPage(reader, page, its);

                    s       = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
                    strText = strText + s;
                    reader.Close();
                }
                return(strText.Substring(84, 61).Replace(" ", "_").Replace(":", "").Trim());
            }

            DirectoryInfo di = new DirectoryInfo(@"C:\\temp\\pdfs");

            foreach (var fi in di.GetFiles())
            {
                Console.WriteLine(di + "\\\\" + fi);
                Console.WriteLine("Pdf: " + ReadPdfFile(di + "\\\\" + fi));
                string oldfile  = di + "\\\\" + fi;
                string text_pdf = ReadPdfFile(di + "\\\\" + fi).ToString();
                string nwfile   = di + "\\\\" + text_pdf.ToString() + ".pdf";
                Console.WriteLine("old: " + oldfile);
                Console.WriteLine("new: " + nwfile);
                //Console.ReadKey();
                // Poner un try para ver donde da error
                File.Copy(oldfile, nwfile, true);
            }
            Console.ReadKey();

            /*
             * string path = "C:\\temp\\ver.pdf";
             * Console.WriteLine("Pdf: " + ReadPdfFile(path));
             * Console.ReadKey();
             */
        }
Пример #27
0
        private void button1_Click(object sender, EventArgs e)
        {

            // Start Reading eBook //
            if (textBox1.Text == "")
            {
                
                MessageBox.Show(" Please Enter a location","PDF to TEXT Converter");
            }
            
            else if (File.Exists(filename))
            {
                try
                {
                    StringBuilder text = new StringBuilder();
                    PdfReader pdfReader = new PdfReader(filename);
                    progressBar1.Maximum = pdfReader.NumberOfPages;
                    for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                    {
                        ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                        string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
                        text.Append(System.Environment.NewLine);
                        text.Append("\n Page Number:" + page);
                        text.Append(System.Environment.NewLine);
                        currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                        text.Append(currentText);
                        pdfReader.Close();
                        progressBar1.Value++;

                    }
                    pdftext.Text += text.ToString();
                    progressBar1.Value = 0;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: "+ ex.Message, "Error");
                }
            }
            else
            {
                pdftext.Text = "Error: eBook does not exist at the specified location";
            }
            // End Reading eBook //
        }
Пример #28
0
        /// <summary>
        /// Use the official test extraction interface.
        /// THIS IS THE BEST METHOD
        /// </summary>
        /// <param name="Filename"></param>
        public string GetPdfFileText(string SrcFilename)
        {
            StringBuilder builder = new StringBuilder();
            PdfReader     reader  = new PdfReader(SrcFilename);

            for (int page = 1; page <= reader.NumberOfPages; page++)
            {
                ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                //ITextExtractionStrategy its = new CSVTextExtractionStrategy();
                string PageText = PdfTextExtractor.GetTextFromPage(reader, page, its);
                //PageCSVText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(PageCSVText)));
                //Byte[] b = Encoding.UTF8.GetBytes(PageCSVText);
                //PageCSVText = Encoding.UTF8.GetString(Encoding.ASCII.GetBytes(PageCSVText));
                //System.Diagnostics.Debug.WriteLine(PageText);
                builder.AppendLine(PageText);
            }
            reader.Close();

            return(builder.ToString());
        }
Пример #29
0
        public static string ReadPdfFile(Stream fileContent)
        {
            StringBuilder text = new StringBuilder();

               //if (File.Exists(fileName))
               {
               var pdfReader = new PdfReader(fileContent);

               for (int page = 1; page <= pdfReader.NumberOfPages; page++)
               {
                   ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                   string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

                   currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                   text.Append(currentText);
               }
               pdfReader.Close();
               }
               return text.ToString();
        }
Пример #30
0
        /**
         * Searches for a tag in a page.
         *
         * @param tag
         *            the name of the tag
         * @param obj
         *            an identifier to find the marked content
         * @param page
         *            a page dictionary
         * @throws IOException
         */
        public void ParseTag(String tag, PdfObject obj, PdfDictionary page)
        {
            PRStream stream = (PRStream)page.GetAsStream(PdfName.CONTENTS);

            // if the identifier is a number, we can extract the content right away
            if (obj is PdfNumber)
            {
                PdfNumber                  mcid      = (PdfNumber)obj;
                RenderFilter               filter    = new MarkedContentRenderFilter(mcid.IntValue);
                ITextExtractionStrategy    strategy  = new SimpleTextExtractionStrategy();
                FilteredTextRenderListener listener  = new FilteredTextRenderListener(strategy, new RenderFilter[] { filter });
                PdfContentStreamProcessor  processor = new PdfContentStreamProcessor(
                    listener);
                processor.ProcessContent(PdfReader.GetStreamBytes(stream), page
                                         .GetAsDict(PdfName.RESOURCES));
                outp.Write(SimpleXMLParser.EscapeXML(listener.GetResultantText(), true));
            }
            // if the identifier is an array, we call the parseTag method
            // recursively
            else if (obj is PdfArray)
            {
                PdfArray arr = (PdfArray)obj;
                int      n   = arr.Size;
                for (int i = 0; i < n; i++)
                {
                    ParseTag(tag, arr[i], page);
                    if (i < n - 1)
                    {
                        outp.WriteLine();
                    }
                }
            }
            // if the identifier is a dictionary, we get the resources from the
            // dictionary
            else if (obj is PdfDictionary)
            {
                PdfDictionary mcr = (PdfDictionary)obj;
                ParseTag(tag, mcr.GetDirectObject(PdfName.MCID), mcr
                         .GetAsDict(PdfName.PG));
            }
        }
Пример #31
0
        public static String ParsePDFtoString(String path)
        {
            StringBuilder text = new StringBuilder();
            try
            {
                PdfReader pdfReader = new PdfReader(path);

                for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                {
                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                    string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

                    currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                    text.Append(currentText);
                    pdfReader.Close();
                }
            }
            catch (Exception) { }

            return text.ToString();
        }
Пример #32
0
        public static string ReadText(string filename)
        {
            string strText = string.Empty;

            using (PdfReader documentReader = new PdfReader(filename))
            {
                for (int page = 1; page <= documentReader.NumberOfPages; page++)
                {
                    ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();

                    using (PdfReader pageReader = new PdfReader(filename))
                    {
                        String s = PdfTextExtractor.GetTextFromPage(pageReader, page, its);

                        s       = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
                        strText = strText + s;
                        pageReader.Close();
                    }
                }
            }
            return(strText);
        }
Пример #33
0
        private List <string> ExtractTextFromPdf(string path)
        {
            List <string> text = new List <string>();

            if (!File.Exists(path))
            {
                MessageBox.Show("Please give the valid path of the PDF file.");
            }
            PdfReader reader2 = new PdfReader(path);

            for (int page = 1; page <= reader2.NumberOfPages; page++)
            {
                ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
                PdfReader reader            = new PdfReader(path);
                String    s = PdfTextExtractor.GetTextFromPage(reader, page, its);
                s = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
                text.Add(s);
                reader.Close();
            }

            return(text);
        }
		public void Process(Crawler crawler, PropertyBag propertyBag)
		{
			AspectF.Define.
				NotNull(crawler, "crawler").
				NotNull(propertyBag, "propertyBag");

			if (propertyBag.StatusCode != HttpStatusCode.OK)
			{
				return;
			}

			if (!IsPdfContent(propertyBag.ContentType))
			{
				return;
			}

			using (Stream input = propertyBag.GetResponse())
			{
				PdfReader pdfReader = new PdfReader(input);
				try
				{
					string title;
					if (pdfReader.Info.TryGetValue("Title", out title))
					{
						propertyBag.Title = Convert.ToString(title, CultureInfo.InvariantCulture).Trim();
					}

					SimpleTextExtractionStrategy textExtractionStrategy = new SimpleTextExtractionStrategy();
					propertyBag.Text = Enumerable.Range(1, pdfReader.NumberOfPages).
						Select(pageNumber => PdfTextExtractor.GetTextFromPage(pdfReader, pageNumber, textExtractionStrategy)).
						Join(Environment.NewLine);
				}
				finally
				{
					pdfReader.Close();
				}
			}
		}
Пример #35
0
        void doSomething(PdfReader reader)
        {
            //pdfReader.Close();
            string tmp;

            PP.SimpleTextExtractionStrategy blah;
            tester atester = null;

            blah = new PP.SimpleTextExtractionStrategy();
            //Debug.WriteLine("here");
            for (int page = 1; page <= reader.NumberOfPages; page++)
            {
                //Debug.WriteLine("here");
                var avar = reader.GetLinks(page);
                //Debug.WriteLine("here");
                var v1 = reader.GetNamedDestinationFromNames();
                var v2 = reader.GetNamedDestinationFromStrings();
                var v3 = reader.GetPageContent(page);
                var v4 = reader.GetPageN(page);
                //var v5=reader.get
                //PP.SimpleTextExtractionStrategy blah = new PP.SimpleTextExtractionStrategy();
                tmp = blah.GetResultantText();
                if (atester == null)
                {
                    atester = new tester();
                }
                tmp = PP.PdfTextExtractor.GetTextFromPage(reader, page);
                tmp = PP.PdfTextExtractor.GetTextFromPage(reader, page, blah);
                tmp = PP.PdfTextExtractor.GetTextFromPage(reader, page, atester);
                PP.PdfContentReaderTool.ListContentStreamForPage(reader, page, Console.Out);

                //PdfReaderContentParser
                this.showPage(reader, page);
                //((PP.ITextExtractionStrategy) new tester()).
                Debug.WriteLine("here");
            }
        }
Пример #36
0
        /// <summary>
        /// Search specified text into this input file.
        /// </summary>
        /// <param name="text">Text to search.</param>
        /// <returns>
        /// A <see cref="PdfText"/> list of matches.
        /// </returns>
        public IEnumerable <PdfText> SearchText(string text)
        {
            Logger.Instance.Debug("");
            Logger.Instance.Debug(" Assembly: iTin.Utilities.Pdf.Writer, Namespace: iTin.Utilities.Pdf.Writer, Class: PdfInput");
            Logger.Instance.Debug(" earch specified text into this input file");
            Logger.Instance.Debug($" > Signature: ({typeof(IEnumerable<PdfText>)}) SearchText({typeof(string)})");
            Logger.Instance.Debug($"   > text: {text}");

            List <PdfText> matchs = new List <PdfText>();

            try
            {
                NativePdf.PdfReader pdfReader = new NativePdf.PdfReader(ToStream());
                int count = pdfReader.NumberOfPages;
                for (int page = 1; page <= count; page++)
                {
                    NativePdfParser.ITextExtractionStrategy strategy = new NativePdfParser.SimpleTextExtractionStrategy();
                    string currentText = NativePdfParser.PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
                    currentText = Encoding.UTF8.GetString(Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));

                    var absolutePosition = currentText.IndexOf(text, StringComparison.OrdinalIgnoreCase);
                    if (absolutePosition != -1)
                    {
                        matchs.Add(new PdfText(text, page, absolutePosition));
                    }
                }

                pdfReader.Close();
            }
            catch
            {
            }

            Logger.Instance.Debug($" > Output: {matchs.Count} item(s)");

            return(matchs);
        }
        public void searchWord(string filename) {
            
            string[] words = { "Взлом", "Хакер", "шаг" };
            List<int> pages = new List<int>();
                //if (File.Exists("C:\\1\\" + filename))
                //if (File.Exists("C:\\1\\Instr.pdf"))
            if (File.Exists(filename))
                {
                    //PdfReader pdfReader = new PdfReader("C:\\1\\" + filename);
                    //PdfReader pdfReader = new PdfReader("C:\\1\\Instr.pdf");
                    PdfReader pdfReader = new PdfReader(filename);

                    for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                        {
                            ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                            string currentPageText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
                         
                        for (int i = 0; i < words.Length; i++)
                            {
                                //bool switch1 = false;

                            if (currentPageText.Contains(words[i]))
                            {
                                pages.Add(page);
                                textBox1.Text += page.ToString();
                                textBox1.AppendText(Environment.NewLine);
                                textBox2.Text += words[i];
                                textBox2.AppendText(Environment.NewLine);
                                textBox2.Text += "\n";
                            }                               
                           }
                        }
                    pdfReader.Close();    
                    }
                    
                }
Пример #38
0
        private void readPdf(string fileToOpen)
        {
            try
            {

            PdfReader reader = new PdfReader(fileToOpen);
            // total number of pages
            int n = reader.NumberOfPages;
            // size of the first page
            Rectangle psize = reader.GetPageSize(1);
            float width = psize.Width;
            float height = psize.Height;
                string asd = "Size of page 1 of {0} => {1} × {2}"+ n+ width+ height;
             RoutesBoxList.Items.Add(asd);
            // file properties
            Dictionary<string, string> infodict = reader.Info;

            for (int page = 1; page <= reader.NumberOfPages; page++)
            {
                ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                string currentText = PdfTextExtractor.GetTextFromPage(reader, page, strategy);

                currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                                RoutesBoxList.Items.Add(currentText);
                                TestBox.Text = currentText;
            }
            foreach (KeyValuePair<string, string> kvp in infodict)
                RoutesBoxList.Items.Add(kvp.Key + " => " + kvp.Value);
            }
            catch (Exception e)
            {
                RoutesBoxList.Items.Add("Cannot deserialize PDF " + fileToOpen);
            }
        }
        //Read stop word list from text file called stopwords.txt
        //public string[] StopWords()
        //{
        //    string[] stopText = File.ReadAllLines("stopwords.txt");
        //    return stopText;
        //}
        public void ReadPdf(string pdfpath)
        {
            try
            {

                PdfReader pdfr = new PdfReader(pdfpath);
                StringBuilder pdfText = new StringBuilder();

                int tp = DocumentInfo.TotalPages;
                //loop to read pdf page by page

                for (int page = 1; page <= tp; page++)
                {
                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                    string currentText = PdfTextExtractor.GetTextFromPage(pdfr, page, strategy);

                    currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));

                    //currentText = currentText.ToLower();

                    POSTagger.mModelPath = "Models\\";
                    string[] tSplittedWords = GetWords(currentText);

                    string[] sentences = POSTagger.SplitSentences(currentText);

                    Sentences[] sentencearray = new Sentences[sentences.Count()];

                    int sc = sentences.Count();
                    for (int i = 0; i < sc; i++)
                    {
                        sentencearray[i] = new Sentences();

                        sentencearray[i].SentenceNumber = i + 1 + currentcountofsentences;

                        sentencearray[i].SentenceString = sentences[i].ToLower();
                        sentenceList.Add(sentencearray[i]);
                    }

                    currentcountofsentences += sentences.Count();

                    string[] POS = POSTagger.PosTagTokens(tSplittedWords);

                    splittedWords.Clear();
                    nrSplittedWords.Clear();
                    countList.Clear();

                    int poslength = POS.Length;
                    for (int i = 0; i < poslength; i++)
                    {
                        //NN Noun, singular or mass
                        //NNS Noun, plural
                        //NNP Proper noun, singular
                        //NNPS Proper noun, plural

                        if (POS[i] == "NN" || POS[i] == "NNS" || POS[i] == "NNP" || POS[i] == "NNPS")
                        {
                        tSplittedWords[i] = tSplittedWords[i].ToLower();
                        splittedWords.Add(tSplittedWords[i]);
                        }

                    }

                    //removing stop words from splittedwords list
                    List<string> t1SplittedWords = new List<string>();
                    foreach (string sw in splittedWords)
                    {

                        if (!Array.Exists(_stopWords, element => element == sw))
                        {

                            t1SplittedWords.Add(sw);

                        }

                        //this also works
                        //if (!_stopWords.Contains(sw))
                        //{
                        //    t1SplittedWords.Add(sw);
                        //}

                    }
                    splittedWords.Clear();
                    splittedWords = t1SplittedWords.ToList();

                    nrSplittedWords = splittedWords.Distinct().ToList();

                    int nrswcount = nrSplittedWords.Count;

                    _eachPageWordCount.Add(nrswcount);
                    _tUniqueWordsinPage = nrswcount;

                    //calculating frequency of words in each page i.e. Term Frequency

                    for (int i = 0; i < nrswcount; i++)
                    {
                        string searchItem = nrSplittedWords[i];

                        int count = 0;
                        for (int j = 0; j < splittedWords.Count(); j++)
                        {
                            if (searchItem == splittedWords[j])
                                count++;

                        }

                        countList.Add(count);

                    }
                    Words[] wordarray = new Words[nrSplittedWords.Count()];

                    for (int i = 0; i < nrswcount; i++)
                    {
                        wordarray[i] = new Words();
                        wordarray[i].Word = nrSplittedWords[i];
                        wordarray[i].TermFrequency = countList[i];
                        wordarray[i].Pageno = page;
                        wordList.Add(wordarray[i]);

                    }

                    //foreach (string s in nrSplittedWords)
                    //{
                    //    UniqueWordsinCorpus.Add(s);
                    //}
                    UniqueWordsinCorpus.AddRange(nrSplittedWords);

                    pdfText.Append(currentText);

                }                  //end of page loop

                pdfr.Close();

                //UniqueWordsinCorpus is a list of string of unique words
                UniqueWordsinCorpus = UniqueWordsinCorpus.Distinct().ToList();

                UniqueWordsinCorpus.Sort();

                foreach (Words w in wordList)
                {
                    int corf = 0;
                    foreach (Words w1 in wordList)
                    {
                        if (w.Word == w1.Word)
                            corf = corf + w1.TermFrequency;

                    }

                    w.CorpusFrequency = corf;
                }

                foreach (Words w in wordList)
                {
                    w.SentencenoWithFrequency = new Dictionary<int, int>();
                    foreach (Sentences s in sentenceList)
                    {
                        int sentfreq = 0;
                        string[] splittedwordsofsentence = GetWords(s.SentenceString);

                        int swoscount = splittedwordsofsentence.Count();
                        for (int i = 0; i < swoscount; i++)
                        {
                            if (w.Word == splittedwordsofsentence[i])
                                sentfreq++;
                        }
                        w.SentencenoWithFrequency.Add(s.SentenceNumber, sentfreq);
                    }
                }

                //wordList.Sort(delegate(Words w1, Words w2) { return w1.Word.CompareTo(w2.Word); });

                wordList.Sort((w1, w2) => w1.Word.CompareTo(w2.Word));

             //copying words from wordList of Words to uniquewordlist of uniquewords while removing the redundant entry

                UniqueWords[] uniquewordarray = new UniqueWords[UniqueWordsinCorpus.Count];

                int uwiccount = UniqueWordsinCorpus.Count;
                for (int i = 0; i < uwiccount; i++)
                {

                    uniquewordarray[i] = new UniqueWords();
                    uniquewordarray[i].SentencenoWithFrequency = new Dictionary<int, int>();
                    uniquewordarray[i].PagenoWithFrequency = new Dictionary<int, int>();
                    foreach (Words w in wordList)
                    {
                        if (UniqueWordsinCorpus[i] == w.Word)
                        {
                            if (uniquewordarray[i].Term == null)
                                uniquewordarray[i].Term = w.Word;

                            uniquewordarray[i].CorpusFrequency = w.CorpusFrequency;

                            uniquewordarray[i].SentencenoWithFrequency = w.SentencenoWithFrequency;

                            uniquewordarray[i].PagenoWithFrequency.Add(w.Pageno, w.TermFrequency);

                        }
                    }

                    UniqueWordList.Add(uniquewordarray[i]);

                }

             //computing document frequency of unique words

                foreach (UniqueWords uw in UniqueWordList)
                {
                    uw.DocFrequency = uw.PagenoWithFrequency.Count;
                }

                //Displaying uniquewords with their attribute values

                //foreach (UniqueWords uw in UniqueWordList)
                //{
                //    DocText.AppendText(uw.Term + "........");
                //    DocText.AppendText(uw.CorpusFrequency.ToString() + "\n");
                //    DocText.AppendText("Sentence no with frequency \n");
                //    List<KeyValuePair<int, int>> list = uw.SentencenoWithFrequency.ToList();
                //    foreach (KeyValuePair<int, int> pair in list)
                //    {
                //        if (pair.Value > 0)
                //        {
                //            DocText.AppendText(pair.Key.ToString() + ".......");
                //            DocText.AppendText(pair.Value.ToString() + Environment.NewLine);
                //        }

                //    }
                //    DocText.AppendText("Page no with freqency \n");
                //    List<KeyValuePair<int, int>> list1 = uw.PagenoWithFrequency.ToList();
                //    foreach (KeyValuePair<int, int> pair in list1)
                //    {
                //        if (pair.Value > 0)
                //        {
                //            DocText.AppendText(pair.Key.ToString() + ".......");
                //            DocText.AppendText(pair.Value.ToString() + Environment.NewLine);
                //        }

                //    }
                //}

                //foreach (Words w in wordList)
                //{
                //    DocText.AppendText(w.Word + Environment.NewLine);
                //    List<KeyValuePair<int, int>> list = w.SentencenoWithFrequency.ToList();
                //    foreach (KeyValuePair<int, int> pair in list)
                //    {
                //        if (pair.Value > 0)
                //        {
                //            DocText.AppendText(pair.Key.ToString() + ".......");
                //            DocText.AppendText(pair.Value.ToString() + Environment.NewLine);
                //        }

                //    }

                //}

                // matrixpro.GenerateMatrix(UniqueWordList);

                //UserWordsEditor uwe=new UserWordsEditor(UniqueWordList);
                //uwe.Show();

            }
            catch (Exception se)
            {

                MessageBox.Show(se.Message);
            }
        }
Пример #40
0
        public void ReadPdf(string path)
        {
            try
            {

                PdfReader pdfr = new PdfReader(path);
                StringBuilder pdfText = new StringBuilder();

                //loop to read pdf page by page

                for (int page = 1; page <= pdfr.NumberOfPages; page++)
                {
                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                    string currentText = PdfTextExtractor.GetTextFromPage(pdfr, page, strategy);

                    currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));

                    POSTagger.mModelPath = "Models\\";
                    string[] tSplittedWords = GetWords(currentText);

                    string[] sentences = POSTagger.SplitSentences(currentText);

                    sentencearray=new Sentences[sentences.Count()];

                    for (int i = 0; i < sentences.Count(); i++)
                    {
                        sentencearray[i]=new Sentences();

                        sentencearray[i].SentenceNumber = i+1+currentcountofsentences;

                        sentencearray[i].SentenceString = sentences[i];
                        sentenceList.Add(sentencearray[i]);
                    }

                    currentcountofsentences += sentences.Count();

                    string[] POS = POSTagger.PosTagTokens(tSplittedWords);

                    splittedWords.Clear();
                    nrSplittedWords.Clear();
                    countList.Clear();
                    for (int i = 0; i < POS.Length; i++)
                    {
                        //NN Noun, singular or mass
                        //NNS Noun, plural
                        //NNP Proper noun, singular
                        //NNPS Proper noun, plural
                        if (POS[i] == "NN" || POS[i] == "NNS" || POS[i] == "NNP" || POS[i] == "NNPS")

                            splittedWords.Add(tSplittedWords[i]);

                    }

                    nrSplittedWords = splittedWords.Distinct().ToList();

                    _tUniqueWordsinPage = nrSplittedWords.Count();

                   //calculating frequency of words in each page
                    for (int i = 0; i < nrSplittedWords.Count();i++ )
                    {
                        string searchItem = nrSplittedWords[i];

                        int count=0;
                        for (int j = 0; j < splittedWords.Count();j++ )
                        {
                            if (searchItem == splittedWords[j])
                                count++;
                        }

                            countList.Add(count);

                    }
                    wordarray=new Words[nrSplittedWords.Count()];

                    for (int i = 0; i < nrSplittedWords.Count(); i++)
                    {
                        wordarray[i] = new Words();

                        wordarray[i].Word = nrSplittedWords[i];
                        wordarray[i].DocFrequency = countList[i];
                        wordarray[i].Pageno=page;

                        wordList.Add(wordarray[i]);

                    }

                    foreach (string s in nrSplittedWords)
                    {
                        UniqueWordsinCorpus.Add(s);
                    }

                        pdfText.Append(currentText);

                }                  //end of page loop

                pdfr.Close();

                UniqueWordsinCorpus = UniqueWordsinCorpus.Distinct().ToList();
                UniqueWordsinCorpus.Sort();

                foreach (Words w in wordList)
                {
                    int corf = 0;
                    foreach (Words w1 in wordList)
                    {
                        if (w.Word == w1.Word)
                            corf = corf + w1.DocFrequency;

                    }

                    w.CorpusFrequency = corf;
                }

                foreach(Words w in wordList)
                {
                    w.SentencenoWithFrequency=new Dictionary<int, int>();
                    foreach(Sentences s in sentenceList)
                    {
                        int sentfreq = 0;
                        string[] splittedwordsofsentence = GetWords(s.SentenceString);
                        for(int i=0;i<splittedwordsofsentence.Count();i++)
                        {
                            if (w.Word == splittedwordsofsentence[i])
                                sentfreq++;
                        }
                       w.SentencenoWithFrequency.Add(s.SentenceNumber,sentfreq);
                    }
                }

                //wordList.Sort(delegate(Words w1, Words w2) { return w1.Word.CompareTo(w2.Word); });

                wordList.Sort((w1,w2) => w1.Word.CompareTo(w2.Word));

                //copying words from wordList of Words to uniquewordlist of uniquewords while removing the redundant entry

                uniquewordarray=new UniqueWords[UniqueWordsinCorpus.Count];
                for (int i = 0; i < UniqueWordsinCorpus.Count; i++)
                {

                    uniquewordarray[i] = new UniqueWords();
                    uniquewordarray[i].SentencenoWithFrequency = new Dictionary<int, int>();
                    uniquewordarray[i].PagenoWithFrequency = new Dictionary<int, int>();
                    foreach (Words w in wordList)
                    {
                        if (UniqueWordsinCorpus[i] == w.Word)
                        {
                            if(uniquewordarray[i].Term==null)
                            uniquewordarray[i].Term = w.Word;

                            uniquewordarray[i].CorpusFrequency = w.CorpusFrequency;

                            uniquewordarray[i].SentencenoWithFrequency = w.SentencenoWithFrequency;

                            uniquewordarray[i].PagenoWithFrequency.Add(w.Pageno,w.DocFrequency);

                        }
                    }

                    UniqueWordList.Add(uniquewordarray[i]);

                }

                //Displaying uniquewords with their attribute values

                foreach (UniqueWords uw in UniqueWordList)
                {
                    DocText.AppendText(uw.Term + "........");
                    DocText.AppendText(uw.CorpusFrequency.ToString() + "\n");
                    DocText.AppendText("Sentence no with frequency \n");
                    List<KeyValuePair<int, int>> list = uw.SentencenoWithFrequency.ToList();
                    foreach (KeyValuePair<int, int> pair in list)
                    {
                        if (pair.Value > 0)
                        {
                            DocText.AppendText(pair.Key.ToString() + ".......");
                            DocText.AppendText(pair.Value.ToString() + Environment.NewLine);
                        }

                    }
                    DocText.AppendText("Page no with freqency \n");
                    List<KeyValuePair<int, int>> list1 = uw.PagenoWithFrequency.ToList();
                    foreach (KeyValuePair<int, int> pair in list1)
                    {
                        if (pair.Value > 0)
                        {
                            DocText.AppendText(pair.Key.ToString() + ".......");
                            DocText.AppendText(pair.Value.ToString() + Environment.NewLine);
                        }

                    }
                }

                    foreach (Words w in wordList)
                    {
                        DocText.AppendText(w.Word + Environment.NewLine);
                        List<KeyValuePair<int, int>> list = w.SentencenoWithFrequency.ToList();
                        foreach (KeyValuePair<int, int> pair in list)
                        {
                            if (pair.Value > 0)
                            {
                                DocText.AppendText(pair.Key.ToString() + ".......");
                                DocText.AppendText(pair.Value.ToString() + Environment.NewLine);
                            }

                        }

                    }

                //Diplaying words with their page no and Docfrequency using objects
                foreach (Words w in wordList)
                {
                    WordnFrequencyTxtBox.AppendText(w.Pageno + "---------" + w.Word + "  -----------" + w.DocFrequency +"-----------"+w.CorpusFrequency+ System.Environment.NewLine);
                }

            }
            catch (Exception se)
            {

                MessageBox.Show(se.Message);
            }
        }
Пример #41
0
 /**
  * Searches for a tag in a page.
  * 
  * @param tag
  *            the name of the tag
  * @param obj
  *            an identifier to find the marked content
  * @param page
  *            a page dictionary
  * @throws IOException
  */
 public void ParseTag(String tag, PdfObject obj, PdfDictionary page) {
     PRStream stream = (PRStream) page.GetAsStream(PdfName.CONTENTS);
     // if the identifier is a number, we can extract the content right away
     if (obj is PdfNumber) {
         PdfNumber mcid = (PdfNumber) obj;
         RenderFilter filter = new MarkedContentRenderFilter(mcid.IntValue);
         ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
         FilteredTextRenderListener listener = new FilteredTextRenderListener(strategy, new RenderFilter[]{filter});
         PdfContentStreamProcessor processor = new PdfContentStreamProcessor(
                 listener);
         processor.ProcessContent(PdfReader.GetStreamBytes(stream), page
                 .GetAsDict(PdfName.RESOURCES));
         outp.Write(SimpleXMLParser.EscapeXML(listener.GetResultantText(), true));
     }
     // if the identifier is an array, we call the parseTag method
     // recursively
     else if (obj is PdfArray) {
         PdfArray arr = (PdfArray) obj;
         int n = arr.Size;
         for (int i = 0; i < n; i++) {
             ParseTag(tag, arr[i], page);
             if (i < n - 1)
                 outp.WriteLine();
         }
     }
     // if the identifier is a dictionary, we get the resources from the
     // dictionary
     else if (obj is PdfDictionary) {
         PdfDictionary mcr = (PdfDictionary) obj;
         ParseTag(tag, mcr.GetDirectObject(PdfName.MCID), mcr
                 .GetAsDict(PdfName.PG));
     }
 }
Пример #42
0
        public string runCheckPatientFolder(Hashtable checkChartNumbers)
        {

            DateTime startDateVal = DateTime.Now, endDateVal = DateTime.Now; 
            string []chartNumbers;
            
            //get directories under the encounter folder
            string []paths = Directory.GetDirectories(data["ENCOUNTER_FOLDER"], "*", SearchOption.TopDirectoryOnly);
            Array.Sort(paths); 
            FileInfo tempFile ; 
            int endIndex = paths.Length; 
            string[] encounterFiles, searchFiles;
            string textToAnalyze, currentText, currentEncounter;
            Regex rgx;
           
                            
            StringBuilder text;
            PdfReader pdfReader;
            //this is function of check pt folder//
            //john is this where the method is for checking pt folder?
            //this is the text that is searched for in the pdf
            string[] octFolder = data["OCT_TEXT_SEARCH"].Split(','), photosFAFolder = data["PHOTOFA_TEXT_SEARCH"].Split(',');
            string[] ultrasound = data["ULTRASOUND_TEXT_SEARCH"].Split(',');
            string[] vf = data["VF_TEXT_SEARCH"].Split(',');
            
            bool hasOctFolder = false, hasPhotosFolder = false, hasUltrasoundFolder = false, hasVFFolder = false;
            
            //string runLog = data["CKPTFOLDERS"] + startDateVal.ToString("yyyy-MM-dd");
            string runLog = data["CKPTFOLDERS"];
            Directory.CreateDirectory(runLog);
            runLog = runLog + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "-CKPTFOLDERS-" + startDateVal.ToString("yyyy-MM-dd") + ".txt";
            StreamWriter sw = new StreamWriter(runLog, true);
            MemoryStream stream = new MemoryStream();
            DateTime theDate;
            StringWriter tw = new StringWriter();
            foreach (DictionaryEntry entry in checkChartNumbers)
            {
                theDate = (DateTime)entry.Key;
                paths = Directory.GetDirectories(data["ENCOUNTER_FOLDER"] + Path.DirectorySeparatorChar +
                    theDate.ToString("yyyy-MM-dd"), "*", SearchOption.TopDirectoryOnly);
                chartNumbers = (string[])  entry.Value;

                for(int j = 0; j < chartNumbers.Length; j++)
                {
                    encounterFiles = Directory.GetFiles(data["ENCOUNTER_FOLDER"] + Path.DirectorySeparatorChar +
                        theDate.ToString("yyyy-MM-dd"), "*" + chartNumbers[j] + "*", SearchOption.AllDirectories);
                    //reset the flags that indicate whether or not the text was found
                    hasVFFolder = hasOctFolder = hasPhotosFolder = hasUltrasoundFolder = false;
                    
                    if (encounterFiles != null && encounterFiles.Length > 0)
                    {//if there are some encounter files
                        sw.WriteLine("{0}:", chartNumbers[j]);
                        tw.WriteLine("{0}:", chartNumbers[j]);
                    }
                    else
                    {//if there are no encounter files for the patient
                        // sw.WriteLine("{0}: no tests", chartNumbers[j]);
                        // tw.WriteLine("{0}: no tests", chartNumbers[j]);

                    }
                    for (int k = 0; k < encounterFiles.Length; k++)
                    {
                        pdfReader = new PdfReader(encounterFiles[k]);
                        tempFile = new FileInfo(encounterFiles[k]);
                        currentEncounter = tempFile.Name.Substring(0, 8);
                        text = new StringBuilder();
                        ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                        //grab the text from the pdf pages
                        for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                        {
                            currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
                            currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                            text.Append(currentText );
                        }
                        text = text.Replace("\n", " ");
                        textToAnalyze = text.ToString(); 
                         
                        if (!hasOctFolder)
                        {//if the OCT folder flag hasn't been set to true
                            for (int u = 0; u < octFolder.Length; u++)
                            {//loop through all the text items we should search for

                                rgx = new Regex(".*" + octFolder[u] + ":[\\s*]\\w+");//build the regular expression pattern that will be used to search the text
                                if (rgx.IsMatch(textToAnalyze))//search teh text
                                {//there we have a match. make sure there is a file in the 5OCT folder with the same encounter date prefix (currentEncounter)
                                    if (Directory.Exists(data["ROUTING_BASE"] + chartNumbers[j] + "\\5OCT\\"))
                                    {
                                        searchFiles = Directory.GetFiles(data["ROUTING_BASE"] + chartNumbers[j] + "\\5OCT\\", currentEncounter + "*.*", SearchOption.AllDirectories);
                                         
                                        if (searchFiles.Length > 0)
                                        {//we have files
                                            hasOctFolder = true;
                                            sw.WriteLine("\t{0}: OK", octFolder[u]);
                                            tw.WriteLine("&nbsp;&nbsp;{0}: OK", octFolder[u]);
                                        }
                                        else
                                        {//we don't have the files we should have
                                            sw.WriteLine("\t{0}: missing files", octFolder[u]);
                                            tw.WriteLine("&nbsp;&nbsp;{0}: missing files", octFolder[u]);
                                        }
                                    
                                    }
                                    else
                                    {
                                        sw.WriteLine("\t{0}: missing files and 5OCT folder", octFolder[u]);
                                        tw.WriteLine("&nbsp;&nbsp;{0}: missing files and 5OCT folder", octFolder[u]);
                                    }
                                }
                            }
                        }
                        if (!hasVFFolder)
                        {//if the OCT folder flag hasn't been set to true
                            for (int u = 0; u < vf.Length; u++)
                            {//loop through all the text items we should search for

                                rgx = new Regex(".*" + vf[u] + ":[\\s*]\\w+");//build the regular expression pattern that will be used to search the text
                                if (rgx.IsMatch(textToAnalyze))//search teh text
                                {//there we have a match. make sure there is a file in the 5OCT folder with the same encounter date prefix (currentEncounter)
                                    if (Directory.Exists(data["ROUTING_BASE"] + chartNumbers[j] + "\\6VF\\"))
                                    {
                                        searchFiles = Directory.GetFiles(data["ROUTING_BASE"] + chartNumbers[j] + "\\6VF\\", currentEncounter + "*.*", SearchOption.AllDirectories);
                                        
                                        if (searchFiles.Length > 0)
                                        {//we have files
                                            hasOctFolder = true;
                                            sw.WriteLine("\t{0}: OK", vf[u]);
                                            tw.WriteLine("&nbsp;&nbsp;{0}: OK", vf[u]);
                                        }
                                        else
                                        {//we don't have the files we should have
                                            sw.WriteLine("\t{0}: missing files", vf[u]);
                                            tw.WriteLine("&nbsp;&nbsp;{0}: missing files", vf[u]);
                                        }
                                    }
                                    else
                                    {
                                        sw.WriteLine("\t{0}: missing files and 6VF folder", vf[u]);
                                        tw.WriteLine("&nbsp;&nbsp;{0}: missing files and 6VF folder", vf[u]);

                                    }
                                }
                            }
                        }

                        if (!hasPhotosFolder)
                        {
                            for (int u = 0; u < photosFAFolder.Length; u++)
                            {
                                rgx = new Regex(".*" + photosFAFolder[u] + ":[\\s*]\\w+");
                                if (rgx.IsMatch(textToAnalyze))
                                {//there we have a match. make sure there is a file in the 5OCT folder with the same encounter date prefix
                                    if (Directory.Exists(data["ROUTING_BASE"] + chartNumbers[j] + "\\4photosFA\\"))
                                    {

                                        searchFiles = Directory.GetFiles(data["ROUTING_BASE"] + chartNumbers[j] + "\\4photosFA\\", currentEncounter + "*.*", SearchOption.AllDirectories);
                                         
                                        if (searchFiles.Length > 0)
                                        {//we have files
                                            hasPhotosFolder = true;
                                            sw.WriteLine("\t{0}: OK", photosFAFolder[u]);
                                            tw.WriteLine("&nbsp;&nbsp;{0}: OK", photosFAFolder[u]);
                                        }
                                        else
                                        {
                                            sw.WriteLine("\t{0}: missing files", photosFAFolder[u]);
                                            tw.WriteLine("&nbsp;&nbsp;{0}: missing files", photosFAFolder[u]);
                                        }
                                    }
                                    else
                                    {
                                        sw.WriteLine("\t{0}: missing files and 4photosFA folder", photosFAFolder[u]);
                                        tw.WriteLine("&nbsp;&nbsp;{0}: missing files and 4photosFA folder", photosFAFolder[u]);

                                    }
                                }
                            }
                        }

                        if (!hasUltrasoundFolder)
                        {
                            for (int u = 0; u < ultrasound.Length; u++)
                            {
                                rgx = new Regex(".*" + ultrasound[u] + ":[\\s*]\\w+");
                                if (rgx.IsMatch(textToAnalyze))
                                {//there we have a match. make sure there is a file in the 5OCT folder with the same encounter date prefix
                                    if (Directory.Exists(data["ROUTING_BASE"] + chartNumbers[j] + "\\7Ultrasound\\"))
                                    {
                                        searchFiles = Directory.GetFiles(data["ROUTING_BASE"] + chartNumbers[j] + "\\7Ultrasound\\", currentEncounter + "*.*", SearchOption.AllDirectories);
                                        
                                        if (searchFiles.Length > 0)
                                        {//we have files
                                            hasUltrasoundFolder = true;
                                            sw.WriteLine("\t{0}: OK", ultrasound[u]);
                                            tw.WriteLine("&nbsp;&nbsp;{0}: OK", ultrasound[u]);
                                        }
                                        else
                                        {
                                            sw.WriteLine("\t{0}: missing files", ultrasound[u]);
                                            tw.WriteLine("&nbsp;&nbsp;{0}: missing files", ultrasound[u]);
                                        }
                                    }
                                    else
                                    {
                                        sw.WriteLine("\t{0}: missing files and 7Ultrasound folder", photosFAFolder[u]);
                                        tw.WriteLine("&nbsp;&nbsp;{0}: missing files and 7Ultrasound folder", photosFAFolder[u]);

                                    }
                                }
                            }
                        }
                    }
                    /*if (matchedOct && !hasOctFolder)
                    {
                        sw.WriteLine("{0} {1} {2} {3}", DateTime.Now, chartNumbers[j], matchedOct ? "Should have OCT" : "Should not have OCT", hasOctFolder ? "Has files in OCT folder" : "Does not have OCT");
                        tw.WriteLine("{0} {1} {2} {3}", DateTime.Now, chartNumbers[j], matchedOct ? "Should have OCT" : "Should not have OCT", hasOctFolder ? "Has files in OCT folder" : "Does not have OCT");
                    }
                    if (matchedPhotos && !hasPhotosFolder)
                    {
                        sw.WriteLine("{0} {1} {2} {3}", DateTime.Now, chartNumbers[j], matchedPhotos ? "Should have PhotosFA" : "Should not have PhotosFA", hasPhotosFolder ? "Has files in PhotosFA folder" : "Does not have PhotosFA");
                        tw.WriteLine("{0} {1} {2} {3}", DateTime.Now, chartNumbers[j], matchedPhotos ? "Should have PhotosFA" : "Should not have PhotosFA", hasPhotosFolder ? "Has file in PhotosFA folder" : "Does not have PhotosFA");

                    }
                    if(matchedUltrasound && !hasUltrasoundFolder){
                        sw.WriteLine("{0} {1} {2} {3}", DateTime.Now, chartNumbers[j], matchedUltrasound ? "Should have Ultrasound" : "Should not have Ultrasound", hasUltrasoundFolder ? "Has files in Ultrasound folder" : "Does not have Ultrasound");
                        tw.WriteLine("{0} {1} {2} {3}", DateTime.Now, chartNumbers[j], matchedUltrasound ? "Should have Ultrasound" : "Should not have Ultrasound", hasUltrasoundFolder ? "Has files in Ultrasound folder" : "Does not have Ultrasound");
                    }*/

                }
            }

            if (tw.ToString().Length == 0)
            {
                /*for (int j = 0; j < chartNumbers.Length; j++)
                {
                    sw.WriteLine("{0}: no tests", chartNumbers[j]);
                    tw.WriteLine("{0}: no tests", chartNumbers[j]);
                }*/
            }

            sw.Close();
           return tw.ToString();
        }
Пример #43
0
        private static IEnumerable<String> GetPdfPagesContent(string path)
        {
            var pagesList = new List<String>();
            using (var pdfReader = new PdfReader(path))
            {
                for (var page = 1; page <= pdfReader.NumberOfPages; page++)
                {
                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy(); //  LocationTextExtractionStrategy();

                    var currentText = PdfTextExtractor.GetTextFromPage(
                        pdfReader,
                        page,
                        strategy);

                    currentText =
                        Encoding.UTF8.GetString(Encoding.Convert(
                            Encoding.Default,
                            Encoding.UTF8,
                            Encoding.Default.GetBytes(currentText)));

                   pagesList.Add(currentText);
                }
            }
            return pagesList;
        }
Пример #44
0
        public List<int> ReadPdfFile(string fileName, string searthText)
        {
            List<int> pages = new List<int>();
            if (File.Exists(fileName))
            {
                PdfReader pdfReader = new PdfReader(fileName);
                for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                {
                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();

                    string currentPageText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
                    if (currentPageText.Contains(searthText))
                    {
                        pages.Add(page);
                    }
                }
                pdfReader.Close();
            }
            return pages;
        }
Пример #45
0
 public static string getPDFText(string fileName)
 {
     PdfReader pdfReader = new PdfReader(fileName);
     StringBuilder text = new StringBuilder();
     for (int page = 1; page <= pdfReader.NumberOfPages; page++)
     {
         ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
         string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
         currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
         text.Append(currentText + "\r\n");
     }
     pdfReader.Close();
     return text.ToString();
 }
Пример #46
0
        private static List<Entry> ReadCembraPdf(string file)
        {
            List<Entry> entries = new List<Entry>();

            PdfReader pdfReader = new PdfReader(file);
            for (int page = 1; page <= pdfReader.NumberOfPages; page++)
            {
                ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

                currentText =
                    Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.GetEncoding("ISO-8859-1"), Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                string[] lines = currentText.Split('\n');
                bool startEntries = false;
                foreach (string line in lines)
                {
                    if (startEntries)
                    {
                        if (line.StartsWith("Kontonummer") || line.StartsWith("Diverses"))
                        {
                            break;
                        }

                        string normalizedline = line.Replace(" ", "");

                        DateTime date;
                        if (DateTime.TryParse(normalizedline.Substring(0, 10), out date))
                        {
                            string currency = "CHE";
                            if (normalizedline.Contains("DEU"))
                            {
                                currency = "DEU";
                            }
                            else if (normalizedline.Contains("GBR"))
                            {
                                currency = "GBR";
                            }
                            else if (normalizedline.Contains("LUX"))
                            {
                                currency = "LUX";
                            }
                            else if (normalizedline.Contains("FRA"))
                            {
                                currency = "FRA";
                            }

                            int currencyPos = normalizedline.IndexOf(currency, StringComparison.InvariantCulture);

                            if (currencyPos <= 0)
                            {
                                continue;
                            }

                            string text = normalizedline.Substring(20, currencyPos - 20);
                            double amount = Double.Parse(normalizedline.Substring(currencyPos + 3));

                            entries.Add(new Entry
                            {
                                Amount = -1*amount,
                                Date = date,
                                Text = text
                            });
                        }
                    }

                    if (line.StartsWith("Einkaufs-Datum"))
                    {
                        startEntries = true;
                    }
                }
            }

            pdfReader.Close();

            return entries;
        }
Пример #47
0
        // Es wird der gesuchte Ausdruck aus der PDF-Fatei ausgelesen.
        public List<string> ReadPdfFile(string fileName, string RegexPattern, string begrenzer1, string begrenzer2, int pComboBoxIndex)
        {
            StringBuilder text = new StringBuilder();

            PdfReader pdfReader = new PdfReader(fileName);

            // Jede einzelne Seite wird ausgelesen.

            for (int page = 1; page <= pdfReader.NumberOfPages; page++)
            {
                ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                string derGesamteAusgeleseneTextInEinemString = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

                if (begrenzer1 != "")
                {
                    // Überflüssiges vorne abschneiden

                    Regex regex = new Regex(begrenzer1);

                    string[] substrings = regex.Split(derGesamteAusgeleseneTextInEinemString);

                    derGesamteAusgeleseneTextInEinemString = substrings[1];
                }

                if (begrenzer2 != "")
                {
                    // Überflüssiges hinten abschneiden

                    Regex hinten = new Regex(begrenzer2);

                    string[] substrings = hinten.Split(derGesamteAusgeleseneTextInEinemString);

                    derGesamteAusgeleseneTextInEinemString = substrings[0];
                }

                derGesamteAusgeleseneTextInEinemString = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(derGesamteAusgeleseneTextInEinemString)));
                text.Append(derGesamteAusgeleseneTextInEinemString);

                pdfReader.Close();

                //MessageBox.Show(derGesamteAusgeleseneTextInEinemString);
            }

            // Auf jeder Seite können auch mehr als eine gefundene Adresse verarbeitet werden.

            System.Text.RegularExpressions.MatchCollection matches;

            // Bei der E-Mail-Adresse wird Groß-/Kleinschreibung nicht unterschieden. Beim Kürzel, Namen etc. schon.

            if (pComboBoxIndex == 0)
            {
                 matches = System.Text.RegularExpressions.Regex.Matches(text.ToString(), RegexPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            }
            else
            {
                 matches = System.Text.RegularExpressions.Regex.Matches(text.ToString(), RegexPattern);
            }

            List<string> gefundeneReguläreAusdrücke = new List<string>();

            int zaehler = 0;

            string ausgabe = "";

            foreach (Match match in matches)
            {

                // Wenn in den Einstellungen festgelegt ist, dass eine bestimmte Domain ignoriert wird, wird ggfs. nichts zurückgegeben.

                if ((Properties.Settings.Default.DieseDomainIgnorieren != "" && match.Value.EndsWith(Properties.Settings.Default.DieseDomainIgnorieren)) || (Properties.Settings.Default.DieseMailIgnorieren != "" && match.Value == Properties.Settings.Default.DieseMailIgnorieren))
                {
                    gefundeneReguläreAusdrücke.Add("Die gefundene E-Mail-Adresse wird aufgrund Ihrer Einstellungen ignoriert.");
                    ausgabe = "\n" + ausgabe + "\n" + "Die gefundene E-Mail-Adresse wird aufgrund Ihrer Einstellungen ignoriert.";
                }
                else
                {
                    gefundeneReguläreAusdrücke.Add(match.Value.ToString());
                    ausgabe = "\n" + ausgabe + "\n" + match.Value.ToString();
                }

                zaehler++;
            }

            return gefundeneReguläreAusdrücke;
        }
Пример #48
0
 public override void ParseTag(String tag, PdfObject obj, PdfDictionary page) {
     if (obj is PdfNumber) {
         PdfNumber mcid = (PdfNumber) obj;
         RenderFilter filter = new MyMarkedContentRenderFilter(mcid.IntValue);
         ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
         FilteredTextRenderListener listener = new FilteredTextRenderListener(
             strategy, filter);
         PdfContentStreamProcessor processor = new PdfContentStreamProcessor(
             listener);
         processor.ProcessContent(PdfReader.GetPageContent(page), page
                                                                      .GetAsDict(PdfName.RESOURCES));
         outp.Write(XMLUtil.EscapeXML(listener.GetResultantText(), true));
     }
     else {
         base.ParseTag(tag, obj, page);
     }
 }
Пример #49
0
        private void button1_Click(object sender, EventArgs e)
        {

            iTextSharp.text.FontFactory.RegisterDirectories();
           
 
            timer1.Stop();
            button5.Text = "P L A Y";
            OpenFileDialog dlg = new OpenFileDialog();
            string filepath;
            dlg.Filter = "PDF files(*.PDF)|*.PDF|All files(*.*)|*.*";
           // axFoxitCtl1.OpenFile("");

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                filepath = dlg.FileName.ToString();

                string strText = string.Empty;
                try
                {

                    PdfReader reader = new PdfReader(filepath);
                    for (int page = 1; page <= reader.NumberOfPages; page++)
                    {
                        ITextExtractionStrategy its ;//= new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy(); //LocationTextExtractionStrategy

                        if (radioButton3.Checked)
                        {
                             its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy(); //LocationTextExtractionStrategy
                        }
                        else {
                             its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy(); //LocationTextExtractionStrategy
                        
                        }
                        String s;
                        s = PdfTextExtractor.GetTextFromPage(reader, page, its);

                        if (false)
                        {
                            var fTahoma = FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H);

                            var pi = new Phrase(s, fTahoma);
                            s = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Unicode, Encoding.UTF8, Encoding.Unicode.GetBytes(pi.Content)));
                            char[] charArray = s.ToCharArray();
                            Array.Reverse(charArray);
                            s = new string(charArray);
                        }

                       var ss = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));

                       
                        //s = s.ToString;
                        strText = strText + " " +ss;
                        MyText.Text = strText;
                        //MyText.RightToLeft = MyText.Fon

                    }
                    reader.Close();
                    i = 0;
                   strText = strText.Replace("\t", " ");
                   strText = strText.Replace("  ", " ");
                  strText =  strText.Replace("\u2000", " ");
                    strText = strText.Replace(Environment.NewLine, "\n");
                    if (mychar == '\n')
                    {
                        strText = strText.Replace("\n", " ");
                        strText = strText.Replace(".", ". " + mychar);
                    }
                    words = strText.Split(new char[] { mychar}, StringSplitOptions.RemoveEmptyEntries);
                    progressBar1.Maximum = words.Length;
                    timer1.Stop();
                    button5.Text = "P L A Y";
                    System.Diagnostics.Process.Start(filepath);
                    //axFoxitCtl1.OpenFile();
                    //axAcroPDF2.LoadFile(filepath);
                    //axAcroPDF2.src = filepath;
                    //axAcroPDF2.Show();
                   


                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);
                }
            }

        }
Пример #50
-27
        public static void SetProperties(string filename)
        {
            Filename = filename;
            FileInfo fi = new FileInfo(Filename);
            Size = Math.Round(Convert.ToDouble(fi.Length)/(1048576), 2);    //1048576=1024*1024
            Extension = fi.Extension;

            if (Extension == ".pdf")
            {
                DocumentType = "Portable Document Format(.pdf)";

                PdfReader pdfr = new PdfReader(Filename);
                StringBuilder pdfText = new StringBuilder();

                TotalPages = pdfr.NumberOfPages;

                //loop to read pdf page by page

                for (int page = 1; page <= pdfr.NumberOfPages; page++)
                {
                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                    string currentText = PdfTextExtractor.GetTextFromPage(pdfr, page, strategy);

                    currentText =
                        Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8,
                                                                      Encoding.Default.GetBytes(currentText)));

                    pdfText.Append(currentText);
                }

                pdfr.Close();

                string completetext=pdfText.ToString();
               // NoOfWords=completetext.Split(' ').Length;

                NoOfWords=Regex.Matches(completetext, @"[A-Za-z0-9]+").Count;

            }

            else if (Extension == ".odt")
            {
                DocumentType = "Open Document Format(.odt)";
                ComputeStatistics();

            }

            else if (Extension == ".docx")
            {
                DocumentType = "Microsoft Word Document(.docx)";
                ComputeStatistics();
            }

            else
            {
                DocumentType = "Word 97-2003 document(.doc)";
                ComputeStatistics();

            }
        }