Esempio n. 1
4
        /// <summary>
        /// uses itextsharp 4.1.6 to convert any pdf to 1.4 compatible pdf, called instead of PdfReader.open
        /// </summary>
        public static PdfDocument Open(MemoryStream sourceStream, PdfDocumentOpenMode openmode)
        {
            PdfDocument outDoc = null;
            sourceStream.Position = 0;

            try
            {
                outDoc = PdfReader.Open(sourceStream, openmode);
            }
            catch (PdfSharp.Pdf.IO.PdfReaderException)
            {
                //workaround if pdfsharp doesn't support this pdf
                sourceStream.Position = 0;
                MemoryStream outputStream = new MemoryStream();
                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(sourceStream);
                iTextSharp.text.pdf.PdfStamper pdfStamper = new iTextSharp.text.pdf.PdfStamper(reader, outputStream);
                pdfStamper.FormFlattening = true;
                pdfStamper.Writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4);
                pdfStamper.Writer.CloseStream = false;
                pdfStamper.Close();

                outDoc = PdfReader.Open(outputStream, openmode);
            }

            return outDoc;
        }
Esempio n. 2
2
 public static Dictionary<string, string> ExtractInfoWithPolicy(string filepath)
 {
     var pdfReader = new iTextSharp.text.pdf.PdfReader(filename: filepath);
     string text = PdfTextExtractor.GetTextFromPage(pdfReader, pageNumber: 1);
     var dict = new Dictionary<string, string>();
     foreach (ExtractionSetting setting in SettingsManager.ExtractionSettings.Settings)
     {
         dict.Add(setting.Key, GetValueFromText(text, setting.ExtractionRegex, (RegexOptions)Enum.Parse(typeof(RegexOptions),setting.RegexOption)));
     }
     return dict;
 }
Esempio n. 3
1
        /// <summary>
        /// Reads a PDF file and extracts all text-searchable content from it.
        /// </summary>
        /// <param name="file">The file to extract text from.</param>
        /// <returns>The text from the PDF file</returns>
        public static string ReadFile(string file)
        {
            if (string.IsNullOrEmpty(file)) throw new ArgumentNullException("file", "file cannot be null or empty");
            FileInfo info = new FileInfo(file);
            if (!info.Exists) throw new FileNotFoundException("file must exist");
            if (!info.Extension.Equals(".pdf", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException("File must have a .pdf extension");

            System.Text.StringBuilder builder = new System.Text.StringBuilder();
            iTextSharp.text.pdf.PdfReader reader = null;
            try {
                reader = new iTextSharp.text.pdf.PdfReader(info.FullName);
                for (int i = 1; i <= reader.NumberOfPages; i++) {
                    builder.Append(ExtractTextFromPDFBytes(reader.GetPageContent(i)));
                    builder.Append(' ');
                }
            }
            catch (Exception) {

            }
            finally {
                if (reader != null) reader.Close();
            }

            return builder.ToString();
        }
Esempio n. 4
1
        //srcで指定されたPDFファイルをページ毎に分割し、destで指定されたパスに保存する。
        //保存ファイル名は「ファイル名-ページ番号.pdf」とする。
        //分割したページ数を返す。
        public List<string> Run(string src, string dest)
        {
            // srcで渡されたファイルが存在するか?
            if (!File.Exists(src))
            {
                throw new FileNotFoundException();
            }

            // destで渡されたフォルダが存在するか?
            if (!Directory.Exists(dest))
            {
                throw new DirectoryNotFoundException();
            }

            var reader = new iTextSharp.text.pdf.PdfReader(src);
            string file_name = Path.GetFileNameWithoutExtension(src);
            int digit = reader.NumberOfPages.ToString().Length;
            var app_name = new MainForm();

            // 一時フォルダにpdfを作成してdestにコピー。
            // その際上書き確認を行う。
            System.IO.DirectoryInfo del = new System.IO.DirectoryInfo(Path.GetTempPath() + "\\" + app_name.Text);
            if (del.Exists) del.Delete(true);
            System.IO.DirectoryInfo tmp = new System.IO.DirectoryInfo(Path.GetTempPath() + "\\" + app_name.Text);
            tmp.Create();
            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                var doc = new iTextSharp.text.Document();
                var dest_tmp = String.Format(@"{{0}}\{{1}}-{{2:D{0}}}.pdf", digit);
                var dest_name = String.Format(dest_tmp, tmp, file_name, i);
                var copy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(dest_name, FileMode.Create));

                doc.Open();
                copy.AddPage(copy.GetImportedPage(reader, i));
                doc.Close();
            }

            // コピーしたファイルを監視する
            Ret.list.Clear();
            var watcher = new System.IO.FileSystemWatcher();
            watcher.Path = dest;
            watcher.Filter = "*.pdf";
            watcher.Changed += new FileSystemEventHandler(changed);
            watcher.Created += new FileSystemEventHandler(changed);

            watcher.EnableRaisingEvents = true;
            FileSystem.CopyDirectory(tmp.ToString(), dest, UIOption.AllDialogs);
            watcher.EnableRaisingEvents = false;
            watcher.Dispose();
            watcher = null;

            tmp.Delete(true);
            reader.Close();

            return Ret.list;
        }
        public byte[] PrintSignToPDF_MemoriaAllPages_TextSharp(Stream File, String Firma, String Firmante)
        {
            MemoryStream outputPdfStream = new MemoryStream();
            PdfDocument document = PdfDocument.FromStream(File);
            document.SerialNumber = "s/va4uPX-1f/a0cHS-wcqFnYOT-gpOHk4qL-h5OAgp2C-gZ2KioqK";
            PdfFont pdfFont = document.CreateStandardFont(PdfStandardFont.Helvetica);
            byte[] pdfBuffer = document.WriteToMemory();
            var reader = new iTextSharp.text.pdf.PdfReader(pdfBuffer);
            var stamper = new iTextSharp.text.pdf.PdfStamper(reader, outputPdfStream);

            iTextSharp.text.pdf.PdfContentByte pdfContentByte2;
            iTextSharp.text.Rectangle pageSize;
            int NumOfPages = document.Pages.Count;

            for (int j = 1; j <= NumOfPages; j++)
            {

                pdfContentByte2 = stamper.GetOverContent(j);
                pageSize = reader.GetPageSizeWithRotation(j);
                pdfContentByte2.BeginText();

                //Firma = String.Format("{0} {1}", Firma, Firmante);
                string[] arrays = Firma.Split(' ');

                //iTextSharp.text.pdf.BaseFont baseFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, Encoding.ASCII.EncodingName, true, true);
                iTextSharp.text.pdf.BaseFont baseFont = iTextSharp.text.pdf.BaseFont.CreateFont("c:/windows/fonts/arial.ttf", iTextSharp.text.pdf.BaseFont.IDENTITY_H, true, true);

                pdfContentByte2.SetFontAndSize(baseFont, 8);
                //pdfContentByte2.SetRGBColorFill(192, 192, 192);
                pdfContentByte2.SetRGBColorFill(0, 0, 0);

                StringBuilder bloqueFirma = new StringBuilder();
                int contador = 0;
                int saltoLineaPixeles = 0;
                for (int i = 0; i < arrays.Length; i++)
                {
                    bloqueFirma.Append(arrays[i]);
                    bloqueFirma.Append(" ");
                    contador++;
                    if ((contador == 35) || ((saltoLineaPixeles > 13) && (contador == 36)))
                    {
                        pdfContentByte2.ShowTextAligned(iTextSharp.text.pdf.PdfContentByte.ALIGN_LEFT, bloqueFirma.ToString(),
                                                             pageSize.Width - (pageSize.Width / 2) - 100,
                                                            (pageSize.Height / 5) - saltoLineaPixeles - 100, 0);
                        contador = 0;
                        bloqueFirma = new StringBuilder();
                        saltoLineaPixeles = saltoLineaPixeles + 10;
                    }
                    else if ((i + 1) == arrays.Length)
                    {
                        pdfContentByte2.ShowTextAligned(iTextSharp.text.pdf.PdfContentByte.ALIGN_LEFT, bloqueFirma.ToString(),
                                                             pageSize.Width - (pageSize.Width / 2) - 100,
                                                            (pageSize.Height / 5) - saltoLineaPixeles - 100, 0);
                        saltoLineaPixeles = saltoLineaPixeles + 10;
                    }
                }

                String[] datos = Firmante.Split('[');
                String Firmante_ = datos[0];
                String pagina = datos[1];
                //Firmante_ = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(Firmante_)));

                pdfContentByte2.ShowTextAligned(iTextSharp.text.pdf.PdfContentByte.ALIGN_LEFT, Firmante_.ToString(),
                                                    pageSize.Width - (pageSize.Width / 2) - 100,
                                                (pageSize.Height / 5) - saltoLineaPixeles - 100, 0);

                saltoLineaPixeles = saltoLineaPixeles + 10;
                pdfContentByte2.ShowTextAligned(iTextSharp.text.pdf.PdfContentByte.ALIGN_LEFT, pagina.ToString(),
                                                    pageSize.Width - (pageSize.Width / 2) - 100,
                                                (pageSize.Height / 5) - saltoLineaPixeles - 100, 0);

                pdfContentByte2.EndText();
            }

            stamper.Close();

            outputPdfStream.Close();
            outputPdfStream.Dispose();
            document.Close();

            return outputPdfStream.GetBuffer();
        }
