/**
         * Put all data from given day into given table
         */
        public static void collectDataforDay(DateTime dateTime, SQLiteConnection m_dbConnection)
        {
            string zeroMonth = dateTime.Month < 10 ? "0" : "";
              string zeroDay = dateTime.Day < 10 ? "0" : "";
              string date = zeroMonth + dateTime.Month + "/" + zeroDay + dateTime.Day + "/" + dateTime.Year;

              PdfReader reader;
              try
              {
            reader = new PdfReader("http://www.equibase.com/premium/eqbPDFChartPlus.cfm?RACE=A&BorP=P&TID=SAR&CTRY=USA&DT=" + date + "&DAY=D&STYLE=EQB");
              }
              catch (Exception e)
              {
            Console.WriteLine("CAPTCHA TIME");
            Console.ReadKey();
            Console.ReadKey();

            reader = new PdfReader("http://www.equibase.com/premium/eqbPDFChartPlus.cfm?RACE=A&BorP=P&TID=SAR&CTRY=USA&DT=" + date + "&DAY=D&STYLE=EQB");
              }
              StringBuilder builder = new StringBuilder();

              for (int x = 1; x <= reader.NumberOfPages; x++)
              {
            PdfDictionary page = reader.GetPageN(x);
            IRenderListener listener = new SBTextRenderer(builder);
            PdfContentStreamProcessor processor = new PdfContentStreamProcessor(listener);
            PdfDictionary pageDic = reader.GetPageN(x);
            PdfDictionary resourcesDic = pageDic.GetAsDict(PdfName.RESOURCES);
            processor.ProcessContent(ContentByteUtils.GetContentBytesForPage(reader, x), resourcesDic);
              }

              if (pages.Count != 0)
              {

            DataHandler handler = new DataHandler(dateTime, pages, m_dbConnection);
            Thread thread = new Thread(new ThreadStart(handler.extractPdfData));

            thread.Start();
            thread.Join();
            reader.Dispose();
            pages.Clear();
              }
              else
              {
            // If there were no races on this particular day, simply skip it! :D
            Console.WriteLine("Invalid Date: " + date);
              }
        }
