Exemple #1
0
        private bool ValidateSO(string so, CAcroPDDoc pdDoc, int id)
        {
            bool   result       = false;
            Regex  isSO         = new Regex("\\d{7}");
            Regex  isTooLong    = new Regex("\\d{8}");
            Regex  notNumbers   = new Regex("[a-z, 0, \n]*");
            string replaceClear = "";

            so = notNumbers.Replace(so, replaceClear);
            if (isSO.IsMatch(so) && !isTooLong.IsMatch(so))
            {
                if (_dataProvider.Exists("Name 1", so))
                {
                    string dataName1 = _dataProvider.GetData("Name 1", so);
                    int    endPages  = pdDoc.GetNumPages();
                    for (int page = 0; page < endPages; page++)
                    {
                        string readName1 = GetName1(GetPageID(page), page, so);
                        result = Levenshtein.EditDistance.IsCloseTo(readName1, dataName1, 0.5);
                        if (result)
                        {
                            break;
                        }
                    }
                }
            }

            return(result);
        }
Exemple #2
0
        void runJob(Action job)
        {
            if (!File.Exists(PdfFilePath))
            {
                throw new InvalidOperationException(BadFileErrorMessage);
            }

            var acrobatPdfDocType = Type.GetTypeFromProgID("AcroExch.PDDoc");

            if (acrobatPdfDocType == null || !isAdobeSdkInstalled)
            {
                throw new InvalidOperationException(SdkError);
            }

            _pdfDoc = (CAcroPDDoc)Activator.CreateInstance(acrobatPdfDocType);
            if (_pdfDoc == null)
            {
                throw new InvalidOperationException(AdobeObjectsErrorMessage);
            }

            var acrobatPdfRectType = Type.GetTypeFromProgID("AcroExch.Rect");

            _pdfRect = (CAcroRect)Activator.CreateInstance(acrobatPdfRectType);

            var result = _pdfDoc.Open(PdfFilePath);

            if (!result)
            {
                throw new InvalidOperationException(BadFileErrorMessage);
            }

            job();

            releaseComObjects();
        }
Exemple #3
0
        // test
        public Boolean OCRDocumentAndSave(String szPdfPathConst)
        {
            CAcroAVDoc avDoc;
            CAcroApp   avApp;

            avApp = new AcroAppClass();
            avDoc = new AcroAVDocClass();
            avApp.Show();

            //open the PDF
            if (avDoc.Open(szPdfPathConst, ""))
            {
                //set the pdDoc object and get some data
                CAcroPDDoc pdDoc = (CAcroPDDoc)avDoc.GetPDDoc();
                try
                {
                    avApp.MenuItemExecute("TouchUp:EditDocument");
                    //System.Threading.Thread.Sleep(1000);
                    avApp.MenuItemExecute("Save");
                }catch (Exception e)
                {
                    return(false);
                }
                avApp.CloseAllDocs();
                avApp.Exit();

                return(true);
            }
            avApp.Exit();
            return(false);
        }
Exemple #4
0
        public void Dispose()
        {
            _pDDoc?.Close();
            _avDoc?.Close(-1);

            _pDDoc = null;
            _pDDoc = null;
        }