Esempio n. 6
0
        public void LoadDocument()
        {
            pdfReader.LoadFile(PrintBoxApp.instance.sessionInfo.shortDocPath);
            pdfReader.setShowToolbar(false);
            pdfReader.setShowScrollbars(false);
            pdfReader.setLayoutMode("SinglePage");
            pdfReader.setPageMode("none");
            GoToPage(1);

            iTextSharp.text.pdf.PdfReader rd = new iTextSharp.text.pdf.PdfReader(PrintBoxApp.instance.sessionInfo.shortDocPath);
            PrintBoxApp.instance.sessionInfo.pagesInDoc = rd.NumberOfPages;
        }
Esempio n. 7
0
        public static void FillTemplate(string path, Stream outputStream, Dictionary<string, string> fields)
        {
            var pdfReader = new iTextSharp.text.pdf.PdfReader(path);
            var pdfStamper = new iTextSharp.text.pdf.PdfStamper(pdfReader, outputStream);
            var pdfFormFields = pdfStamper.AcroFields;

            foreach (var field in fields)
            {
                pdfFormFields.SetField(field.Key, field.Value);
            }

            pdfStamper.FormFlattening = true;
            pdfStamper.Close();
        }
Esempio n. 8
0
 public static RecoveryDetails ExtractInfo(string filepath)
 {
     var pdfReader = new iTextSharp.text.pdf.PdfReader(filename: filepath);
     string text = PdfTextExtractor.GetTextFromPage(pdfReader, pageNumber: 1);
     var recoveryDetails = new RecoveryDetails();
     recoveryDetails.WorkOrder = GetValueFromText(text, ExtractionRegex.WorkOrder);
     recoveryDetails.User = GetValueFromText(text, ExtractionRegex.User);
     recoveryDetails.Date = GetValueFromText(text, ExtractionRegex.Date);
     recoveryDetails.Customer = GetValueFromText(text, ExtractionRegex.Customer);
     recoveryDetails.Address = GetValueFromText(text, ExtractionRegex.Address, RegexOptions.Singleline);
     recoveryDetails.Mobile = GetValueFromText(text, ExtractionRegex.Mobile);
     recoveryDetails.City = GetValueFromText(text, ExtractionRegex.City);
     recoveryDetails.PinCode = GetValueFromText(text, ExtractionRegex.PinCode);
     return recoveryDetails;
 }
Esempio n. 9
0
        /* ----------------------------------------------------------------- */
        ///
        /// Merge
        ///
        /// <summary>
        /// 2 つの PDF ファイルを結合します。
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        private bool Merge(UserSetting setting, string escaped)
        {
            // Nothing to do.
            if (string.IsNullOrEmpty(escaped) ||
                (setting.ExistedFile != Parameter.ExistedFiles.MergeHead &&
                 setting.ExistedFile != Parameter.ExistedFiles.MergeTail))
            {
                return(true);
            }

            string tmp  = Utility.WorkingDirectory + '\\' + System.IO.Path.GetRandomFileName();
            string head = (setting.ExistedFile == Parameter.ExistedFiles.MergeHead) ? setting.OutputPath : escaped;
            string tail = (setting.ExistedFile == Parameter.ExistedFiles.MergeTail) ? setting.OutputPath : escaped;

            bool status = true;

            try
            {
                iTextSharp.text.pdf.PdfReader reader_head = Open(head, setting.Permission.Password);
                iTextSharp.text.pdf.PdfReader reader_tail = Open(tail, setting.Permission.Password);

                using (var fs = new System.IO.FileStream(tmp, System.IO.FileMode.Create))
                {
                    iTextSharp.text.pdf.PdfCopyFields copy = new iTextSharp.text.pdf.PdfCopyFields(fs);
                    copy.AddDocument(reader_head);
                    copy.AddDocument(reader_tail);
                    copy.Close();
                }
                reader_head.Close();
                reader_tail.Close();
            }
            catch (Exception err)
            {
                _messages.Add(new Message(Message.Levels.Error, err));
                _messages.Add(new Message(Message.Levels.Debug, err));
                status = false;
            }
            finally
            {
                if (CubePdf.Misc.File.Exists(setting.OutputPath))
                {
                    CubePdf.Misc.File.Delete(setting.OutputPath, true);
                }
                if (!status || !CubePdf.Misc.File.Exists(tmp))
                {
                    CubePdf.Misc.File.Move(escaped, setting.OutputPath, true);
                }
                else
                {
                    CubePdf.Misc.File.Move(tmp, setting.OutputPath, true);
                }

                if (CubePdf.Misc.File.Exists(tmp))
                {
                    CubePdf.Misc.File.Delete(tmp, false);
                }
                if (CubePdf.Misc.File.Exists(escaped))
                {
                    CubePdf.Misc.File.Delete(escaped, false);
                }
            }

            return(status);
        }
Esempio n. 10
0
        /// <summary>
        /// MainListに新たなpdfファイルを加える為の関数。
        /// </summary>
        // pdfファイルのフルパスはTagを使って管理
        private void AddItemToList(string filename, string password)
        {
            // 既に同じパスのファイルが存在するなら何もしない
            foreach (ListViewItem item in MainList.Items)
            {
                FileProperty obj = item.Tag as FileProperty;
                if (obj.Path == filename) { return; }
            }

            // パスワードが入力されていない場合
            if (password == null)
            {
                try
                {
                    var reader = new iTextSharp.text.pdf.PdfReader(filename);
                    var ListData = new ListViewItem();
                    double numberofpages = reader.NumberOfPages;
                    double size = Math.Round(reader.FileLength / Math.Pow(2, 10), 0);
                    var property = new FileProperty();

                    ListData.Text = Path.GetFileName(filename);
                    ListData.SubItems.Add(String.Format("{0:#,0}", numberofpages));
                    ListData.SubItems.Add(String.Format("{0:#,0} KB", size));
                    ListData.SubItems.Add(File.GetLastWriteTime(filename).ToString());
                    property.Path = filename;
                    property.OwnerPassword = password;
                    property.IgnoreExistence = false;
                    ListData.Tag = property;

                    MainList.Items.Add(ListData);
                }

                // 例外を検出したとき、ファイルがパスワード管理されていたら解除を求める。
                catch (Exception)
                {
                    if (Configure.IsProtected(filename))
                    {
                        LoadSetting(filename);
                    }
                    else
                    {
                        OriginalMessageBox_OK(String.Format(Properties.Resources.UnSupportedFile, Path.GetFileName(filename)), MessageBoxIcon.Error);
                    }
                }
            }

            // パスワードが入力された場合
            else
            {
                try
                {
                    var configure = new Configure();
                    var detached = configure.DetachPassword(filename, password);

                    var reader = new iTextSharp.text.pdf.PdfReader(detached);
                    var ListData = new ListViewItem();
                    double numberofpages = reader.NumberOfPages;
                    var fileinfo = new FileInfo(filename);
                    double size = Math.Round(fileinfo.Length / Math.Pow(2, 10), 0);
                    var property = new FileProperty();

                    ListData.Text = Path.GetFileName(filename);
                    ListData.SubItems.Add(String.Format("{0:#,0}", numberofpages));
                    ListData.SubItems.Add(String.Format("{0:#,0} KB", size));
                    ListData.SubItems.Add(File.GetLastWriteTime(filename).ToString());
                    property.Path = filename;
                    property.OwnerPassword = password;
                    property.IgnoreExistence = false;
                    ListData.Tag = property;

                    MainList.Items.Add(ListData);
                }

                catch (Exception)
                {
                    OriginalMessageBox_OK(String.Format(Properties.Resources.UnSupportedFile, Path.GetFileName(filename)), MessageBoxIcon.Error);
                }

                // 一時ファイルを消去
                finally
                {
                    var configure = new Configure();
                    File.Delete(configure.DetachPassword(filename, password));
                }
            }
        }