Exemple #2
1
        //-------------------------------------------------------------------------
        private bool ExtractImages(String PDFSourcePath, Audit sourceAudit, out Exception exception)
        {
            //List<System.Drawing.Image> ImgList = new List<System.Drawing.Image>();

            exception = null;
            iTextSharp.text.pdf.RandomAccessFileOrArray RAFObj = null;
            iTextSharp.text.pdf.PdfReader PDFReaderObj = null;
            iTextSharp.text.pdf.PdfObject PDFObj = null;
            iTextSharp.text.pdf.PdfStream PDFStremObj = null;
            int pageNumber = 0;
            bool ok = false;
            try
            {
                RAFObj = new iTextSharp.text.pdf.RandomAccessFileOrArray(PDFSourcePath);
                PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj, null);
                for (int i = 0; i < PDFReaderObj.XrefSize; i++)
                {
                    PDFObj = PDFReaderObj.GetPdfObject(i);

                    if ((PDFObj != null) && PDFObj.IsStream())
                    {
                        PDFStremObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
                        iTextSharp.text.pdf.PdfObject subtype = PDFStremObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);

                        if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
                        {
                            try
                            {
                                iTextSharp.text.pdf.parser.PdfImageObject PdfImageObj =
                         new iTextSharp.text.pdf.parser.PdfImageObject((iTextSharp.text.pdf.PRStream)PDFStremObj);

                                System.Drawing.Image ImgPDF = PdfImageObj.GetDrawingImage();
                                pageNumber++;
                                if (pageNumber > PDFReaderObj.NumberOfPages)
                                    return false;
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
                pageNumber = 0;
                PageCount = PDFReaderObj.NumberOfPages;
                for (int i = 0; i < PDFReaderObj.XrefSize; i++)
                {
                    PDFObj = PDFReaderObj.GetPdfObject(i);

                    if ((PDFObj != null) && PDFObj.IsStream())
                    {
                        PDFStremObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
                        iTextSharp.text.pdf.PdfObject subtype = PDFStremObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);

                        if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
                        {
                            try
                            {
                                iTextSharp.text.pdf.parser.PdfImageObject PdfImageObj =
                         new iTextSharp.text.pdf.parser.PdfImageObject((iTextSharp.text.pdf.PRStream)PDFStremObj);

                                System.Drawing.Image ImgPDF = PdfImageObj.GetDrawingImage();
                                pageNumber++;
                                //using (Bitmap bmp = new Bitmap(ImgPDF))
                                //{
                                //    SaveFrameFiles(PDFSourcePath, sourceAudit, bmp, pageNumber, PageCount);
                                try
                                {
                                    SaveFrameFiles(PDFSourcePath, sourceAudit, (Bitmap)ImgPDF, pageNumber, PageCount);
                                }
                                catch (Exception)
                                {
                                    ImgPDF.Dispose();
                                    continue;
                                }
                                ImgPDF.Dispose();
                                ok = true;
                                //}
                            }
                            catch (Exception)
                            { }
                        }
                    }
                }
                return ok;
            }
            catch (Exception)// ex
            {
                //log.LogMessage(PDFSourcePath + " Page" + pageNumber.ToString() + " ", ex);
                return false;
            }
            finally
            {
                PDFReaderObj.Close();
                PDFReaderObj.Dispose();
            }
        }
Exemple #3
0
 private void freePDF()
 {
     if (avaPDF)
     {
         try {
             pdfReader.Dispose();
             pdfDoc.Dispose();
             pdfCopy.Dispose();
         } catch {
             pdfReader = null;
             pdfDoc    = null;
             pdfCopy   = null;
         }
     }
 }
Exemple #4
0
        /**
         * Internal function used to process folders in the dictionary. These values 
         * usually come from the property file. It retrieves the number of files contained, whether or not
         * the folder contains a new file.
         */
        private List<FolderInfo> processFolderList(Dictionary<string, string> folderList)
        {
            List<FolderInfo> toReturn = new List<FolderInfo>();
            Dictionary<String, String> keywords = null;
            JavaScriptSerializer j = new JavaScriptSerializer();
            SpiderWeb.Models.FolderInfo tempInfo;
            string dirName;
            PdfReader pdfReader = null;

            BufferedStream randomAccess = null;
            foreach (KeyValuePair<string, string> entry in folderList)
            {
                dirName = entry.Value;

                FileInfo tempFile = new FileInfo(dirName);
                tempInfo = new SpiderWeb.Models.FolderInfo();
                tempInfo.folderName = dirName.Substring(dirName.LastIndexOf("\\") + 1);
                tempInfo.folderPath = dirName;

                dirName = tempFile.FullName;
                if (!Directory.Exists(dirName) && (dirName.ToUpper().StartsWith(this.data["DRR_DRIVE"] + ":") || dirName.StartsWith("\\\\")))
                {
                    Directory.CreateDirectory(dirName);
                }
                if (Directory.Exists(dirName))
                {
                    string[] allFiles = Directory.GetFiles(dirName, "*pdf");
                    tempInfo.fileCount = allFiles.Length;
                    tempInfo.hasNewFile = false;
                    string openDirectory, currentDirectory;
                    foreach (string fileName in allFiles)
                    {
                        try
                        {

                            randomAccess = new BufferedStream(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), 12288);
                            pdfReader = new PdfReader(randomAccess, null);

                            if (pdfReader.Info.ContainsKey("Keywords"))
                            {
                                keywords = j.Deserialize<Dictionary<String, String>>(getValue(pdfReader.Info, "Keywords"));
                                //keywords = getKeywords(output);
                                /*if (pdfDocument.Metadata != null && pdfDocument.Metadata["Keywords"] != null && pdfDocument.Metadata["Keywords"].ToString().Length > 0)
                                {
                                    keywords = j.Deserialize<Dictionary<String, String>>((string)pdfDocument.Metadata["Keywords"]);*/
                                openDirectory = getValue(keywords, IndividualRFileInfo.OPEN_DIRECTORY);
                                currentDirectory = getValue(keywords, IndividualRFileInfo.CURRENT_DIRECTORY);
                                if (openDirectory != currentDirectory || openDirectory.Length == 0)
                                {
                                    tempInfo.hasNewFile = true;
                                    break;
                                }
                            }
                            else
                            {
                                tempInfo.hasNewFile = true;
                                break;
                            }

                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.StackTrace);
                        }
                        finally
                        {
                            randomAccess.Close();
                            pdfReader.Close();
                            pdfReader.Dispose();
                            pdfReader = null;

                        }
                    }

                    //  allFolders[dirName] = tempInfo;
                }
                dirName = dirName.Substring(dirName.LastIndexOf("\\") + 1);
                tempInfo.alias = entry.Key;

                toReturn.Add(tempInfo);
            }
            return toReturn;
        }