Exemple #5
0
        /* Adds two watermarks: one using a pdf file and a the second text.
         * You can use the stamp.pdf file in the TestFiles directory.
         */
        private void addWatermarkButton_Click(object sender, EventArgs e)
        {
            String filter = "PDF Files (*.pdf)|*.PDF|" +
                            "All files (*.*)|*.*";
            String filename = chooseFile(filter);

            if (filename != null && g_AVDoc.IsValid())
            {
                CAcroPDDoc pdDoc = (CAcroPDDoc)g_AVDoc.GetPDDoc();
                //Acquire the Acrobat JavaScript Object interface from the PDDoc object
                Object jsObj = pdDoc.GetJSObject();

                /* Add a watermark from a file.
                 * See the readme for a discussion on InvokeMember.
                 * function prototype:
                 * addWatermarkFromFile(cDIPath, nSourcePage, nStart, nEnd, bOnTop, bOnScreen, bOnPrint, nHorizAlign, nVertAlign, nHorizValue, nVertValue, bPercentage, nScale, bFixedPrint, nRotation, nOpacity)
                 */
                object[] addFileWatermarkParam = { filename, 0, 0, 0, true, true, true, 0, 3, 10, -10, false, 0.4, false, 0, 0.7 };

                Type T = jsObj.GetType();
                T.InvokeMember(
                    "addWatermarkFromFile",
                    BindingFlags.InvokeMethod |
                    BindingFlags.Public |
                    BindingFlags.Instance,
                    null, jsObj, addFileWatermarkParam);

                //get current time and make a string from it
                System.DateTime currentTime = System.DateTime.Now;

                /* make a color object */
                Object colorObj = T.InvokeMember(
                    "color",
                    BindingFlags.GetProperty |
                    BindingFlags.Public |
                    BindingFlags.Instance,
                    null, jsObj, null);
                Type   colorType    = colorObj.GetType();
                Object blueColorObj = colorType.InvokeMember(
                    "blue",
                    BindingFlags.GetProperty |
                    BindingFlags.Public |
                    BindingFlags.Instance,
                    null, colorObj, null);

                /* Add a text watermark.
                 * ' function prototype:
                 * '   addWatermarkFromText(cText, nTextAlign, cFont, nFontSize, color, nStart, nEnd, bOnTop, bOnScreen, bOnPrint, nHorizAlign, nVertAlign, nHorizValue, nVertValue, bPercentage, nScale, bFixedPrint, nRotation, nOpacity)
                 */
                object[] addTextWatermarkParam = { currentTime.ToShortTimeString(), 1, "Helvetica", 100, blueColorObj, 0, 0, true, true, true, 0, 3, 20, -45, false, 1.0, false, 0, 0.7 };
                T.InvokeMember(
                    "addWatermarkFromText",
                    BindingFlags.InvokeMethod |
                    BindingFlags.Public |
                    BindingFlags.Instance,
                    null, jsObj, addTextWatermarkParam);
            }
        }
Exemple #6
0
 public Pdf(string fileName)
 {
     _fileName = fileName;
     _document = (CAcroPDDoc)Interaction.CreateObject("AcroExch.PDDoc", "");
     if (!_document.Open(fileName))
     {
         throw new FileNotFoundException(fileName);
     }
     _rect = (CAcroRect)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.Rect", "");
 }
 ///<summary>
 ///Returns the PDDoc object associated with this instance.
 ///</summary>
 private CAcroPDDoc GetPDDocFromFile(string directory)
 {
     _avDoc = (CAcroAVDoc)_app.GetAVDoc(0);
     if (_avDoc.Open(directory, "autoTemp"))
     {
         CAcroPDDoc result = (CAcroPDDoc)_avDoc.GetPDDoc();
         return(result);
     }
     else
     {
         return(null);
     }
 }
Exemple #8
0
        private static string GetFileName()
        {
            CAcroPDDoc pdDoc = (CAcroPDDoc)g_AVDoc.GetPDDoc();
            Object     jsObj = pdDoc.GetJSObject();
            Type       T     = jsObj.GetType();

            return(((string)T.InvokeMember(
                        "documentFileName",
                        BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance,
                        null,
                        jsObj,
                        null
                        )).Replace(".pdf", ""));
        }
Exemple #9
0
        private static int GetPageCount()
        {
            CAcroPDDoc pdDoc = (CAcroPDDoc)g_AVDoc.GetPDDoc();
            Object     jsObj = pdDoc.GetJSObject();
            Type       T     = jsObj.GetType();

            return(Convert.ToInt32((double)T.InvokeMember(
                                       "numPages",
                                       BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance,
                                       null,
                                       jsObj,
                                       null
                                       )));
        }
Exemple #10
0
        private static void ExportPages()
        {
            CAcroPDDoc pdDoc = (CAcroPDDoc)g_AVDoc.GetPDDoc();
            Object     jsObj = pdDoc.GetJSObject();
            Type       T     = jsObj.GetType();

            int pages = GetPageCount();

            Console.WriteLine("The file {0} contains {1} pages", GetFileName(), pages);

            for (int i = 0; i < pages; i++)
            {
                Console.WriteLine("Page {0} name: {1}", i + 1, GetPageName(i));
                SavePage(i, GetPageName(i), GetFileName());
            }
        }