Esempio n. 11
0
        public static string PrintPDFResize(string fileNamePath)
        {
            Debug.Log("CashmaticApp", "PrintPDFResize");
            string fileDirectory = Path.GetDirectoryName(fileNamePath);
            string fileName      = Path.GetFileNameWithoutExtension(fileNamePath);
            string newFile       = fileDirectory + "\\" + fileName + "_print.pdf";



            try
            {
                // open the reader
                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(fileNamePath);

                iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
                //Document document = new Document(size);
                iTextSharp.text.Document document = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(size.Width + 15, size.Height + Global.CardPaymentPrintPageSizeAddHeight));

                // open the writer
                FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
                iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fs);
                document.Open();

                // the pdf content
                iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;

                if (Global.cardholderReceipt != "")
                {
                    // select the font properties
                    iTextSharp.text.pdf.BaseFont bf = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.COURIER_BOLD, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.EMBEDDED);
                    cb.SetColorFill(iTextSharp.text.BaseColor.BLACK);
                    cb.SetFontAndSize(bf, 8);

                    int StartAt = Global.CardPaymentPrintStartAt + Global.CardPaymentPrintPageSizeAddHeight;

                    foreach (string line in Global.cardholderReceipt.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
                    {
                        // write the text in the pdf content
                        cb.BeginText();
                        // put the alignment and coordinates here
                        cb.ShowTextAligned(0, line, Global.CardPaymentPrintLeft, StartAt, 0);
                        cb.EndText();
                        StartAt = StartAt - Global.CardPaymentPrintLineHeight;
                    }
                }

                //// create the new page and add it to the pdf
                iTextSharp.text.pdf.PdfImportedPage page = writer.GetImportedPage(reader, 1);
                cb.AddTemplate(page, 10, +Global.CardPaymentPrintPageSizeAddHeight);

                // close the streams and voilá the file should be changed :)
                document.Close();
                fs.Close();
                writer.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                Debug.Log("CashmaticApp", ex.ToString());
            }

            return(newFile);
        }
Esempio n. 12
0
        /* ----------------------------------------------------------------- */
        ///
        /// AddInformation
        ///
        /// <summary>
        /// PDF ファイルに対して、引数に指定されたユーザ設定にしたがって
        /// 必要な情報を付与します。
        /// </summary>
        ///
        /// <remarks>
        /// iTextSharp を用いて以下の情報を付与します。
        ///
        /// - 文書プロパティ
        /// - 文書を開くためのパスワード (UserPassword)
        /// - 権限編集のためのパスワード (OwnerPassword)
        /// - 各種パーミッション
        /// </remarks>
        ///
        /* ----------------------------------------------------------------- */
        private bool AddInformation(UserSetting setting)
        {
            if (!CubePdf.Misc.File.Exists(setting.OutputPath))
            {
                return(false);
            }

            string tmp = Utility.WorkingDirectory + '\\' + System.IO.Path.GetRandomFileName();

            iTextSharp.text.pdf.PdfReader reader = null;
            bool status = true;

            try
            {
                CubePdf.Misc.File.Move(setting.OutputPath, tmp, true);
                reader = new iTextSharp.text.pdf.PdfReader(tmp);
                var writer = new iTextSharp.text.pdf.PdfStamper(reader,
                                                                new System.IO.FileStream(setting.OutputPath, System.IO.FileMode.Create), PdfVersionToiText(setting.PDFVersion));

                // 文書プロパティ
                Dictionary <string, string> info = new Dictionary <string, string>();
                info["Title"]    = setting.Document.Title;
                info["Author"]   = setting.Document.Author;
                info["Subject"]  = setting.Document.Subtitle;
                info["Keywords"] = setting.Document.Keyword;
                info["Creator"]  = Properties.Resources.ProductName;
                info["Producer"] = Properties.Resources.ProductName;
                writer.MoreInfo  = info;

                // デバッグログ
                var message = new System.Text.StringBuilder();
                message.AppendLine("iTextSharp.text.pdf.PdfStamper.MoreInfo");
                message.AppendLine(String.Format("\tTitle    = {0}", info["Title"]));
                message.AppendLine(String.Format("\tAuthor   = {0}", info["Author"]));
                message.AppendLine(String.Format("\tSubject  = {0}", info["Subject"]));
                message.Append(String.Format("\tKeywords = {0}", info["Keywords"]));
                _messages.Add(new Message(Message.Levels.Debug, message.ToString()));

                // パスワード and/or パーミッション
                string user  = !string.IsNullOrEmpty(setting.Password) ? setting.Password : string.Empty;
                string owner = !string.IsNullOrEmpty(setting.Permission.Password) ? setting.Permission.Password : string.Empty;
                if (string.IsNullOrEmpty(owner) && !string.IsNullOrEmpty(user))
                {
                    owner = user;
                }
                int permission = this.PermissionToiText(setting.Permission);
                if (!string.IsNullOrEmpty(user) || !string.IsNullOrEmpty(owner))
                {
                    writer.SetEncryption(iTextSharp.text.pdf.PdfWriter.STANDARD_ENCRYPTION_128, user, owner, permission);
                }

                writer.Close();
            }
            catch (Exception err)
            {
                _messages.Add(new Message(Message.Levels.Error, err));
                _messages.Add(new Message(Message.Levels.Debug, err));
                status = false;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (CubePdf.Misc.File.Exists(tmp))
                {
                    if (!CubePdf.Misc.File.Exists(setting.OutputPath))
                    {
                        CubePdf.Misc.File.Move(tmp, setting.OutputPath, true);
                    }
                    else
                    {
                        var fi = new System.IO.FileInfo(setting.OutputPath);
                        if (fi.Length == 0)
                        {
                            CubePdf.Misc.File.Move(tmp, setting.OutputPath, true);
                        }
                        else
                        {
                            CubePdf.Misc.File.Delete(tmp, false);
                        }
                    }
                }
            }

            return(status);
        }
Esempio n. 13
0
 /* ----------------------------------------------------------------- */
 ///
 /// IsValidPassword
 /// 
 /// <summary>
 /// 指定したパスワードが有効であるかどうかを判定する.
 /// </summary>
 /// 
 /* ----------------------------------------------------------------- */
 private static bool IsValidPassword(string path, string password)
 {
     var status = true;
     try
     {
         var test = new iTextSharp.text.pdf.PdfReader(path, System.Text.Encoding.UTF8.GetBytes(password));
         if (!test.IsOpenedWithFullPermissions) status = false;
         test.Close();
     }
     catch (Exception /* err */)
     {
         status = false;
     }
     return status;
 }
Esempio n. 14
0
        /* ----------------------------------------------------------------- */
        ///
        /// Open
        /// 
        /// <summary>
        /// PDF ファイルを開く。パスワードが必要な場合は、第 2 引数で指定
        /// されたパスワードで試行する。
        /// </summary>
        /// 
        /* ----------------------------------------------------------------- */
        private static iTextSharp.text.pdf.PdfReader Open(string path, string password)
        {
            iTextSharp.text.pdf.PdfReader dest = null;
            if (!IsProtected(path)) dest = new iTextSharp.text.pdf.PdfReader(path);
            else if (IsValidPassword(path, password))
            {
                dest = new iTextSharp.text.pdf.PdfReader(path, System.Text.Encoding.UTF8.GetBytes(password));
            }
            else throw new Exception(String.Format("パスワードで保護されているPDFファイルに結合する事はできません。", path));

            return dest;
        }