Exemple #5
0
        /**
        * Returns meta data information from the pdf file
        */
        public Dictionary<string, string> GetFileChartInformation(string path)
        {
            BufferedStream randomAccess = null;
            PdfReader pdfReader = null;

            Dictionary<String, String> keywords = new Dictionary<String, String>();
            JavaScriptSerializer j = new JavaScriptSerializer();
            try
            {
                //if (File.Exists(path))
                // {
                randomAccess = new BufferedStream(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
                pdfReader = new PdfReader(randomAccess, null);


                keywords = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(getValue(pdfReader.Info, "Keywords"));

                //}
            }
            catch (Exception e)
            {
                ExceptionUtility.LogException(e, "");
            }
            finally
            {
                if (randomAccess != null)
                {
                    randomAccess.Close();
                }
                if (pdfReader != null)
                {
                    pdfReader.Close();
                    pdfReader.Dispose();
                    pdfReader = null;
                }
            }
            return keywords;
        }
Exemple #6
0
        public void setMetaData(string path, Dictionary<String, String> values)
        {
            Hashtable toReturn = new Hashtable();
            BufferedStream randomAccess = null;
            PdfReader pdfReader = null;
            Dictionary<String, String> keywords = new Dictionary<String, String>();
            JavaScriptSerializer j = new JavaScriptSerializer();
            try
            {
                randomAccess = new BufferedStream(this.WaitForFile(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete), 12288);
                pdfReader = new PdfReader(randomAccess, null);
                keywords = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(getValue(pdfReader.Info, "Keywords"));

                if (keywords == null)
                {
                    keywords = new Dictionary<String, String>();
                }
                MemoryStream mem = new MemoryStream();
                if (pdfReader != null)
                {
                    using (BufferedStream ms = new BufferedStream(mem, 12288))
                    {
                        using (PdfStamper stamper = new PdfStamper(pdfReader, ms))
                        {
                            Dictionary<String, String> info = pdfReader.Info;
                            foreach (KeyValuePair<string, string> entry in values)
                            {
                                if (keywords.ContainsKey(entry.Key))
                                {
                                    keywords[entry.Key] = entry.Value;
                                    if (entry.Key != IndividualRFileInfo.CURRENT_DIRECTORY)
                                    {
                                        FileInfo fInfo = new FileInfo(path);
                                        if (keywords.ContainsKey(IndividualRFileInfo.CURRENT_DIRECTORY))
                                        {
                                            keywords[IndividualRFileInfo.CURRENT_DIRECTORY] = fInfo.Directory.Name;
                                        }
                                        else
                                        {
                                            keywords.Add(IndividualRFileInfo.CURRENT_DIRECTORY, fInfo.Directory.Name);

                                        }
                                    }
                                }
                                else
                                {
                                    keywords.Add(entry.Key, entry.Value);
                                }
                            }
                            string allStr = j.Serialize(keywords);
                            info["Keywords"] = allStr;

                            stamper.MoreInfo = info;
                            stamper.Close();
                        }

                        //File.Delete(path);
                        File.WriteAllBytes(path, mem.ToArray());
                        ms.Close();
                        ms.Dispose();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
            finally
            {
                if (randomAccess != null)
                {
                    randomAccess.Close();

                }
                if (pdfReader != null)
                {
                    pdfReader.Close();
                    pdfReader.Dispose();
                }
            }
        }
Exemple #7
0
        private Boolean unlockPDF(String r_password, String w_password)
        {
            Boolean NOPASS = true;

            ////////////////////////////////////////////////////
            // PDF解錠
            ////////////////////////////////////////////////////
            if (avaPDF)
            {
                // 一時ファイル取得
                String  tmpFilePath = Path.GetTempFileName();
                Boolean isRP        = false;
                Boolean isWP        = false;

                // パスワードなしで読み込めるかチェック
                try {
                    pdfReader = new PdfReader(dataGridView1.Rows[0].Cells[3].Value.ToString());
                    isRP      = false; // ユーザーパスワードなし
                                       // オーナーパスワードが掛っているかチェック
                    isWP   = (pdfReader.IsEncrypted()) ? true : false;
                    NOPASS = !(isRP || isWP);
                    pdfReader.Close();
                    pdfReader.Dispose();
                } catch {
                    isRP   = true;
                    NOPASS = false;
                }
                if (NOPASS)
                {
                    // パスワードがかかっていない
                    label2.Text = WindowsFormsApplication1.Properties.Resources.pdf2;
                    //"This document is not applied password.";
                    pdfReader.Close();
                    pdfReader.Dispose();
                    return(false);
                }
                if (isRP && (r_password.Length == 0))
                {
                    // ユーザーパスワードが掛っているが、入力されていない
                    label2.Text = WindowsFormsApplication1.Properties.Resources.pdf3;
                    // "This document has been user password-protected.";
                    return(false);
                }
                if (isWP && (w_password.Length == 0))
                {
                    // オーナーパスワードが掛っているが、入力されていない
                    label2.Text = WindowsFormsApplication1.Properties.Resources.pdf4;
                    //"This document has been owner password-protected.";
                    return(false);
                }

                String rp = (r_password.Length == 0) ? null : r_password;
                String wp = (w_password.Length == 0) ? r_password : w_password;

                try {
                    pdfReader = new PdfReader(dataGridView1.Rows[0].Cells[3].Value.ToString(), (byte[])System.Text.Encoding.ASCII.GetBytes(wp));
                } catch {
                    label2.Text = WindowsFormsApplication1.Properties.Resources.message2;
                    // "Password is incorrect.";
                    return(false);
                }


                try {
                    pdfDoc  = new iTextSharp.text.Document(pdfReader.GetPageSize(1));
                    os      = new FileStream(tmpFilePath, FileMode.OpenOrCreate);
                    pdfCopy = new PdfCopy(pdfDoc, os);
                    pdfCopy.Open();

                    pdfDoc.Open();
                    pdfCopy.AddDocument(pdfReader);

                    pdfDoc.Close();
                    pdfCopy.Close();
                    pdfReader.Close();
                    pdfReader.Dispose();
                    // オリジナルファイルと一時ファイルを置き換える
                    System.IO.File.Copy(tmpFilePath, dataGridView1.Rows[0].Cells[3].Value.ToString(), true);
                    System.IO.File.Delete(tmpFilePath);
                } catch (Exception eX) {
                    label2.Text = WindowsFormsApplication1.Properties.Resources.error1 + eX.Message;
                    // "Saving failed." + eX.Message;
                    return(false);
                }
            }
            return(true);
        }
        /// <summary>
        /// Prepare the data needed for digital signature. Unfortunately
        /// CAPICOM's client-side implementation both hashes **AND** signs
        /// passed in data instead of signing data already hashed, so the 
        /// **entire** PDF content bytes are needed.
        /// </summary>
        /// <param name="pdfIn">PDF file contents</param>
        /// <returns>
        /// Base64 encoded PDF content bytes client will sign.
        /// </returns>
        public string PreSign(byte[] pdfIn)
        {
            byte[] pdfRawContent = null;
            bool isOdd = true;
            var timeStamp = DateTime.Now;
            var pdfSignature = new PdfSignature(
                PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED
            );
            pdfSignature.Date = new PdfDate(timeStamp);
            var exclusionSizes = new Dictionary<PdfName, int>();
            exclusionSizes.Add(PdfName.CONTENTS, EXCLUSION_BUFFER * 2 + 2);
            PdfReader reader = null;
            int? signedFields = null;
            try
            {
                var cert = new WebCertificateReader().GetSigningCertificate();
                do
                {
                    ++DataReadCount;
                    reader = new PdfReader(pdfIn);
                    _acroFieldsWorker = new AcroFieldsReader(reader.AcroFields);
                    signedFields = signedFields ?? _acroFieldsWorker.SignedFields();
                    _memoryStream = new MemoryStream();
                    var stamper = signedFields == 0
                        ? PdfStamper.CreateSignature(reader, _memoryStream, '\0')
                        : PdfStamper.CreateSignature(reader, _memoryStream, '\0', null, true)
                    ;
                    _signatureAppearance = stamper.SignatureAppearance;
                    InitSignatureField(stamper);
                    pdfSignature.Reason = Reason;
                    _signatureAppearance.Certificate = cert;
                    _signatureAppearance.SignDate = timeStamp;
                    _signatureAppearance.CryptoDictionary = pdfSignature;
                    _signatureAppearance.PreClose(exclusionSizes);
                    using (Stream sapStream = _signatureAppearance.GetRangeStream())
                    {
                        using (var ms = new MemoryStream())
                        {
                            sapStream.CopyTo(ms);
                            pdfRawContent = ms.ToArray();
                        }

                        // pdfRawContent = StreamHandler.ReadAllBytes(sapStream);
                        // fix CAPICOM's broken implemetation: signature
                        // invalid if sapStream.Length is **ODD**
                        if ((pdfRawContent.Length % 2) == 0)
                        {
                            isOdd = false;
                        }
                        else
                        {
                            Reason += "\0";
                        }
                        DataSize = sapStream.Length;
                    }
                    // sanity check
                    if (DataReadCount > 2) throw new InvalidOperationException("DataReadCount");
                } while (isOdd);
            }
            catch { throw; }
            finally
            {
                HttpContext.Current.Session[InstanceLookupKey] = this;
                if (reader != null) { reader.Dispose(); }
            }
            return Convert.ToBase64String(pdfRawContent);
        }
Exemple #9
0
        protected void AnalyzeFile()
        {
            analyzeFailed = false;
            this.SetStatusText("Analyzing...");
            SetPictureVisible(ref imgError, false);
            SetPictureVisible(ref imgOK, false);

            if (radRadioButton2.IsChecked && txtPageNumbers.Text.Trim().Length > 0)
            {
                try
                {
                    String[] pages = txtPageNumbers.Text.Trim().Replace(" ", "").Split(',');
                    foreach (string s in pages)
                    {
                        if (s.Contains('-'))
                        {
                            String[] pageRange = s.Split('-');
                            if (Convert.ToInt32(pageRange[0]) >= Convert.ToInt32(pageRange[1]))
                            {
                                MessageBox.Show("Cannot count pages backwards. Please correct your page range.", "Invalid Page Range", MessageBoxButtons.OK);
                                analyzeFailed = true;
                                SetButtonEnabled(ref btnSourcePDF, true);
                                SetButtonEnabled(ref btnDestinationPDF, true);
                                SetPictureVisible(ref imgError, true);
                                SetGroupBoxEnabled(ref radGroupBox1, true);
                                this.SetStatusText("Invalid Page Range");
                                this.SetProgressBar(ref progressStatus, false, 100);
                                this.SetProgressPanelVisible(false);
                                analyzeThread.Abort();
                                return;
                            } else if (pageRange.Length > 2)
                            {
                                MessageBox.Show("Invalid page range entered. Please correct your entry and try again", "Invalid Page Range", MessageBoxButtons.OK);
                                analyzeFailed = true;
                                SetButtonEnabled(ref btnSourcePDF, true);
                                SetButtonEnabled(ref btnDestinationPDF, true);
                                SetGroupBoxEnabled(ref radGroupBox1, true);
                                SetPictureVisible(ref imgError, true);
                                this.SetStatusText("Invalid Page Range");
                                this.SetProgressBar(ref progressStatus, false, 100);
                                this.SetProgressPanelVisible(false);
                                analyzeThread.Abort();
                                return;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    analyzeFailed = true;
                    SetButtonEnabled(ref btnSourcePDF, true);
                    SetButtonEnabled(ref btnDestinationPDF, true);
                    SetPictureVisible(ref imgError, true);
                    SetGroupBoxEnabled(ref radGroupBox1, true);
                    this.SetStatusText("Invalid Page Range");
                    this.SetProgressBar(ref progressStatus, false, 100);
                    this.SetProgressPanelVisible(false);
                    analyzeThread.Abort();
                    return;
                }
            }

            PdfReader pdfDocument = new PdfReader(lblSourcePDF.Text);
            PdfDictionary document = new PdfDictionary( );
            SortPagesProvider sortPagesProvider = new SortPagesProvider();
            int page_number = 0;

            if (radRadioButton1.IsChecked) {
                bookMarkReferences = new List<BookMarkReference>();
                IList<Dictionary<string, object>> bookmarks = SimpleBookmark.GetBookmark(pdfDocument);

                if (bookmarks != null) {
                    int i = 0;
                    this.SetProgressBar(ref progressStatus, true, bookmarks.Count);
                    foreach (Dictionary<string, object> bk in bookmarks)
                    {
                        foreach (KeyValuePair<string, object> kvr in bk)
                        {
                            if (kvr.Key == "Page" || kvr.Key == "page")
                                page_number = Convert.ToInt32(Regex.Match(kvr.Value.ToString(), "[0-9]+").Value);
                        }

                        bookMarkReferences.Add(new BookMarkReference(bookmarks[i].Values.ToArray().GetValue(0).ToString(), page_number));
                        this.AddTreeNode(radTreeView1, bookmarks[i].Values.ToArray().GetValue(0).ToString() + " (Page: " + page_number.ToString() + ")");
                        this.SetStatusText(string.Format("Analyzing, {0}...", bookmarks[i].Values.ToArray().GetValue(0).ToString()));
                        this.SetProgressBarValue(ref progressStatus, i);
                        Thread.Sleep(500);
                        i++;

                    }

                    bookMarkReferences.Sort(sortPagesProvider);
                    SetButtonEnabled(ref btnSourcePDF, true);
                    SetButtonEnabled(ref btnDestinationPDF, true);
                    SetPictureVisible(ref imgOK, true);
                    SetGroupBoxEnabled(ref radGroupBox1, true);
                    this.SetStatusText("Done.");
                    this.SetProgressBar(ref progressStatus, false, 100);
                    this.SetProgressPanelVisible(false);
                } else {
                    analyzeFailed = true;
                    SetButtonEnabled(ref btnSourcePDF, true);
                    SetButtonEnabled(ref btnDestinationPDF, true);
                    SetPictureVisible(ref imgError, true);
                    SetGroupBoxEnabled(ref radGroupBox1, true);
                    this.SetStatusText("No Bookmarks Found!");
                    this.SetProgressBar(ref progressStatus, false, 100);
                    this.SetProgressPanelVisible(false);
                }
            } else if (radRadioButton2.IsChecked) {
                String[] pages = txtPageNumbers.Text.Trim().Replace(" ", "").Split(',');

                Int32 pageCount = pdfDocument.NumberOfPages;

                if (pages.Length > 0) {
                    this.SetProgressBar(ref progressStatus, true, pages.Length);
                    try {
                        for (int i = 0; i < pages.Length; i++)
                        {
                            this.SetStatusText(string.Format("Analyzing, {0}...", pages[i]));
                            this.SetProgressBarValue(ref progressStatus, i+1);

                            if (pages[i].Trim() != "") {
                                if (pages[i].Contains("-")) {
                                    if (pages[i].Split('-')[1].Trim() != "") {
                                        Int32 lastnum = Convert.ToInt32(pages[i].Split('-')[1]);
                                        if (lastnum > pageCount) {
                                            analyzeFailed = true;
                                            this.AddTreeNode(radTreeView1, "Page(s): " + pages[i] + " - Invalid");
                                        } else {
                                            this.AddTreeNode(radTreeView1, "Page(s): " + pages[i] + " - \u2713");
                                        }

                                    }
                                } else {
                                    if (Convert.ToInt32(pages[i]) > pageCount) {
                                        analyzeFailed = true;
                                        this.AddTreeNode(radTreeView1, "Page(s): " + pages[i] + " - Invalid");
                                    } else {
                                        this.AddTreeNode(radTreeView1, "Page(s): " + pages[i] + " - \u2713");
                                    }
                                }
                            }

                        }

                        this.SetStatusText("Done.");
                        SetButtonEnabled(ref btnSourcePDF, true);
                        SetButtonEnabled(ref btnDestinationPDF, true);
                        SetPictureVisible(ref imgOK, true);
                        SetGroupBoxEnabled(ref radGroupBox1, true);
                        this.SetProgressBar(ref progressStatus, false, 100);
                        this.SetProgressPanelVisible(false);
                    } catch (Exception ex) {
                        MessageBox.Show("There was a problem analyzing your document. Please check your entries and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.SetStatusText("Failed.");
                        SetButtonEnabled(ref btnSourcePDF, true);
                        SetButtonEnabled(ref btnDestinationPDF, true);
                        SetPictureVisible(ref imgError, true);
                        SetGroupBoxEnabled(ref radGroupBox1, true);
                        this.SetProgressBar(ref progressStatus, false, 100);
                        this.SetProgressPanelVisible(false);
                    }
                }
            } else {
                analyzeFailed = true;
                this.SetStatusText("No pages documented.");
                SetButtonEnabled(ref btnSourcePDF, true);
                SetButtonEnabled(ref btnDestinationPDF, true);
                SetPictureVisible(ref imgError, true);
                SetGroupBoxEnabled(ref radGroupBox1, true);
                this.SetProgressBar(ref progressStatus, false, 100);
                this.SetProgressPanelVisible(false);
            }

            pdfDocument.Close();
            pdfDocument.Dispose();
        }
Exemple #10
0
        void ExportToMultiplePDF(int index)
        {
            int finishedReports = 0;

            PdfStamper stamper = null;
            PdfReader reader = null;

                //Go through each student in the list

                foreach (var student in StudentList)
                {
                    string savePath = System.IO.Path.Combine(System.IO.Path.GetFullPath(textSavePath.Text),
                            string.Format("{0}.pdf",
                            index == 0
                            ? student.Name.Replace(' ', '_')
                            : student.NameReversed));

                    //Create FileStream for the template pdf
                    var templateStream = new FileStream(System.IO.Path.GetFullPath(textTempLocation.Text), FileMode.Open);

                    //Create FileStream for new student report pdf
                    var studentStream = new FileStream(savePath, FileMode.Create);

                    //Open existing pdf
                    reader = new PdfReader(templateStream);

                    //Create stamper to set the contents of the fields
                    stamper = new PdfStamper(reader, studentStream);

                    var form = stamper.AcroFields;

                    //Setting the text of the template to the stored info
                    form.SetField("Street", student.Address);
                    form.SetField("CityZipState", student.CityZipState);
                    form.SetField("ClassName", student.ClassName);
                    form.SetField("Comments", student.Comments);
                    form.SetField("Grade", student.Grade.ToString());
                    form.SetField("Critique", student.Critique);
                    form.SetField("HighSchool", student.HighSchool);
                    form.SetField("Session", student.Session);
                    form.SetField("Absences", student.SemesterTotalAbs.ToString());
                    form.SetField("Tardies", student.SemesterTotalTdy.ToString());
                    form.SetField("NetAbsences", student.SemesterNetAbs.ToString());
                    form.SetField("StuNameReversed", student.NameReversed);

                    form.SetField("Date", DateTime.Now.ToShortDateString());

                    //Flatten the fields that we do not want editable

                    stamper.FormFlattening = true;

                    stamper.PartialFormFlattening("StuNameReversed");
                    stamper.PartialFormFlattening("Street");
                    stamper.PartialFormFlattening("CityZipState");
                    stamper.PartialFormFlattening("HighSchool");
                    stamper.PartialFormFlattening("ClassName");
                    stamper.PartialFormFlattening("Session");
                    stamper.PartialFormFlattening("Absences");
                    stamper.PartialFormFlattening("Tardies");
                    stamper.PartialFormFlattening("NetAbsences");
                    stamper.PartialFormFlattening("Grade");
                    stamper.PartialFormFlattening("Critique");

                    stamper.Dispose();
                    reader.Dispose();

                    //reports progress to update status text on the bottom
                    bgProgressThread.ReportProgress(++finishedReports);

                }
        }