Exemple #11
0
        private static void SavePage(int page, string pageName, string fileName)
        {
            CAcroPDDoc pdDoc = (CAcroPDDoc)g_AVDoc.GetPDDoc();
            Object     jsObj = pdDoc.GetJSObject();
            Type       T     = jsObj.GetType();

            object[] parameters =
            {
                page,
                page,
                outputPath + fileName + pageName + ".pdf"
            };
            T.InvokeMember(
                "extractPages",
                BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance,
                null,
                jsObj,
                parameters
                );
        }
Exemple #12
0
        private void CreateFile(int startPageNum, int lenPages, CAcroPDDoc fromDoc, string saveToDirectory, string so)
        {
            CAcroAVDoc newAVDoc = _pdfProvider.GetAcroAVDoc();
            CAcroPDDoc newPDDoc = (CAcroPDDoc)newAVDoc.GetPDDoc();


            try
            {
                newPDDoc.Create();
                newPDDoc.InsertPages(-1, fromDoc, startPageNum - 1, lenPages, 0);
                OnFileCreated(saveToDirectory);
            }
            catch
            {
            }
            finally
            {
                newPDDoc?.Close();
                newAVDoc?.Close(-1);
            }
        }
Exemple #13
0
        public void Publish(string tempFilePath, string so, string label, int startPageNum, int endPageNum, bool eof = false)
        {
            _pDDoc = GetPDDocFromFile(tempFilePath);
            int lenPages = GetEndPages(eof, endPageNum) - startPageNum;

            try
            {
                if (_pDDoc != null)
                {
                    string fullPath = GetPublishDirectory(so, label);
                    string copyPath = GetCopyDirectory(so, label);
                    FileCreated += this_OnFileCreated;
                    CreateFile(startPageNum, lenPages, _pDDoc, fullPath, so);
                }
            }
            catch
            {
            }
            finally
            {
                _pDDoc.Close();
            }
        }
Exemple #14
0
        private static string GetPageName(int page)
        {
            CAcroPDDoc pdDoc = (CAcroPDDoc)g_AVDoc.GetPDDoc();
            Object     jsObj = pdDoc.GetJSObject();
            Type       T     = jsObj.GetType();

            object[] parameters = { page };
            string   fullName   = (string)T.InvokeMember(
                "getPageLabel",
                BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance,
                null,
                jsObj,
                parameters
                );

            Match match = pageNameRegex.Match(fullName);

            if (match.Success)
            {
                return(match.Value);
            }

            return(fullName);
        }