Esempio n. 15
0
        private void button_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog()
            {
                Filter = "PDF filers|*.pdf", ValidateNames = true, Multiselect = false
            })
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(ofd.FileName);
                        StringBuilder sd = new StringBuilder();
                        for (int i = 1; i <= reader.NumberOfPages; i++)
                        {
                            sd.Append(PdfTextExtractor.GetTextFromPage(reader, i));
                        }
                        //richTextBox1.Text = sd.ToString();
                        var content = sd.ToString();
                        //string[] sp = content.Split(':');
                        string[] sp = content.Split(new string[] { "Name 6:" }, StringSplitOptions.None);

                        //Console.WriteLine(sp.Length);
                        for (int i = 1; i < 5; i++)
                        {
                            string[] sp2 = sp[i].Split(':');
                            // Console.Write(sp[i].Length);
                            //Console.WriteLine("-");
                            for (int k = 0; k < sp2.Length; k++)
                            {
                                // if
                                if (k == 0 || k == 1 || k == 2 || k == 3 || k == 4)
                                {
                                    sp2[k] = sp2[k].Remove(sp2[k].Length - 1);
                                }
                                if ((sp2[k - 1].Substring(sp2[k - 1].Length - 3)) == "POD")
                                {
                                    sp2[k] = sp2[k].Remove(sp2[k].Length - 5);
                                }
                                if (sp2[k - 1].Substring(sp2[k - 1].Length - 3) == "DOB")
                                {
                                    sp2[k] = sp2[k].Remove(sp2[k].Length - 5);
                                }
                                if (sp2[k].Substring(sp2[k].Length - 5) == "a.k.a")
                                {
                                    sp2[k] = sp2[k].Remove(sp2[k].Length - 5);
                                }
                                if (sp2[k].Substring(sp2[k].Length - 8) == "Nationality")
                                {
                                    sp2[k] = sp2[k].Remove(sp2[k].Length - 17);
                                }
                                if (sp2[k].Substring(sp2[k].Length - 26) == "National Identification no")
                                {
                                    sp2[k] = sp2[k].Remove(sp2[k].Length - 9);
                                }
                                if (k == 10)
                                {
                                    sp2[k] = sp2[k].Remove(sp2[k].Length - 12);
                                }
                                if (k == 11)
                                {
                                    sp2[k] = sp2[k].Remove(sp2[k].Length - 8);
                                }
                                if (k == 12)
                                {
                                    sp2[k] = sp2[k].Remove(sp2[k].Length - 5);
                                }
                                //Console.Write(sp2[k]);
                                Console.Write(sp2[k].Substring(sp2[k].Length - 3));
                                Console.Write("||");
                            }
                            Console.WriteLine("-");
                        }

                        //Console.WriteLine(sp.Length);
                        //Console.WriteLine(sp[2]);
                        //for (int j = 1; j <= sp.Length; j++)
                        //{
                        //    string[] sp2 = sp[j].Split(':');
                        //    Console.Write(sp[j].Length);
                        //    //Console.WriteLine("-");
                        //    for (int k = 0; k <= sp2.Length; k++)
                        //    {
                        //        Console.Write(sp2[k]);
                        //        Console.Write(",");
                        //    }
                        //    Console.WriteLine("-");
                        //}



                        //Console.WriteLine(sp.Length);
                        //  richTextBox1.Text = sp.Length.ToString();
                        //for(int i=1;i<=content.Length;i++)
                        //{
                        //    richTextBox1.Text = i.ToString();
                        //}
                        //richTextBox1.Text = sp[00];

                        reader.Close();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
Esempio n. 16
0
        private void ConvertToStream(string fileUrl)
        {
            try
            {
                Thread waitThread = new Thread(() =>
                {
                    PleaseWaitWindow wait = new PleaseWaitWindow();

                    wait.ShowDialog();
                    // wait.LoadingAdorner.IsAdornerVisible = true;
                    wait.Close();
                });
                waitThread.SetApartmentState(ApartmentState.STA);
                waitThread.Start();
            }

            catch
            {
            }

            System.Threading.Thread.Sleep(2000);

            try
            {
                //  ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

                HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(fileUrl);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();



                var    theStream = new object();
                string fileName  = AppDomain.CurrentDomain.BaseDirectory + "Printings" + @"\toPrint.pdf";


                using (var stream = File.Create(fileName))
                {
                    File.SetAttributes(fileName, FileAttributes.Normal);
                    response.GetResponseStream().CopyTo(stream);
                }

                iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(fileName);
                int numberOfPages = pdfReader.NumberOfPages;

                if (GlobalCounters.numberOfCurrentPrintings + numberOfPages <= Convert.ToInt32("6"))
                {
                    try
                    {
                        // this.log.Info("Invoking Action: ViewPrintRequested " + numberOfPages.ToString() + " pages.");
                    }
                    catch
                    { }

                    System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                    info.UseShellExecute = true;
                    info.WindowStyle     = System.Diagnostics.ProcessWindowStyle.Hidden;
                    info.Verb            = "print";
                    info.FileName        = fileName;
                    info.CreateNoWindow  = true;


                    System.Diagnostics.Process p = new System.Diagnostics.Process();
                    p.StartInfo = info;
                    p.Start();

                    p.WaitForInputIdle();
                    p.CloseMainWindow();

                    /*  if (numberOfPages < Int32.Parse(this.numberOfAvailabelPagesToPrint))
                     * {
                     *    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(numberOfPages));
                     * }
                     * else
                     * {
                     *    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
                     * }*/
                    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(6));

                    if (false == p.CloseMainWindow())
                    {
                        try
                        {
                            p.Kill();
                        }
                        catch { }
                    }
                    else
                    {
                        try
                        {
                            p.Kill();
                        }
                        catch { }
                    }

                    try
                    {
                        //  this.sender.SendAction("Printed " + numberOfPages + " pages.");
                    }
                    catch { }
                    GlobalCounters.numberOfCurrentPrintings += numberOfPages;
                }

                else
                {
                    System.Windows.MessageBox.Show("Unfortunately, you can not print so many pages! Please press OK to continue.");
                }
            }
            catch
            {
            }
            finally
            {
                //response.Close();
            }
        }
        private void verifySingleItem()
        {
            addresscollection aic = new addresscollection();
            string sourceFileName = _sourcefilename;
            FileStream x = new FileStream(sourceFileName, FileMode.Open);
            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(x);

            //AWESOME!!
            //      x.Close()

            //x.Dispose()
            string s = "";
            string s1 = "";
            System.Xml.XmlNode ep = null;
            System.Xml.XmlNode batch = null;
            int pages = reader.NumberOfPages;
            reader.Close();
            x.Close();
            if (parseaddresssingle(ref _aiSingle, pages)) {
                //Des not catch a single first page, anytime this is true it's a new first page
                //    ep.InnerText = i + 1
                // Console.WriteLine(ai.Address1)

            }
            aic.Add(_aiSingle);

            reader.Close();
            //Me.RichTextBox1.Invoke(New updatert(AddressOf updaterichtext), New Object() {XMLDOC.OuterXml, badaddress})
            Invoke(new updatert(updaterichtext), new object[] {
                XMLDOC,
                badaddress
            });
            //Me.RichTextBox1.Invoke(New updatert(AddressOf updaterichtext), New Object() {badaddress})
            Invoke(new updatedatagrid(updatedatagridonMail), new object[] { aic });
            Invoke(new updatecomplete(updatecompleted), new object[]{});

            //rtrf(0) = rf2
            //textExtractionStrategy = New iTextSharp.text.pdf.parser.FilteredTextRenderListener(mystrat, rtrf)
            //MsgBox(iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, 1, textExtractionStrategy))
            // iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, 1, textExtractionStrategy)
        }
Esempio n. 18
0
        private void ConvertToStream(string fileUrl)
        {
            try
            {
                this.events.PublishOnUIThread(new ViewStartPrintProgressCommand());
            }

            catch (Exception ex)
            {
                this.log.Info("InvokingAction: ViewException " + ex.ToString());
            }

            System.Threading.Thread.Sleep(3000);

            try {
                ServicePointManager
                .ServerCertificateValidationCallback +=
                    (sender, cert, chain, sslPolicyErrors) => true;

                HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(fileUrl);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();



                var    theStream = new object();
                string fileName  = AppDomain.CurrentDomain.BaseDirectory + "Printings" + @"\toPrint.pdf";


                using (var stream = File.Create(fileName))
                {
                    File.SetAttributes(fileName, FileAttributes.Normal);
                    response.GetResponseStream().CopyTo(stream);
                }

                iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(fileName);
                int numberOfPages = pdfReader.NumberOfPages;

                if (GlobalCounters.numberOfCurrentPrintings + numberOfPages <= Convert.ToInt32(this.numberOfAvailabelPagesToPrint))
                {
                    try
                    {
                        this.log.Info("Invoking Action: ViewPrintRequested " + numberOfPages.ToString() + " pages.");
                    }
                    catch
                    { }

                    try
                    {
                        TaskbarManager.HideTaskbar();
                    }
                    catch { }

                    try
                    {
                        System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                        info.UseShellExecute = true;
                        info.WindowStyle     = System.Diagnostics.ProcessWindowStyle.Hidden;
                        info.Verb            = "print";
                        info.FileName        = fileName;
                        info.CreateNoWindow  = true;


                        System.Diagnostics.Process p = new System.Diagnostics.Process();
                        p.StartInfo = info;
                        p.Start();

                        p.WaitForExit();
                        p.CloseMainWindow();


                        if (false == p.CloseMainWindow())
                        {
                            try
                            {
                                p.Kill();
                            }
                            catch { }
                        }
                        else
                        {
                            try
                            {
                                p.Kill();
                            }
                            catch { }
                        }
                    }
                    catch { }

                    GlobalCounters.numberOfCurrentPrintings += numberOfPages;

                    try
                    {
                        TaskbarManager.HideTaskbar();
                    }
                    catch { }

                    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(6));

                    try
                    {
                        TaskbarManager.HideTaskbar();
                    }
                    catch { }



                    try
                    {
                        this.sender.SendAction("Printed " + numberOfPages + " pages.");
                    }
                    catch { }
                }

                else
                {
                    System.Windows.MessageBox.Show("Unfortunately, you can not print so many pages! Please press OK to continue.");
                }
            }
            catch (Exception ex)
            {
                this.log.Info("InvokingAction: ViewException " + ex.ToString());
            }
            finally
            {
            }
        }
Esempio n. 19
0
        private void button1_Click(object sender, EventArgs e)
        {
            var datecombination = listBox1.SelectedValue.ToString();

            datecombination = datecombination.Replace(" To ", " , ");
            var           arrayelement = datecombination.Split(',');
            List <string> queryList    = Utilities.DataBaseUtility.GetList("select distinct start_date,end_date from Timesheets");
            //var stringvalue = String.Format("select e.FirstName,e.LastName,e.Role,g.gross_amt,n.netpay_amt,n.deduction_amt from ((employees e join netpay n on e.DocNum=n.Emp_id) join grosspay g on e.docnum=g.emp_id) where e.docNum=104 and n.paystartdate='{0}' and n.payenddate='{1}'", arrayelement[0].Substring(0, arrayelement[0].Length - 15).Trim(), arrayelement[1].Substring(0, arrayelement[0].Length - 14).Trim());
            int employeeID = 0;

            try
            {
                employeeID = Convert.ToInt32(employeesAdmin.Text);
            }
            catch (Exception ex)
            {
                employeeID = 104;
            }

            if (employeeID < 111 && employeeID > 100)
            {
            }
            else
            {
                employeeID = 104;
            }
            arrayelement[0] = arrayelement[0].Remove(arrayelement[0].Length - 15);

            //var stringvalue = "SELECT e.FirstName,e.LastName,e.Role,n.netpay_amt,n.deduction_amt from employees e inner join netpay n on e.DocNum=n.Emp_id";
            var stringvalue = "SELECT * FROM ([employees] AS [e] INNER JOIN [grosspay] AS [g] ON [e].[DocNum] = [g].[emp_id]) INNER JOIN [NETPAY] AS [N] ON [N].[emp_id]=[e].[DocNum] where [e].docNum=" + employeeID + " and [g].PayStartDate like '%" + arrayelement[0] + "%' and [N].PayStartDate like '%" + arrayelement[0] + "%'";
            //var stringvalue = String.Format("SELECT EMPLOYEES.FirstName, EMPLOYEES.Role, EMPLOYEES.gross_amt, EMPLOYEES.Role, NetPay.NetPay_Amt, NetPay.Benefits_Amt, NetPay.Deductions_Amt, GrossPay.GrossPay, GrossPay.PayStartDate, GrossPay.PayEndDateFROM EMPLOYEES, NetPay, GrossPay;");
            var value = Utilities.DataBaseUtility.GetList(stringvalue);

            String[] finalValue = value[1].Split(',');

            if (button1.Text.Equals("Download PaySlip"))
            {
                String     path     = System.AppDomain.CurrentDomain.BaseDirectory;
                String     fileName = "payslip.pdf";
                FileStream fs       = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Create, FileAccess.Write, FileShare.None);
                iTextSharp.text.Document      doc    = new iTextSharp.text.Document();
                iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, fs);
                doc.Open();
                String spacing   = "                                                                                         ";
                String imagepath = Directory.GetCurrentDirectory();

                imagepath = imagepath.Replace("\\bin\\Debug", "\\Images\\HawkLogo.bmp");
                //  + "\\Images\\HawkLogo.bmp";
                iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(imagepath);



                doc.Add(new Paragraph("-------------------------------------PAYSLIP - METRO VIDEO PHOTO -------------------------------------              "));
                doc.Add(gif);
                doc.Add(new Paragraph(spacing + "Employee ID : " + finalValue[0]));
                doc.Add(new Paragraph(spacing + "First Name : " + finalValue[2]));
                doc.Add(new Paragraph(spacing + "Last Name : " + finalValue[3]));
                doc.Add(new Paragraph(spacing + "Email ID : " + finalValue[12]));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph("Pay Period:"));
                doc.Add(new Paragraph("Start Date : " + finalValue[23]));
                doc.Add(new Paragraph("--------------------------------------------"));
                doc.Add(new Paragraph("End Date : " + finalValue[24]));
                doc.Add(new Paragraph("---------------------------"));
                doc.Add(new Paragraph("Total Overtime Pay : " + finalValue[25]));
                doc.Add(new Paragraph("---------------------------------------------"));
                doc.Add(new Paragraph("Gross Pay : " + finalValue[26]));
                doc.Add(new Paragraph("--------------------------------------------"));
                doc.Add(new Paragraph("Benefit Amount : " + finalValue[31]));
                doc.Add(new Paragraph("--------------------------------------------"));
                doc.Add(new Paragraph("Deduction Amount : " + finalValue[32]));
                doc.Add(new Paragraph("--------------------------------------------"));
                doc.Add(new Paragraph("Final Pay (Net Pay) : " + finalValue[36]));



                doc.Close();
                string FileLocation = System.AppDomain.CurrentDomain.BaseDirectory + fileName;
                //string WatermarkLocation = "C:\\Users\\Prithiviraj\\Desktop\\PDF Document\\Myimage.png";
                String WatermarkLocation = Directory.GetCurrentDirectory();

                WatermarkLocation = WatermarkLocation.Replace("\\bin\\Debug", "\\Applications\\Payroll\\Images\\bgconfidential.png");

                Document document = new Document();
                iTextSharp.text.pdf.PdfReader  pdfReader = new iTextSharp.text.pdf.PdfReader(FileLocation);
                iTextSharp.text.pdf.PdfStamper stamp     = new iTextSharp.text.pdf.PdfStamper(pdfReader, new FileStream(FileLocation.Replace(".pdf", "_" + finalValue[0] + ".pdf"), FileMode.Create));

                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(WatermarkLocation);
                img.SetAbsolutePosition(0, 5); // set the position in the document where you want the watermark to appear (0,0 = bottom left corner of the page)

                iTextSharp.text.pdf.PdfContentByte waterMark;
                for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                {
                    waterMark = stamp.GetUnderContent(page);
                    waterMark.AddImage(img);
                }
                stamp.FormFlattening = true;
                stamp.Close();
                label1.Visible = true;
                label1.Text    = "Your file (payslip.pdf) is succssfully downloaded";
            }

            else if (button1.Text.Equals("View Gross Pay"))
            {
                label1.Visible = true;
                label1.Text    = "Gross Pay";

                heading1.Visible = true;
                heading2.Visible = true;
                heading3.Visible = true;
                heading4.Visible = true;
                heading5.Visible = true;
                heading6.Visible = true;

                value1.Visible = true;
                value2.Visible = true;
                value3.Visible = true;
                value4.Visible = true;
                value5.Visible = true;
                value6.Visible = true;


                heading1.Text = "Employee ID: ";
                heading2.Text = "Regular Hourly Pay Rate: ";
                heading3.Text = "Overtime Hourly Pay Rate: ";
                heading4.Text = "Num of Regular Hours: ";
                heading5.Text = "Num of overtime Hours: ";
                heading6.Text = "Gross Pay: ";

                int regHours      = Convert.ToInt32(finalValue[22]) / Convert.ToInt32(finalValue[20]);
                int overTimeHours = Convert.ToInt32(finalValue[25]) / Convert.ToInt32(finalValue[21]);

                value1.Text = finalValue[0];
                value2.Text = "$" + finalValue[20];
                value3.Text = "$" + finalValue[21];
                value4.Text = regHours.ToString();
                value5.Text = overTimeHours.ToString();
                value6.Text = "$" + finalValue[26];
            }
            else if (button1.Text.Equals("View Net Pay"))
            {
                label1.Visible = true;
                label1.Text    = "Net Pay";

                heading1.Visible = true;
                heading2.Visible = true;
                heading3.Visible = true;
                heading4.Visible = true;
                heading5.Visible = true;
                //  heading6.Visible = true;

                value1.Visible = true;
                value2.Visible = true;
                value3.Visible = true;
                value4.Visible = true;
                value5.Visible = true;
                //   value6.Visible = true;


                heading1.Text = "Employee ID: ";
                heading2.Text = "Gross Pay: ";
                heading3.Text = "Total Benefits: ";
                heading4.Text = "Total Deductions: ";
                heading5.Text = "Net Pay: ";
                //  heading6.Text = "Gross Pay: ";

                value1.Text = finalValue[0];
                value2.Text = "$" + finalValue[26];
                value3.Text = "$" + finalValue[31];
                value4.Text = "$" + finalValue[32];
                value5.Text = "$" + finalValue[36];
                // value6.Text = finalValue[26];
            }
        }
        public void verify()
        {
            addresscollection aic = new addresscollection();
            addressitem ai = null;
            string sourceFileName = _sourcefilename;
            FileStream x = new FileStream(sourceFileName, FileMode.Open);
            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(x);
            //AWESOME!!
            x.Close();
            x.Dispose();
            string s = "";
            string s1 = "";
            System.Xml.XmlNode ep = null;
            System.Xml.XmlNode batch = null;
            System.Xml.XmlNode startingpage = null;
            System.Xml.XmlNode envelope = null;
            int pages = reader.NumberOfPages;
            int i;
            for (i = 0; i <= reader.NumberOfPages - 1; i++) {
                this.Label2.Invoke(new updatetext(updatelabel1text), new object[] { "Processing Page " + Convert.ToString(i + 1)  + " of " + pages });
                DataRow dr = _dtt.Rows[0];
                System.util.RectangleJ rect1 = new System.util.RectangleJ(Convert.ToInt32( dr["x"]), Convert.ToInt32( dr["y"]), Convert.ToInt32( dr["width"]), Convert.ToInt32( dr["height"]));
                iTextSharp.text.pdf.parser.RegionTextRenderFilter rf = new iTextSharp.text.pdf.parser.RegionTextRenderFilter(rect1);
                iTextSharp.text.pdf.parser.LocationTextExtractionStrategy mystrat = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
                iTextSharp.text.pdf.parser.RegionTextRenderFilter[] rtrf = new iTextSharp.text.pdf.parser.RegionTextRenderFilter[2];
                rtrf[0] = rf;
                //Dim rect2 As New System.util.RectangleJ(0, 700, 800, 140)
                //Dim rf2 As New iTextSharp.text.pdf.parser.RegionTextRenderFilter(rect2)
                iTextSharp.text.pdf.parser.FilteredTextRenderListener textExtractionStrategy = new iTextSharp.text.pdf.parser.FilteredTextRenderListener(mystrat, rtrf);

                DataRow dr1 = _dtt.Rows[1];
                System.util.RectangleJ rect2 = new System.util.RectangleJ(Convert.ToInt32( dr1["x"]), Convert.ToInt32( dr1["y"]), Convert.ToInt32( dr1["width"]), Convert.ToInt32( dr1["height"]));
                iTextSharp.text.pdf.parser.RegionTextRenderFilter rf1 = new iTextSharp.text.pdf.parser.RegionTextRenderFilter(rect2);
                iTextSharp.text.pdf.parser.LocationTextExtractionStrategy mystrat1 = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
                iTextSharp.text.pdf.parser.RegionTextRenderFilter[] rtrf1 = new iTextSharp.text.pdf.parser.RegionTextRenderFilter[2];
                rtrf1[0] = rf1;
                //Dim rect2 As New System.util.RectangleJ(0, 700, 800, 140)
                //Dim rf2 As New iTextSharp.text.pdf.parser.RegionTextRenderFilter(rect2)
                iTextSharp.text.pdf.parser.FilteredTextRenderListener textExtractionStrategy1 = new iTextSharp.text.pdf.parser.FilteredTextRenderListener(mystrat1, rtrf1);

                s = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, i + 1, textExtractionStrategy);

                if (!string.IsNullOrEmpty(s)) {
                    s1 = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, i + 1, textExtractionStrategy1);

                    if (parseaddress(s, s1, ref batch, i + 1, ref ep, ref envelope, ref startingpage, ref ai)) {
                        //Des not catch a single first page, anytime this is true it's a new first page
                        //    ep.InnerText = i + 1
                        // Console.WriteLine(ai.Address1)
                        aic.Add(ai);
                    }

                }

                if (i == reader.NumberOfPages - 1 & (ep != null)) {
                    ep.InnerText = Convert.ToString(i + 1);
                }

                if (i == reader.NumberOfPages - 1 & (ai != null)) {
                    ai.endpage = Convert.ToInt32( i + 1);
                }
                // CurrentPage = CurrentPage + 1
            }
            reader.Close();
            //Me.RichTextBox1.Invoke(New updatert(AddressOf updaterichtext), New Object() {XMLDOC.OuterXml, badaddress})
            this.RichTextBox1.Invoke(new updatert(updaterichtext), new object[] {
                XMLDOC,
                badaddress
            });
            //Me.RichTextBox1.Invoke(New updatert(AddressOf updaterichtext), New Object() {badaddress})
            Invoke(new updatedatagrid(updatedatagridonMail), new object[] { aic });
            Invoke(new updatecomplete(updatecompleted), new object[]{});

            //rtrf(0) = rf2
            //textExtractionStrategy = New iTextSharp.text.pdf.parser.FilteredTextRenderListener(mystrat, rtrf)
            //MsgBox(iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, 1, textExtractionStrategy))
            // iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, 1, textExtractionStrategy)
        }
        public string ExtractTextFromRegionOfPdf(string sourceFileName)
        {
            FileStream x = new FileStream(sourceFileName, FileMode.Open);
            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(x);
            //AWESOME!!

            System.util.RectangleJ rect1 = new System.util.RectangleJ(Rect.X, System.Math.Abs(this.PictureBox1.Height - Rect.Y) - Rect.Height, Rect.Width, Rect.Height);
            iTextSharp.text.pdf.parser.RegionTextRenderFilter rf = new iTextSharp.text.pdf.parser.RegionTextRenderFilter(rect1);
            iTextSharp.text.pdf.parser.LocationTextExtractionStrategy mystrat = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
            iTextSharp.text.pdf.parser.RegionTextRenderFilter[] rtrf = new iTextSharp.text.pdf.parser.RegionTextRenderFilter[2];
            rtrf[0] = rf;
            //Dim rect2 As New System.util.RectangleJ(0, 700, 800, 140)
            //Dim rf2 As New iTextSharp.text.pdf.parser.RegionTextRenderFilter(rect2)
            iTextSharp.text.pdf.parser.FilteredTextRenderListener textExtractionStrategy = new iTextSharp.text.pdf.parser.FilteredTextRenderListener(mystrat, rtrf);

            //rtrf(0) = rf2
            //textExtractionStrategy = New iTextSharp.text.pdf.parser.FilteredTextRenderListener(mystrat, rtrf)
            //MsgBox(iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, 1, textExtractionStrategy))
            // iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, 1, textExtractionStrategy)
            x.Close();
            x.Dispose();
            reader.Close();

            if (_mode == 1) {

                if (this.loadedbool) {
                    string s = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, CurrentPage + 1, textExtractionStrategy);

                    DialogResult y =  MessageBox.Show("This field is showing : " + s + "\r\n" + "Is this the correct variable on this page?","Confirm" , MessageBoxButtons.YesNo );

                    if (y == DialogResult.Yes ) {

                        _dtt.Rows[_CurrentCount]["x"] = Rect.X;
                        _dtt.Rows[_CurrentCount]["y"] = System.Math.Abs(this.PictureBox1.Height - Rect.Y) - Rect.Height;
                        _dtt.Rows[_CurrentCount]["width"] = Rect.Width;
                        _dtt.Rows[_CurrentCount]["height"] = Rect.Height;

                        if (_CurrentCount == 0) {
                            DialogResult xx = MessageBox.Show("There is an optional Parimeter where you can select something that only appears on the first page, do you want to add this.  It can be part of a string like Page 1 of XX?", "Confirm", MessageBoxButtons.YesNo);
                            if (xx == DialogResult.No)
                            {
                                _CurrentCount = 2;
                            }
                        }

                        if (_dtt.Rows[_CurrentCount]["FieldName"] == "FirstPageConstant") {
                            _validatetext = Interaction.InputBox("Enter Charectors to match, if you enter \"1 of \" it will be true for anything after the of");
                            _dtt.Rows[_CurrentCount + 1]["misc"] = _validatetext;
                            _CurrentCount += 1;
                        }
                        _CurrentCount += 1;

                        if (_CurrentCount == 3) {
                            _CurrentCount = 0;
                            this.Label2.Text = "OK, you have completed the template, if you wish to start over simply do it again and start by selecting the area with:" + _dtt.Rows[0]["fieldname"];
                            startover = 1;
                            drawrectangles();

                            MessageBox.Show("Make sure you save this if you want to use it in the future.");

                        } else {
                            this.Label2.Text = "Now Select : " + _dtt.Rows[_CurrentCount]["fieldname"];
                        }
                    }
                }
            } else {
                this.Label2.Text = "OK, you have completed the template, if you wish to start over simply do it again and start by selecting the area with:" + _dtt.Rows[0]["fieldname"];
            }
            return "";
        }