Exemple #15
0
        //[TestMethod]
        public void GetPageID_ReturnsNeg1_GivenNotRecognizedPDFPage()
        {
            //Arrange
            Acrobat_COM acrobat_COM = new Acrobat_COM(nondefined_ValidPDF_path);
            CAcroPDDoc  pDDoc       = acrobat_COM.PDDocs[0];

            AcrobatPostOCR postOCR = new AcrobatPostOCR(dataProvider, pDDoc);
            MailItem       mail    = Factory.GetTestMail_withPDFAttachment
                                     (
                Factory.GetOutlookApplication(),
                nondefined_ValidPDF_path
                                     );
            int firstPage = 1;

            int expected = -1;


            //Act
            int actual = postOCR.GetPageID(firstPage);


            //Assert
            Assert.AreEqual(expected, actual);
        }
        /// <summary>
        /// Constructor invoked on auto creation of files.
        /// </summary>
        /// <param name="src"></param>
        /// <param name="list"></param>
        /// <param name="cvLen"></param>
        /// <param name="bind"></param>
        /// <param name="ticket"></param>
        /// <param name="atty"></param>
        public ImposeSaddleStitch(
            string src,
            IOrderedEnumerable <CockleFilePdf> list,
            int cvLen,
            TypeOfBindEnum bind,
            int?ticket,
            string atty)
        {
            SourceFolder    = src;
            ImposedFiles    = new List <CockleFilePdf>(list);
            TypeOfBind      = bind;
            CoverLength     = cvLen;
            PageCountOfBody = 0;
            NewFilesCreated = new List <CockleFilePdf>();

            // get total page count
            ImposedFiles.ForEach(f =>
            {
                using (PdfReader r = new PdfReader(f.FullName))
                {
                    PageCountOfBody += r.NumberOfPages;
                }
            });
            if (PageCountOfBody == 0)
            {
                PageCountOfBody = null;
            }

            // create folder for processed files
            ProcessedFolder = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(SourceFolder, "processed"));

            // create new file names
            NewFileNames = new Dictionary <string, string>
            {
                { "Cover", System.IO.Path.Combine(ProcessedFolder.FullName, "Cover.pdf") },
                { "Brief", System.IO.Path.Combine(ProcessedFolder.FullName, "Brief.pdf") },
                { "Combined", System.IO.Path.Combine(ProcessedFolder.FullName, "Combined.pdf") },
                { "FinalVersion", System.IO.Path.Combine(SourceFolder, string.Format(
                                                             "{0} {1} cv{2}{3}br{4}{5}B4 pr.pdf", ticket, atty,
                                                             ImposedFiles.Any(x => x.FileType == SourceFileTypeEnum.InsideCv) ? " icv " : " ",
                                                             ImposedFiles.Any(x => x.FileType == SourceFileTypeEnum.Motion) ? " brmo " : " ",
                                                             ImposedFiles.Any(x => x.FileType == SourceFileTypeEnum.App_Index) ? " ain " : " ",
                                                             ImposedFiles.Any(x => x.FileType == SourceFileTypeEnum.App_File) ? " app " : " ")
                                                         .Replace("  ", " ")) },
                { "FinalVersionWithOnlyCover", System.IO.Path.Combine(SourceFolder, string.Format("{0} {1} cv B4 pr.pdf", ticket, atty)) }
            };

            bool hasCover = ImposedFiles.Any(f => f.FileType == SourceFileTypeEnum.Cover);

            if (hasCover)
            {
                ImposeCover(ImposedFiles, NewFileNames["Cover"]);
            }

            bool hasOnlyCover = true;

            ImposedFiles.ForEach(f => { if (f.FileType != SourceFileTypeEnum.Cover)
                                        {
                                            hasOnlyCover = false;
                                        }
                                 });
            if (!hasOnlyCover)
            {
                ImposeBrief(ImposedFiles, NewFileNames["Brief"], TypeOfBind);
            }

            // COMBINE COVER WITH BRIEF
            try
            {
                if (hasCover && !hasOnlyCover)
                {
                    if (!combinedImposedCoverAndBrief(NewFileNames["Brief"], NewFileNames["Cover"], NewFileNames["Combined"]))
                    {
                        System.Diagnostics.Debug.WriteLine("Failure here!");
                    }
                }
            }
            catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); }

            // copy file to main folder
            try
            {
                if (System.IO.File.Exists(NewFileNames["FinalVersion"]))
                {
                    System.IO.File.Delete(NewFileNames["FinalVersion"]);
                }
                //File.Copy(NewFileNames["Combined"], NewFileNames["FinalVersion"], true);

                // open, save, close with acrobat
                AcroApp   _myAdobe = new Acrobat.AcroApp();
                AcroAVDoc _acroDoc = new AcroAVDoc();

                CAcroPDDoc _pdDoc = null;
                if (hasOnlyCover)
                {
                    _acroDoc.Open(NewFileNames["Cover"], null);
                    _pdDoc = (Acrobat.AcroPDDoc)(_acroDoc.GetPDDoc());
                    _pdDoc.Save(1, NewFileNames["FinalVersionWithOnlyCover"]);

                    // keep track of files created
                    NewFilesCreated.Add(new CockleFilePdf(
                                            NewFileNames["FinalVersionWithOnlyCover"], atty, ticket, SourceFileTypeEnum.Imposed_Cover, ""));
                }
                else
                {
                    _acroDoc.Open(NewFileNames["Combined"], null);
                    _pdDoc = (Acrobat.AcroPDDoc)(_acroDoc.GetPDDoc());
                    _pdDoc.Save(1, NewFileNames["FinalVersion"]);

                    // keep track of files created
                    NewFilesCreated.Add(new CockleFilePdf(
                                            NewFileNames["FinalVersion"], atty, ticket, SourceFileTypeEnum.Imposed_Cover_and_Brief, ""));
                }
                _pdDoc.Close();
                _acroDoc.Close(0);
                _myAdobe.Exit();
            }
            catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); }

            // attempt to delete processed folder
            try { ProcessedFolder.Delete(true); }
            catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); }
        }