Esempio n. 22
0
        /// <summary>
        /// Uses the GetResponseCore and GetResponseCoreFinalize to 'inherit' the IFilter behaviour
        /// but also extend it with iTextSharp
        /// </summary>
        /// <remarks>
        /// Add iTextSharp to get better 'title'
        /// [v7] fix by [email protected]	
        /// </remarks>
        public override bool GetResponse(System.Net.HttpWebResponse webresponse)
        {
            string filename = System.IO.Path.Combine(Preferences.DownloadedTempFilePath, (System.IO.Path.GetFileName(this.Uri.LocalPath)));

            base.GetResponseCore(webresponse, filename);

            // [v7] fix by [email protected]
            iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(filename);
            if (null != pdfReader.Info["Title"])
            {   // overwrite the 'filename' with the embedded title
                string pdfTitle = Convert.ToString(pdfReader.Info["Title"]).Trim();
                if (!String.IsNullOrEmpty(pdfTitle))
                {
                    this.Title = pdfTitle;
                }
            }

            // Now, since we've loaded the iTextSharp library, and the EPocalipse IFilter sometimes
            // fails (old Acrobat, installation problem, etc); let's try 'indexing' the PDF with iTextSharp
            // [v7]
            if (String.IsNullOrEmpty(this.All))
            {
                this.All = String.Empty;
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                // Following code from:
                // http://www.vbforums.com/showthread.php?t=475759
                for (int p = 1; p <= pdfReader.NumberOfPages; p++)
                {
                    byte[] pageBytes = pdfReader.GetPageContent(p);

                    if (null != pageBytes)
                    {
                        iTextSharp.text.pdf.PRTokeniser token = new iTextSharp.text.pdf.PRTokeniser(new iTextSharp.text.pdf.RandomAccessFileOrArray(pageBytes));
                        while (token.NextToken())
                        {
                            iTextSharp.text.pdf.PRTokeniser.TokType tknType = token.TokenType;
                            string tknValue = token.StringValue;

                            if (tknType == iTextSharp.text.pdf.PRTokeniser.TokType.STRING)
                            {
                                sb.Append(token.StringValue);
                            }
                            else if (tknType == iTextSharp.text.pdf.PRTokeniser.TokType.NUMBER && tknValue == "-600")
                            {
                                sb.Append(" ");
                            }
                            else if (tknType == iTextSharp.text.pdf.PRTokeniser.TokType.OTHER && tknValue == "TJ")
                            {
                                sb.Append(" ");
                            }
                        }
                    }
                }
                this.All += sb.ToString().Replace('\0', ' ');
            }
            pdfReader.Close();

            base.GetResponseCoreFinalize(filename);

            if (!String.IsNullOrEmpty(this.All))
            {
                this.Description = base.GetDescriptionFromWordsOnly(WordsOnly);
                return true;
            }
            else
            {
                return false;
            }
        }