Exemple #17
0
        //http://www.myexception.cn/c-sharp/1506415.html
        //http://www.aspose.com/docs/display/pdfnet/Generate+Thumbnail+Images+from+PDF+Documents
        public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath,
                                            string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, double resolution)
        {
            CAcroPDDoc  pdfDoc   = null;
            CAcroPDPage pdfPage  = null;
            CAcroRect   pdfRect  = null;
            CAcroPoint  pdfPoint = null;

            // Create the document (Can only create the AcroExch.PDDoc object using late-binding)
            // Note using VisualBasic helper functions, have to add reference to DLL
            pdfDoc = (CAcroPDDoc)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.PDDoc", "");

            // validate parameter
            if (!pdfDoc.Open(pdfInputPath))
            {
                throw new FileNotFoundException();
            }
            if (!Directory.Exists(imageOutputPath))
            {
                Directory.CreateDirectory(imageOutputPath);
            }
            if (startPageNum <= 0)
            {
                startPageNum = 1;
            }
            if (endPageNum > pdfDoc.GetNumPages() || endPageNum <= 0)
            {
                endPageNum = pdfDoc.GetNumPages();
            }
            if (startPageNum > endPageNum)
            {
                int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum;
            }
            if (imageFormat == null)
            {
                imageFormat = ImageFormat.Jpeg;
            }
            if (resolution <= 0)
            {
                resolution = 1;
            }

            // start to convert each page
            for (int i = startPageNum; i <= endPageNum; i++)
            {
                pdfPage  = (CAcroPDPage)pdfDoc.AcquirePage(i - 1);
                pdfPoint = (CAcroPoint)pdfPage.GetSize();
                pdfRect  = (CAcroRect)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.Rect", "");

                int imgWidth  = (int)((double)pdfPoint.x * resolution);
                int imgHeight = (int)((double)pdfPoint.y * resolution);

                pdfRect.Left   = 0;
                pdfRect.right  = (short)imgWidth;
                pdfRect.Top    = 0;
                pdfRect.bottom = (short)imgHeight;

                // Render to clipboard, scaled by 100 percent (ie. original size)
                // Even though we want a smaller image, better for us to scale in .NET
                // than Acrobat as it would greek out small text
                pdfPage.CopyToClipboard(pdfRect, 0, 0, (short)(100 * resolution));

                IDataObject clipboardData = Clipboard.GetDataObject();

                if (clipboardData != null && clipboardData.GetDataPresent(DataFormats.Bitmap))
                {
                    string _dir  = Path.Combine(imageOutputPath, imageName);
                    string _path = _dir + "_" + i.ToString() + ".jpg";
                    if (File.Exists(_path))
                    {
                        File.Delete(_path);
                    }

                    Bitmap pdfBitmap = (Bitmap)clipboardData.GetData(DataFormats.Bitmap);
                    pdfBitmap.Save(_path, imageFormat);
                    pdfBitmap.Dispose();
                }
            }

            pdfDoc.Close();
            Marshal.ReleaseComObject(pdfPage);
            Marshal.ReleaseComObject(pdfRect);
            Marshal.ReleaseComObject(pdfDoc);
            Marshal.ReleaseComObject(pdfPoint);
        }
Exemple #18
0
 public AcrobatPostOCR(IOrderDataProvider dataProvider, CAcroPDDoc pDDoc)
 {
     _dataProvider = dataProvider;
     _pdDoc        = pDDoc;
 }
Exemple #19
0
        /* open data file, and then create individual forms for each row.
         * The open document must contain an template. You can use FormSample.pdf
         * and data.txt in the TestFiles directory.
         */
        private void processFormDataButton_Click(object sender, EventArgs e)
        {
            String filter = "Text Files (*.txt)|*.TXT|" +
                            "All files (*.*)|*.*";
            String filename = chooseFile(filter);

            if (filename != null && g_AVDoc.IsValid())
            {
                CAcroPDDoc pdDoc = (CAcroPDDoc)g_AVDoc.GetPDDoc();
                Object     jsObj = pdDoc.GetJSObject();

                /*For each row in data.txt, as defined by the NUM_ROWS constant, we:
                 *
                 *  1. Spawn the form template.
                 *  2. Populate the form with the data from data.txt.
                 *  3. Save the PDF.
                 */
                Object newDoc         = null;
                Object template       = null;
                bool   formDataExists = true;
                int    currentIndex   = 0;
                while (formDataExists)
                {
                    /*Acquire the form template and spawn a new page.
                     *
                     * We could use the doc.templates object to get all templates
                     * in the doc and then spawn the first, but since we have a specific
                     * data file, we will look for a specific template.
                     */
                    object[] getTemplateParam = { "Templates:1" };

                    Type T = jsObj.GetType();
                    template = T.InvokeMember(
                        "getTemplate",
                        BindingFlags.InvokeMethod |
                        BindingFlags.Public |
                        BindingFlags.Instance,
                        null, jsObj, getTemplateParam);

                    if (template == null)
                    {
                        MessageBox.Show("Failed to acquire form template.");
                        return;
                    }

                    object[] spawnParam = { 1, false, false };

                    Type templateType = template.GetType();
                    templateType.InvokeMember(
                        "spawn",
                        BindingFlags.InvokeMethod |
                        BindingFlags.Public |
                        BindingFlags.Instance,
                        null, template, spawnParam);


                    /*Extract the page and populate the form with the data*/
                    object[] extractPagesParam = { 1 };
                    newDoc = T.InvokeMember(
                        "extractPages",
                        BindingFlags.InvokeMethod |
                        BindingFlags.Public |
                        BindingFlags.Instance,
                        null, jsObj, extractPagesParam);

                    object[] importTextDataParam = { filename, currentIndex };
                    double   importError         = (double)T.InvokeMember(
                        "importTextData",
                        BindingFlags.InvokeMethod |
                        BindingFlags.Public |
                        BindingFlags.Instance,
                        null, newDoc, importTextDataParam);

                    if (importError == 0)
                    {
                        /* Save the new PDF to the output folder at the top level of the sample
                         * output folder has to exist, so create it first.
                         */
                        String newFileName = Application.StartupPath + "\\..\\..\\..\\output\\data" + (currentIndex + 1) + ".pdf";
                        Directory.CreateDirectory(Application.StartupPath + "\\..\\..\\..\\output");
                        object[] saveAsParam = { newFileName };
                        T.InvokeMember(
                            "saveAs",
                            BindingFlags.InvokeMethod |
                            BindingFlags.Public |
                            BindingFlags.Instance,
                            null, newDoc, saveAsParam);
                    }
                    else
                    {
                        formDataExists = false;
                    }

                    object[] closeDocParam = { !formDataExists };
                    T.InvokeMember(
                        "closeDoc",
                        BindingFlags.InvokeMethod |
                        BindingFlags.Public |
                        BindingFlags.Instance,
                        null, newDoc, closeDocParam);

                    currentIndex++;
                }
            }
        }