Esempio n. 23
0
 /* ----------------------------------------------------------------- */
 ///
 /// IsProtected
 /// 
 /// <summary>
 /// 指定した PDF ファイルがパスワードによるセキュリティが設定され
 /// ているかどうか判定する.
 /// </summary>
 /// 
 /* ----------------------------------------------------------------- */
 private static bool IsProtected(string path)
 {
     bool status = false;
     try
     {
         var test = new iTextSharp.text.pdf.PdfReader(path);
         status = !test.IsOpenedWithFullPermissions;
         test.Close();
     }
     catch (iTextSharp.text.pdf.BadPasswordException /* err */)
     {
         status = true;
     }
     return status;
 }
        private void verifysendsingletomultiple(string xtemplate, DataTable dt)
        {
            addresscollection aic = new addresscollection();
            string x = null;
            x = xtemplate;
            System.Xml.XmlNode batchnode = null;
            System.Xml.XmlNode recipients = null;

            FileStream x1 = new FileStream(_sourcefilename, FileMode.Open);
            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(x1);
            //AWESOME!!
            x1.Close();
            x1.Dispose();
            string s = "";
            string s1 = "";
            int nop = reader.NumberOfPages;
            reader.Close();
            System.Xml.XmlNode ep = null;
            System.Xml.XmlNode batch = null;
            int pages = reader.NumberOfPages;
            int i = 0;
            foreach (DataRow r in dt.Rows) {
                this.Label2.Invoke(new updatetext(updatelabel1text), new object[] { "Processing Page " + (i + 1) + " of " + dt.Rows.Count });
                i += 1;
                foreach (DataColumn c in dt.Columns) {
                    try {
                        if ((!object.ReferenceEquals(dt.Rows[1][c], DBNull.Value))) {
                            x = Strings.Replace(x, "{" + c.ColumnName + "}", (string) r[c]);
                        } else {
                            x = Strings.Replace(x, "{" + c.ColumnName + "}", "");
                        }

                    } catch {
                    }
                }
                x = Regex.Replace(x, "^\\s+$[\\r\\n]*", "", RegexOptions.Multiline);
                addressitem ai = null;

                if (parseaddresssingledoctomultiple(ref ai, ref batchnode, x, 1, nop, i, ref recipients)) {
                }
                //EVERY PAGE IS GOOD
                aic.Add(ai);
                x = xtemplate;
            }
            //Me.DataGridView2.DataSource = aic

            this.RichTextBox1.Invoke(new updatert(updaterichtext), new object[] {
                XMLDOC,
                badaddress
            });
            //Me.RichTextBox1.Invoke(New updatert(AddressOf updaterichtext), New Object() {badaddress})
            Invoke(new updatedatagrid(updatedatagridonMail), new object[] { aic });
            Invoke(new updatecomplete(updatecompleted), new object[]{});
        }
Esempio n. 25
0
        /// <summary>
        /// 获取指定PDF文件的总页码数
        /// </summary>
        /// <param name="strSourceFile">PDF文件路径</param>
        /// <returns></returns>
        public static int GetPdfFilePages(string strSourceFile, out string errorMsg)
        {
            errorMsg = string.Empty;
            int iPages = -1;

            if (System.IO.File.Exists(strSourceFile))
            {
                iTextSharp.text.pdf.PdfReader reader = null;
                try
                {
                    reader = new iTextSharp.text.pdf.PdfReader(strSourceFile);
                    iPages = reader.NumberOfPages;
                }
                catch (iTextSharp.text.exceptions.IllegalPdfSyntaxException)
                {
                    iPages   = -10;
                    errorMsg = "iTextSharp IllegalPdfSyntaxException";
                }
                catch (iTextSharp.text.exceptions.InvalidImageException)
                {
                    iPages   = -10;
                    errorMsg = "iTextSharp InvalidImageException";
                }
                catch (iTextSharp.text.exceptions.InvalidPdfException)
                {
                    iPages   = -10;
                    errorMsg = "iTextSharp InvalidPdfException";
                }
                catch (iTextSharp.text.exceptions.BadPasswordException)
                {
                    iPages   = -10;
                    errorMsg = "iTextSharp BadPasswordException";
                }
                catch (StackOverflowException es)
                {
                    iPages   = -1;
                    errorMsg = string.Format("iTextSharp Reader StackOverflowException Error:{0}", es.Message);
                }
                catch (Exception ex)
                {
                    iPages   = -1;
                    errorMsg = ex.Message;
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Dispose();
                    }
                }
            }
            else
            {
                iPages = -1;
            }
            if (errorMsg.Length > 0)
            {
                IOHelp.WriteLog(string.Format("pdffile={0}, error={1}", strSourceFile, errorMsg), 5, "checkpdfError");
            }
            return(iPages);
        }