Exemple #20
0
        /* searches the specified pdf for the word in the searchTextBox, looping
         * through all matches until done or cancelled.
         */
        private void searchButton_Click(object sender, EventArgs e)
        {
            if (g_AVDoc.IsValid())
            {
                CAcroPDDoc pdDoc = (CAcroPDDoc)g_AVDoc.GetPDDoc();
                //Acquire the Acrobat JavaScript Object interface from the PDDoc object
                Object jsObj = pdDoc.GetJSObject();
                Type   T     = jsObj.GetType();

                int  nCount         = 0;
                bool continueSearch = true;
                currentStatus.Text = "Searching ... ";

                // total number of pages
                double nPages = (double)T.InvokeMember(
                    "numPages",
                    BindingFlags.GetProperty |
                    BindingFlags.Public |
                    BindingFlags.Instance,
                    null, jsObj, null);

                //Go through pages
                for (int i = 0; i < nPages && continueSearch; i++)
                {
                    // check each word in a page
                    object[] getPageNumWordsParam = { i };
                    double   nWords = (double)T.InvokeMember(
                        "getPageNumWords",
                        BindingFlags.InvokeMethod |
                        BindingFlags.Public |
                        BindingFlags.Instance,
                        null, jsObj, getPageNumWordsParam);

                    for (int j = 0; j < nWords && continueSearch; j++)
                    {
                        //get a word
                        object[] getPageNthWordParam = { i, j };
                        String   word = (String)T.InvokeMember(
                            "getPageNthWord",
                            BindingFlags.InvokeMethod |
                            BindingFlags.Public |
                            BindingFlags.Instance,
                            null, jsObj, getPageNthWordParam);

                        // compare the word with what the user wants
                        int result = String.Compare(word, searchTextBox.Text);

                        // if same
                        if (result == 0)
                        {
                            nCount             = nCount + 1;
                            currentStatus.Text = "word found at " + j;
                            T.InvokeMember(
                                "selectPageNthWord",
                                BindingFlags.InvokeMethod |
                                BindingFlags.Public |
                                BindingFlags.Instance,
                                null, jsObj, getPageNthWordParam);


                            if (MessageBox.Show("Continue Search?",
                                                "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                            {
                                continueSearch = false;
                            }
                        }
                    }
                    if (continueSearch == true)
                    {
                        currentStatus.Text = "Search Done";
                    }
                    else
                    {
                        currentStatus.Text = "User Cancelled Search";
                    }
                }
            }
        }
Exemple #21
0
        public String getPageRangeBetweenStrings(String szPdfPathConst, String HeaderStr, String FooterStr, Boolean includeFirstPageInRange, Boolean includeLastPageInRange)
        {
            CAcroApp        avApp;
            CAcroAVDoc      avDoc;
            CAcroAVPageView avPage;

            avApp = new AcroAppClass();
            avDoc = new AcroAVDocClass();
            avDoc.Open(szPdfPathConst, "");
            CAcroPDDoc pdDoc          = (CAcroPDDoc)avDoc.GetPDDoc();
            List <int> PageListHeader = new List <int>();
            List <int> PageListFooter = new List <int>();
            //AcroPDDoc pdDoc = getPDDoc(szPdfPathConst);
            int        TotalNumberOfPages = pdDoc.GetNumPages();
            AcroPDPage page;

            //set AVPage View object
            avPage = (CAcroAVPageView)avDoc.GetAVPageView();
            avApp.Show();
            for (int i = 0; i < TotalNumberOfPages; i++)
            {
                page = (AcroPDPage)pdDoc.AcquirePage(i);
                Boolean TextCheck = avDoc.FindText(HeaderStr, 1, 1, 0);
                if (TextCheck == true)
                {
                    int PageNum = avPage.GetPageNum();
                    PageListHeader.Add(PageNum);
                }
            }


            List <int> PagesWithHeaderWords = DeDuplicateArray(PageListHeader);



            for (int i = 0; i < TotalNumberOfPages; i++)
            {
                page = (AcroPDPage)pdDoc.AcquirePage(i);
                Boolean TextCheck = avDoc.FindText(FooterStr, 1, 1, 0);
                if (TextCheck == true)
                {
                    int PageNum = avPage.GetPageNum();
                    PageListFooter.Add(PageNum);
                }
            }
            List <int> PagesWithFooterWords = DeDuplicateArray(PageListFooter);
            int        MinimumFooterRange   = 0;
            int        MinimumHeaderRange   = 0;

            if (PagesWithFooterWords.Count == 0 || PagesWithHeaderWords.Count == 0)
            {
                return("No Range Found");
            }

            MinimumFooterRange = PagesWithFooterWords.Min();
            MinimumHeaderRange = PagesWithFooterWords.Min();



            int HeaderFinalPageNumber = MinimumHeaderRange + 1;
            int FooterFinalPageNumber = MinimumFooterRange + 1;

            if (!includeFirstPageInRange)
            {
                HeaderFinalPageNumber++;
            }
            if (!includeLastPageInRange)
            {
                FooterFinalPageNumber--;
            }

            return(HeaderFinalPageNumber + "-" + FooterFinalPageNumber);
        }
Exemple #22
0
        void runJob(Action job)
        {
            if (!File.Exists(PdfFilePath))
                throw new InvalidOperationException(BadFileErrorMessage);

            var acrobatPdfDocType = Type.GetTypeFromProgID("AcroExch.PDDoc");
            if (acrobatPdfDocType == null || !isAdobeSdkInstalled)
                throw new InvalidOperationException(SdkError);

            _pdfDoc = (CAcroPDDoc)Activator.CreateInstance(acrobatPdfDocType);
            if (_pdfDoc == null)
                throw new InvalidOperationException(AdobeObjectsErrorMessage);

            var acrobatPdfRectType = Type.GetTypeFromProgID("AcroExch.Rect");
            _pdfRect = (CAcroRect)Activator.CreateInstance(acrobatPdfRectType);

            var result = _pdfDoc.Open(PdfFilePath);
            if (!result)
                throw new InvalidOperationException(BadFileErrorMessage);

            job();

            releaseComObjects();
        }