Esempio n. 26
0
 ///<summary>open file via iTextSharp and return pdf v1.4 for PdfSharp</summary>
 static MemoryStream GetCompartibleStream(string filename)
 {
     MemoryStream outputStream = new MemoryStream();
     iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(filename);
     iTextSharp.text.pdf.PdfStamper pdfStamper = new iTextSharp.text.pdf.PdfStamper(reader, outputStream);
     pdfStamper.FormFlattening = true;
     pdfStamper.Writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4);
     pdfStamper.Writer.CloseStream = false;
     pdfStamper.Close();
     return outputStream;
 }
        public void countpage(string printPCLFile)
        {
            string docFile = printPCLFile;
            string msg     = "";

            try
            {
                if (docFile.ToLower().EndsWith("pdf"))
                {
                    iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(docFile);
                    int num = reader.NumberOfPages;

                    msg  = num + "页";
                    mnum = num;
                }
                if (docFile.ToLower().EndsWith("jpg"))
                {
                    mnum = 1;
                }
                if (docFile.ToLower().EndsWith("xlsx") || docFile.ToLower().EndsWith("xlsm"))
                {
                    string path  = System.IO.Directory.GetCurrentDirectory();
                    string sPath = path + "\\temp\\xlsx";

                    // MessageBox.Show(docFile+"\n"+ sPath, "sPath");
                    if (XLSConvertToPDF(docFile, sPath))
                    {
                        string pdffile = sPath + ".pdf";
                        // MessageBox.Show(pdffile,"pdffile");
                        iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(pdffile);
                        int num = reader.NumberOfPages;
                        msg  = num + "页";
                        mnum = num;
                    }
                }
                if (docFile.ToLower().EndsWith("doc") || docFile.ToLower().EndsWith("docx"))
                {
                    //this.textFilename.Text = msg;
                    object wordFile = docFile;
                    object oMissing = Missing.Value;
                    //自定义object类型的布尔值
                    object oTrue  = true;
                    object oFalse = false;

                    object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
                    //定义WORD Application相关
                    Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
                    //WORD程序不可见
                    appWord.Visible = false;
                    //不弹出警告框
                    appWord.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                    //打开要打印的文件
                    Microsoft.Office.Interop.Word.Document doc = appWord.Documents.Open(
                        ref wordFile,
                        ref oMissing,
                        ref oTrue,
                        ref oFalse,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing);
                    // 计算Word文档页数 
                    WdStatistic stat = WdStatistic.wdStatisticPages;
                    num = doc.ComputeStatistics(stat, ref oMissing);//.ComputeStatistics(stat, ref Nothing); 
                    //打印完关闭WORD文件
                    doc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);
                    //退出WORD程序
                    appWord.Quit(ref oMissing, ref oMissing, ref oMissing);
                    doc     = null;
                    appWord = null;
                    msg     = num + "页";
                    mnum    = num;
                }
            }
            catch (System.Exception ex)
            {
                msg = ex.Message;
            }
        }
        public byte[] PrintSignToPDF_TextSharp(Stream File, String Firma, String Firmante)
        {
            MemoryStream outputPdfStream = new MemoryStream();
            PdfDocument document = PdfDocument.FromStream(File);
            document.SerialNumber = "s/va4uPX-1f/a0cHS-wcqFnYOT-gpOHk4qL-h5OAgp2C-gZ2KioqK";
            PdfFont pdfFont = document.CreateStandardFont(PdfStandardFont.Helvetica);
            byte[] pdfBuffer = document.WriteToMemory();
            var reader = new iTextSharp.text.pdf.PdfReader(pdfBuffer);
            var stamper = new iTextSharp.text.pdf.PdfStamper(reader, outputPdfStream);

            iTextSharp.text.pdf.PdfContentByte pdfContentByte2;
            iTextSharp.text.Rectangle pageSize;
            try
            {
                pdfContentByte2 = stamper.GetOverContent(1);
                pageSize = reader.GetPageSizeWithRotation(1);
                pdfContentByte2.BeginText();
            }
            catch
            {
                pdfContentByte2 = stamper.GetOverContent(2);//PafinaFirma = 2
                pageSize = reader.GetPageSizeWithRotation(1);
                pdfContentByte2.BeginText();
            }

            //Firma = String.Format("{0} {1}", Firma, Firmante);
            string[] arrays = Firma.Split(' ');
            //iTextSharp.text.pdf.BaseFont baseFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);
            iTextSharp.text.pdf.BaseFont baseFont = iTextSharp.text.pdf.BaseFont.CreateFont("c:/windows/fonts/arial.ttf", iTextSharp.text.pdf.BaseFont.IDENTITY_H, true);

            pdfContentByte2.SetFontAndSize(baseFont, 12);
            pdfContentByte2.SetRGBColorFill(0, 0, 0);

            StringBuilder bloqueFirma = new StringBuilder();
            int contador = 0;
            int saltoLineaPixeles = 5;
            for (int i = 0; i < arrays.Length; i++)
            {
                bloqueFirma.Append(arrays[i]);
                bloqueFirma.Append(" ");
                contador++;
                if ((contador == 35) || ((saltoLineaPixeles > 13) && (contador == 36)))
                {
                    pdfContentByte2.ShowTextAligned(iTextSharp.text.pdf.PdfContentByte.ALIGN_LEFT, bloqueFirma.ToString(),
                                                         pageSize.Width - (pageSize.Width / 5),
                                                        (pageSize.Height / 3) - saltoLineaPixeles - 110, 0);
                    contador = 0;
                    bloqueFirma = new StringBuilder();
                    saltoLineaPixeles = saltoLineaPixeles + 20;
                }
                else if ((i + 1) == arrays.Length)
                {
                    pdfContentByte2.ShowTextAligned(iTextSharp.text.pdf.PdfContentByte.ALIGN_LEFT, bloqueFirma.ToString(),
                                                         pageSize.Width - (pageSize.Width / 5),
                                                        (pageSize.Height / 3) - saltoLineaPixeles - 110, 0);
                    saltoLineaPixeles = saltoLineaPixeles + 20;
                }
            }

            pdfContentByte2.ShowTextAligned(iTextSharp.text.pdf.PdfContentByte.ALIGN_LEFT, Firmante.ToString(),
                                                pageSize.Width - (pageSize.Width / 5),
                                            (pageSize.Height / 3) - saltoLineaPixeles - 110, 0);

            pdfContentByte2.EndText();

            stamper.Close();

            outputPdfStream.Close();
            outputPdfStream.Dispose();
            document.Close();

            return outputPdfStream.GetBuffer();
        }
Esempio n. 29
-1
 /// <summary>
 /// Return a page count for pdf
 /// </summary>
 /// <param name="pdfPath"></param>
 /// <returns></returns>
 public int PDFPageCount(string pdfPath)
 {
     try
     {
         iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(pdfPath);
         int pageCount = pdfReader.NumberOfPages;
         pdfReader.Close();
         return pageCount;
     }
     catch (Exception)
     {
         return 0;
     }
 }
Esempio n. 30
-1
        /* ----------------------------------------------------------------- */
        ///
        /// AddInformation
        ///
        /// <summary>
        /// PDF ファイルに対して、引数に指定されたユーザ設定にしたがって
        /// 必要な情報を付与します。
        /// </summary>
        /// 
        /// <remarks>
        /// iTextSharp を用いて以下の情報を付与します。
        /// 
        /// - 文書プロパティ
        /// - 文書を開くためのパスワード (UserPassword)
        /// - 権限編集のためのパスワード (OwnerPassword)
        /// - 各種パーミッション
        /// </remarks>
        ///
        /* ----------------------------------------------------------------- */
        private bool AddInformation(UserSetting setting)
        {
            if (!CubePdf.Misc.File.Exists(setting.OutputPath)) return false;

            string tmp = Utility.WorkingDirectory + '\\' + System.IO.Path.GetRandomFileName();

            iTextSharp.text.pdf.PdfReader reader = null;
            bool status = true;
            try
            {
                CubePdf.Misc.File.Move(setting.OutputPath, tmp, true);
                reader = new iTextSharp.text.pdf.PdfReader(tmp);
                var writer = new iTextSharp.text.pdf.PdfStamper(reader,
                    new System.IO.FileStream(setting.OutputPath, System.IO.FileMode.Create), PdfVersionToiText(setting.PDFVersion));

                // 文書プロパティ
                Dictionary<string, string> info = new Dictionary<string, string>();
                info["Title"] = setting.Document.Title;
                info["Author"] = setting.Document.Author;
                info["Subject"] = setting.Document.Subtitle;
                info["Keywords"] = setting.Document.Keyword;
                info["Creator"] = Properties.Resources.ProductName;
                info["Producer"] = Properties.Resources.ProductName;
                writer.MoreInfo = info;

                // デバッグログ
                var message = new System.Text.StringBuilder();
                message.AppendLine("iTextSharp.text.pdf.PdfStamper.MoreInfo");
                message.AppendLine(String.Format("\tTitle    = {0}", info["Title"]));
                message.AppendLine(String.Format("\tAuthor   = {0}", info["Author"]));
                message.AppendLine(String.Format("\tSubject  = {0}", info["Subject"]));
                message.Append(    String.Format("\tKeywords = {0}", info["Keywords"]));
                _messages.Add(new Message(Message.Levels.Debug, message.ToString()));

                // パスワード and/or パーミッション
                string user  = !string.IsNullOrEmpty(setting.Password) ? setting.Password : string.Empty;
                string owner = !string.IsNullOrEmpty(setting.Permission.Password) ? setting.Permission.Password : string.Empty;
                if (string.IsNullOrEmpty(owner) && !string.IsNullOrEmpty(user)) owner = user;
                int permission = this.PermissionToiText(setting.Permission);
                if (!string.IsNullOrEmpty(user) || !string.IsNullOrEmpty(owner))
                {
                    writer.SetEncryption(iTextSharp.text.pdf.PdfWriter.STANDARD_ENCRYPTION_128, user, owner, permission);
                }

                writer.Close();
            }
            catch (Exception err)
            {
                _messages.Add(new Message(Message.Levels.Error, err));
                _messages.Add(new Message(Message.Levels.Debug, err));
                status = false;
            }
            finally
            {
                if (reader != null) reader.Close();
                if (CubePdf.Misc.File.Exists(tmp))
                {
                    if (!CubePdf.Misc.File.Exists(setting.OutputPath)) CubePdf.Misc.File.Move(tmp, setting.OutputPath, true);
                    else
                    {
                        var fi = new System.IO.FileInfo(setting.OutputPath);
                        if (fi.Length == 0) CubePdf.Misc.File.Move(tmp, setting.OutputPath, true);
                        else CubePdf.Misc.File.Delete(tmp, false);
                    }
                }
            }

            return status;
        }