public static void Run()
        {
            try
            {
                // ExStart:CreatePdfA1
                // The path to the documents directory.
                string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_TechnicalArticles();

                // Create pdf document
                Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();

                // Instantiate License class and call its SetLicense method to use the license
                Aspose.Pdf.License license = new Aspose.Pdf.License();
                license.SetLicense("Aspose.Custom.lic");

                // Set the conformance property of Pdf class to predefined value
                pdf1.Conformance = Aspose.Pdf.Generator.PdfConformance.PdfA1B;

                // Add a section into the pdf document
                Aspose.Pdf.Generator.Section sec1 = pdf1.Sections.Add();

                // Save the document
                pdf1.Save(dataDir + "CreatePdfA1_out.pdf");
                // ExEnd:CreatePdfA1  
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
            }
        }
示例#2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting...");

            // Initialize license object
            Aspose.Pdf.License license = new Aspose.Pdf.License();
            // Set license
            license.SetLicense("Aspose.Pdf.lic");

            Console.WriteLine("Loading Document...");

            var pdfDocument = LoadDocument();

            var service = new HighlightService();

            Console.WriteLine("Highlighting...");

            var sw = new Stopwatch();

            sw.Start();
            var highlightCount = service.Highlight(pdfDocument, new System.Collections.Generic.List <string> {
                "lorem", "ip", "et", "ac"
            });

            sw.Stop();

            Console.WriteLine($"Finished highlighting '{highlightCount}' phrases");
            Console.WriteLine("Saving...");
            pdfDocument.Save(Path.Combine(Directory.GetCurrentDirectory(), "highlighted.pdf"));

            Console.WriteLine("====================");
            Console.WriteLine($"Highlighting took {sw.Elapsed.TotalSeconds} seconds");
        }
        public static void Run()
        {
            try
            {
                // ExStart:HelloWorldUsingAPI
                // The path to the documents directory.
                string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_General();

                // Create pdf document
                Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();

                // Instantiate License class and call its SetLicense method to use the license
                Aspose.Pdf.License license = new Aspose.Pdf.License();
                license.SetLicense("Aspose.Pdf.lic");

                // Add a section into the pdf document
                Aspose.Pdf.Generator.Section sec1 = pdf1.Sections.Add();

                // Add a text paragraph into the section
                sec1.Paragraphs.Add(new Aspose.Pdf.Generator.Text("Hello World"));           

                dataDir = dataDir + "HelloWorldUsingAPI_out.pdf";
                // Save the document
                pdf1.Save(dataDir);
                // ExEnd:HelloWorldUsingAPI
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
            }
            
        }
示例#4
0
        public static void Run()
        {
            try
            {
                // ExStart:HelloWorldUsingXSLT
                // The path to the documents directory.
                string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_General();

                // Create pdf document
                Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();

                // Instantiate License class and call its SetLicense method to use the license
                Aspose.Pdf.License license = new Aspose.Pdf.License();
                license.SetLicense("Aspose.Pdf.lic");

                // Bind XML and XSLT files to the document
                pdf1.BindXML(dataDir + "HelloWorldUsingXSLT.XML", dataDir + "HelloWorld.xslt");

                dataDir = dataDir + "HelloWorldUsingXSLT_out_.pdf";
                // Save the document
                pdf1.Save(dataDir);
                // ExEnd:HelloWorldUsingXSLT
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
            }
        }
示例#5
0
        public void SetPdfLicense()
        {
            var l = new Aspose.Pdf.License();

            //l.SetLicense(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Aspose.Total.lic"));
            l.SetLicense(LStream);
        }
示例#6
0
        public static void Run()
        {
            try
            {
                // ExStart:CreatePdfA1
                // The path to the documents directory.
                string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_TechnicalArticles();

                // Create pdf document
                Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();

                // Instantiate License class and call its SetLicense method to use the license
                Aspose.Pdf.License license = new Aspose.Pdf.License();
                license.SetLicense("Aspose.Custom.lic");

                // Set the conformance property of Pdf class to predefined value
                pdf1.Conformance = Aspose.Pdf.Generator.PdfConformance.PdfA1B;

                // Add a section into the pdf document
                Aspose.Pdf.Generator.Section sec1 = pdf1.Sections.Add();

                //Save the document
                pdf1.Save(dataDir + "CreatePdfA1_out_.pdf");
                // ExEnd:CreatePdfA1
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
            }
        }
        public static void Run()
        {
            try
            {
                // ExStart:HelloWorldUsingAPI
                // The path to the documents directory.
                string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_General();

                // Create pdf document
                Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();

                // Instantiate License class and call its SetLicense method to use the license
                Aspose.Pdf.License license = new Aspose.Pdf.License();
                license.SetLicense("Aspose.Pdf.lic");

                // Add a section into the pdf document
                Aspose.Pdf.Generator.Section sec1 = pdf1.Sections.Add();

                // Add a text paragraph into the section
                sec1.Paragraphs.Add(new Aspose.Pdf.Generator.Text("Hello World"));

                dataDir = dataDir + "HelloWorldUsingAPI_out.pdf";
                // Save the document
                pdf1.Save(dataDir);
                // ExEnd:HelloWorldUsingAPI
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
            }
        }
示例#8
0
        public MemoryStream WatermarkFile(MemoryStream s, string sUserName, DateTime dtCurrentDate, string sCompany)
        {
            Aspose.Pdf.License l2 = new Aspose.Pdf.License();
            l2.SetLicense("ASPOSE-DE-CCO-121128--140416092055-DE-SCO-157407.txt");
            l2.Embedded = true;
            Document pdfDocument = new Document(s);

            Document     pdfDocumentNoStamps = pdfDocument; //RemoveExistingWatermarks(pdfDocument);
            PdfFileStamp pdfStamp            = new PdfFileStamp(pdfDocumentNoStamps);

            return(AddWatermarkToFile(pdfDocumentNoStamps, ref pdfStamp, sUserName, dtCurrentDate, sCompany));
        }
示例#9
0
        public PdfModelProcessor()
        {
            license = new License();
            DocsPaDB.Query_DocsPAWS.ClientSideModelProcessor csmp = new DocsPaDB.Query_DocsPAWS.ClientSideModelProcessor();

            byte[] licenseContent = csmp.GetLicense("ASPOSE");
            if (licenseContent != null)
            {
                System.IO.MemoryStream licenseStream = new System.IO.MemoryStream(licenseContent, 0, licenseContent.Length);
                license.SetLicense(licenseStream);
                licenseStream.Close();
            }
        }
示例#10
0
        static void Main(string[] args)
        {
            foreach (var process in Process.GetProcessesByName("AcroRd32"))
            {
                process.Kill();
            }

            using var fileStream = File.Open("D:\\WorkAsposeFiles\\License.txt", FileMode.Open);

            var pdf = new Aspose.Pdf.License();

            pdf.SetLicense(fileStream);
            fileStream.Seek(0, SeekOrigin.Begin);

            var word = new Aspose.Words.License();

            word.SetLicense(fileStream);
            fileStream.Seek(0, SeekOrigin.Begin);

            var cells = new Aspose.Cells.License();

            cells.SetLicense(fileStream);

            var model = new SkuPdfModel()
            {
                Characteristics = new List <Characteristic>
                {
                    new Characteristic("Количество листов в пачке", "45 шт"),
                    new Characteristic("Класс бумаги", "C"),
                    new Characteristic("Плотность бумаги", "80 гр/м2"),
                    new Characteristic("Страна происхождения", "Россия")
                },
                Classifications = new List <Classification>
                {
                    new Classification("ОКПД2", "32.99.12.120 Ручки и маркеры с наконечником из фетра и прочих пористых материалов"),
                    new Classification("КПГЗ", "01.15.05.03.04 Принадлежности для досок и флипчартов"),
                    new Classification("КТРУ", "32.99.12.120-00000001 Маркер")
                },
                SupplierOffers = new List <SupplierOffer>
                {
                    new SupplierOffer("ООО \"ЯСТРЕБ\"", "5427713792", "1219511-21", "5-10 дней", "г Москва, обл Московская", 47, 20),
                    new SupplierOffer("ИП ВЛАДИМИР", "4767898456", "4578548-45", "2-3 часа", "г Казань, Татарстан", 30, 20),
                    new SupplierOffer("ООО \"ЖЕНЕРИК\"", "7894598723", "6578459-12", "1-2 недели", "г Москва, обл Московская", 50, 20)
                }
            };

            CreateTemplate(model);

            Process.Start("D:\\WorkAsposeFiles\\template.pdf");
        }
示例#11
0
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();

            fd.Filter           = "License Files (*.lic)|*.lic|All files (*.*)|*.*";
            fd.InitialDirectory = @"C:\";
            fd.Title            = "Please select a License file to Use.";
            fd.Multiselect      = false;
            if (fd.ShowDialog() == DialogResult.OK)
            {
                txtLicense.Text = fd.FileName;
                Aspose.Pdf.License lic = new Aspose.Pdf.License();
                lic.SetLicense(txtLicense.Text);
            }
        }
示例#12
0
 protected License() 
 {
     try
     {
         if (_license == null)
         {
             _license = new AsposePdf.License();
             _license.SetLicense(GetLicence());
         }
     }
     catch (Exception e)
     {
         Logger.LogError(e);
     }
 }
        public static void Run()
        {
            try
            {
                // ExStart:ImageFromMemory
                // The path to the documents directory.
                string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_General();

                // Set the license for Aspose.Pdf
                Aspose.Pdf.License license = new Aspose.Pdf.License();
                license.SetLicense("Aspose.Custom.lic");

                // Create a memory stream object
                System.IO.MemoryStream mstream = new System.IO.MemoryStream(); 

                // Instantiate a Pdf object
                Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();

                // Create a new section in the Pdf document
                Aspose.Pdf.Generator.Section sec1 = new Aspose.Pdf.Generator.Section(pdf1); 

                // Add the section in the sections collection of the Pdf document
                pdf1.Sections.Add(sec1); 

                // Create an image object
                Aspose.Pdf.Generator.Image image1 = new Aspose.Pdf.Generator.Image(sec1); 

                // Add the image into paragraphs collection of the section
                sec1.Paragraphs.Add(image1); 

                image1.ImageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Bmp; 

                // Set the ImageStream to a MemoryStream object
                image1.ImageInfo.ImageStream = mstream ; 

                // Set desired the image scale
                image1.ImageScale = 0.5F; 

                // Save the Pdf
                pdf1.Save(dataDir + "ImageFromMemory_out.pdf"); 
                // ExEnd:ImageFromMemory
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
            }
            
        }
示例#14
0
        public static void Run()
        {
            try
            {
                // ExStart:ImageFromMemory
                // The path to the documents directory.
                string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_General();

                // Set the license for Aspose.Pdf
                Aspose.Pdf.License license = new Aspose.Pdf.License();
                license.SetLicense("Aspose.Custom.lic");

                // Create a memory stream object
                System.IO.MemoryStream mstream = new System.IO.MemoryStream();

                // Instantiate a Pdf object
                Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();

                // Create a new section in the Pdf document
                Aspose.Pdf.Generator.Section sec1 = new Aspose.Pdf.Generator.Section(pdf1);

                // Add the section in the sections collection of the Pdf document
                pdf1.Sections.Add(sec1);

                // Create an image object
                Aspose.Pdf.Generator.Image image1 = new Aspose.Pdf.Generator.Image(sec1);

                // Add the image into paragraphs collection of the section
                sec1.Paragraphs.Add(image1);

                image1.ImageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Bmp;

                // Set the ImageStream to a MemoryStream object
                image1.ImageInfo.ImageStream = mstream;

                // Set desired the image scale
                image1.ImageScale = 0.5F;

                // Save the Pdf
                pdf1.Save(dataDir + "ImageFromMemory_out.pdf");
                // ExEnd:ImageFromMemory
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
            }
        }
示例#15
0
        protected static void CheckLicense(LicenseProvider provider)
        {
            try
            {
                switch (provider)
                {
                case LicenseProvider.Cells:
                    var license1 = new Aspose.Cells.License();
                    license1.SetLicense(LICENSEPATH);
                    break;

                case LicenseProvider.Diagram:
                    var license2 = new Aspose.Diagram.License();
                    license2.SetLicense(LICENSEPATH);
                    break;

                case LicenseProvider.Pdf:
                    var license3 = new Aspose.Pdf.License();
                    license3.SetLicense(LICENSEPATH);
                    break;

                case LicenseProvider.Slides:
                    var license4 = new Aspose.Slides.License();
                    license4.SetLicense(LICENSEPATH);
                    break;

                case LicenseProvider.Words:
                    var license5 = new Aspose.Words.License();
                    license5.SetLicense(LICENSEPATH);
                    break;

                case LicenseProvider.Tasks:
                    var license6 = new Aspose.Tasks.License();
                    license6.SetLicense(LICENSEPATH);
                    break;

                case LicenseProvider.Imaging:
                    var license7 = new Aspose.Imaging.License();
                    license7.SetLicense(LICENSEPATH);
                    break;
                }
            }
            catch (Exception ex)
            {
                WriteLicenseException(ex);
            }
        }
        public void Start()
        {
            Aspose.Pdf.License pdflicense = new Aspose.Pdf.License();
            pdflicense.SetLicense(aposePDFLicense);
            pdflicense.Embedded = true;

            Aspose.BarCode.License barCodeLicense = new Aspose.BarCode.License();
            barCodeLicense.SetLicense(aposeBarCodeLicense);
            bool ff = barCodeLicense.IsLicensed;

            _timer = new System.Timers.Timer(30000);
            _timer.Elapsed += new ElapsedEventHandler(this.ServiceTimer_Tick);

            _timer.Enabled = true;
            _timer.Start();
            Log("Service Started");
        }
示例#17
0
        public string pdfConverter()
        {
            string dirpath  = Path.Combine(sourcePath, "Temp");
            string filepath = Path.Combine(dirpath, "Temp.jpeg");

            if (!Directory.Exists(dirpath))
            {
                Directory.CreateDirectory(dirpath);
            }

            Aspose.Pdf.License            licpdf = new Aspose.Pdf.License();
            Aspose.Pdf.Devices.JpegDevice dev    = new Aspose.Pdf.Devices.JpegDevice();
            Document pdfdoc = new Aspose.Pdf.Document(sourceFile);

            dev.Process(pdfdoc.Pages[1], filepath);

            return(filepath);
        }
        public static void Run()
        {
            try
            {
                // ExStart:HyphenationWhileCreatingPDF
                // The path to the documents directory.
                string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_TechnicalArticles();

                // Create pdf document
                Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();

                // Instantiate License class and call its SetLicense method to use the license
                Aspose.Pdf.License license = new Aspose.Pdf.License();
                license.SetLicense("Aspose.Pdf.lic");

                // Bind XML into the document
                pdf1.BindXML(dataDir + "Hyphen-test.xml", null);

                // Enable hyphenation function. Default value is false.
                pdf1.IsAutoHyphenated = true;

                // Set the hyphenation dictionary path.
                pdf1.HyphenationDictionaryPath = dataDir + "Hyphen.xml";

                // Set the hyphenation area width. Default value is 12 points.
                pdf1.HyphenationZoneWidth = 0;

                // Set the maximum number of consecutive hyphenations. Default value is zero that means no //limits.
                pdf1.ConsecutiveHyphensLimits = 0;

                // Save the Pdf file
                pdf1.Save(dataDir + "Hyphen-test_out_.pdf");
                // ExEnd:HyphenationWhileCreatingPDF
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
            }
        }
        public static void Run()
        {
            try
            {
                // ExStart:HyphenationWhileCreatingPDF
                // The path to the documents directory.
                string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_TechnicalArticles();

                // Create pdf document
                Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();

                // Instantiate License class and call its SetLicense method to use the license
                Aspose.Pdf.License license = new Aspose.Pdf.License();
                license.SetLicense("Aspose.Pdf.lic");

                // Bind XML into the document
                pdf1.BindXML(dataDir + "Hyphen-test.xml", null);

                // Enable hyphenation function. Default value is false.
                pdf1.IsAutoHyphenated = true;

                // Set the hyphenation dictionary path.
                pdf1.HyphenationDictionaryPath = dataDir + "Hyphen.xml";

                // Set the hyphenation area width. Default value is 12 points.
                pdf1.HyphenationZoneWidth = 0;

                // Set the maximum number of consecutive hyphenations. Default value is zero that means no // Limits.
                pdf1.ConsecutiveHyphensLimits = 0;

                // Save the Pdf file
                pdf1.Save(dataDir + "Hyphen-test_out.pdf");
                // ExEnd:HyphenationWhileCreatingPDF     
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
            }
        }
        public static void Run()
        {
            try
            {
                // ExStart:HelloWorldUsingXMLAndAPI
                // The path to the documents directory.
                string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_General();

                // Create pdf document
                Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();

                // Instantiate License class and call its SetLicense method to use the license
                Aspose.Pdf.License license = new Aspose.Pdf.License();
                license.SetLicense("Aspose.Pdf.lic");

                // Bind XML into the document
                pdf1.BindXML(dataDir + "HelloWorldUsingAPI.XML", null);

                // Get the first Section from the PDF document
                Aspose.Pdf.Generator.Section sec1 = pdf1.Sections[0];

                // Get the Text paragraph (whose ID is Text1) from the section
                Aspose.Pdf.Generator.Text text1 = sec1.Paragraphs["Text1"] as Aspose.Pdf.Generator.Text;

                // Add a text Segment to the text paragraph
                text1.Segments.Add("Hello World");

                dataDir = dataDir + "HelloWorldUsingXMLAndAPI_out_.pdf";
                // Save the document
                pdf1.Save(dataDir);
                // ExEnd:HelloWorldUsingXMLAndAPI
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
            }
        }
示例#21
0
        /// <summary>
        /// 開始既時作業
        /// </summary>
        private void StartRealTime()
        {
            EFilingMailService.RealTimeTimerFlag = true;

            Utility utility = null;

            string strSql = string.Empty;

            List <IDataParameter> para = null;

            DataTable dt = null;

            //string file_temp_dir_path = Path.Combine(ConfigPath.TempDirPath, Guid.NewGuid().ToString());
            try
            {
                //if (!Directory.Exists(file_temp_dir_path)) Directory.CreateDirectory(file_temp_dir_path);

                utility = new Utility();

                this.InitLog("RealTime");

                if (utility.XDocSetting == null)
                {
                    this.WriteLog(Mode.LogMode.INFO, string.Format("沒有設定檔")); return;
                }
                bool real_time_switch = ((string)utility.XDocSetting.Root.Descendants("Timer").Where(x => (string)x.Element("name") == "Real").FirstOrDefault().Element("switch")).ToUpper().Equals("Y");

                if (!real_time_switch)
                {
                    return;
                }

                List <string> ym_list = new List <string>();

                DateTime start_date = DateTime.Parse((string)utility.XDocSetting.Root.Descendants("Timer").Where(x => (string)x.Element("name") == "Real").FirstOrDefault().Element("startDate"));

                DateTime end_date = DateTime.Parse((string)utility.XDocSetting.Root.Descendants("Timer").Where(x => (string)x.Element("name") == "Real").FirstOrDefault().Element("endDate"));

                if (end_date.ToString("yyyyMM").Equals(start_date.ToString("yyyyMM")))
                {
                    ym_list.Add(start_date.ToString("yyyyMM"));
                }
                else
                {
                    DateTime start_date_temp = start_date;

                    DateTime end_date_temp = end_date;

                    while (!end_date_temp.ToString("yyyyMM").Equals(start_date_temp.ToString("yyyyMM")))
                    {
                        this.WriteLog(Mode.LogMode.INFO, string.Format("增加:{0}", end_date.ToString("yyyyMM")));

                        ym_list.Add(end_date_temp.ToString("yyyyMM"));

                        end_date_temp = end_date_temp.AddMonths(-1);
                    }
                }

                for (int i = 0; i < ym_list.Count; i++)
                {
                    string ym = ym_list[i];

                    strSql = utility.Select.BATCH_CIF_INFO(start_date.ToString("yyyy/MM/dd 00:00:00"), end_date.ToString("yyyy/MM/dd 23:59:59"), ym, ref para);

                    #region SQL Debug

                    this.WriteLog(Log.Mode.LogMode.DEBUG, strSql);

                    this.WriteLog(Log.Mode.LogMode.DEBUG, para.ToLog());

                    #endregion

                    utility.DBConn.GeneralSqlCmd.Command.CommandTimeout = 90;

                    dt = utility.DBConn.GeneralSqlCmd.ExecuteToDataTable(strSql, para);

                    this.WriteLog(Mode.LogMode.INFO, string.Format("{0}共有{1}筆資料", ym, dt.Rows.Count));

                    if (dt.Rows.Count.Equals(0))
                    {
                        continue;
                    }

                    string message = string.Empty;

                    var query = from batch in dt.AsEnumerable()
                                select new
                    {
                        CREATE_DATETIME      = batch.Field <DateTime>("CREATE_DATETIME"),
                        SESSION_KEY          = batch.Field <string>("SESSION_KEY"),
                        TXN_DATE             = batch.Field <DateTime>("TXN_DATE"),
                        TXN_ACCOUNT          = batch.Field <string>("TXN_ACCOUNT"),
                        BRANCH_ID            = batch.Field <string>("BRANCH_ID"),
                        FILE_ID              = batch.Field <string>("FILE_ID"),
                        FILE_CREATE_DATETIME = batch.Field <DateTime>("CREATE_DATETIME"),
                        FILE_SEQ             = batch.Field <Int16>("FILE_SEQ"),
                        FILE_ROOT            = batch.Field <string>("FILE_ROOT"),
                        FILE_PATH            = batch.Field <string>("FILE_PATH"),
                        PDF            = batch.Field <string>("PDF"),
                        FILE_TYPE      = batch.Field <Int16>("FILE_TYPE"),
                        T_MNEMONIC     = batch.Field <string>("T_MNEMONIC"),
                        T_EMAIL_SIGN_1 = batch.Field <string>("T_EMAIL_SIGN_1"),
                        T_EMAIL_1      = batch.Field <string>("T_EMAIL_1")
                    };

                    var queryG = query.GroupBy(o => o.T_MNEMONIC);

                    Aspose.Pdf.License licenseWordsTxt = new Aspose.Pdf.License();
                    licenseWordsTxt.SetLicense("Aspose.Pdf.lic");

                    //if (!Directory.Exists(file_temp_dir_path)) Directory.CreateDirectory(file_temp_dir_path);

                    string txt_file_path    = Path.Combine(ConfigPath.FtpDirPath, string.Format("{0}.txt", start_date.ToString("yyyyMMdd")));
                    string txt_OK_file_path = Path.Combine(ConfigPath.FtpDirPath, string.Format("{0}.OK", start_date.ToString("yyyyMMdd")));

                    txt_file_path.DeleteSigleFile();
                    txt_OK_file_path.DeleteSigleFile();

                    //StreamWriter streamWriter = new StreamWriter(txt_file_path, true, Encoding.UTF8);
                    //StreamWriter streamWriterOK = new StreamWriter(txt_OK_file_path, true, Encoding.UTF8);
                    using (StreamWriter streamWriterOK = new StreamWriter(txt_OK_file_path, true, Encoding.UTF8),
                           streamWriter = new StreamWriter(txt_file_path, true, Encoding.UTF8))
                    {
                        int fileNameOKCount = 0;

                        foreach (var item in queryG)
                        {
                            this.WriteLog(Log.Mode.LogMode.INFO, string.Format("準備產生{0}", item.Key));

                            Document docBasic = new Document();

                            string content = string.Empty;
                            string cif_ID  = string.Empty;

                            switch (item.Key.Length)
                            {
                            case 9:
                            case 11:
                                cif_ID = item.Key.Substring(0, item.Key.Length - 1);
                                break;

                            default:
                                cif_ID = item.Key;
                                break;
                            }

                            string pdf_file_path = Path.Combine(ConfigPath.FtpDirPath, string.Format("{0}_{1}_001.pdf", start_date.ToString("yyyyMMdd"), item.Key));

                            //if (!File.Exists(pdf_file_path))
                            {
                                long pdfFileSize        = 0;
                                bool isPDFSizeTooLength = false;
                                int  fileNameCount      = 1;

                                foreach (var batch in item)
                                {
                                    try
                                    {
                                        utility.DBLog(SysCode.A010, "Batch", batch.T_MNEMONIC, string.Format("開始產生PDF:{0}", Path.GetFileNameWithoutExtension(pdf_file_path)));

                                        string file_root = batch.FILE_ROOT;

                                        string file_path = batch.FILE_PATH;

                                        string file_full_path = file_root.FilePathCombine(file_path);

                                        bool exists = File.Exists(file_full_path);

                                        if (!exists)
                                        {
                                            this.WriteLog(Log.Mode.LogMode.ERROR, message = string.Format("SESSION_KEY:{0},CIF_ID:{1},FILE_ID:{2}::檔案不存在({3})", batch.SESSION_KEY, batch.T_MNEMONIC, batch.FILE_ID, file_full_path));
                                            continue;
                                        }
                                        // Load the source image file to Stream object
                                        FileStream fs = new FileStream(file_full_path, FileMode.Open, FileAccess.Read);

                                        pdfFileSize += fs.Length;

                                        byte[] tmpBytes = new byte[fs.Length];
                                        fs.Read(tmpBytes, 0, int.Parse(fs.Length.ToString()));

                                        MemoryStream mystream = new MemoryStream(tmpBytes);

                                        Document docAdd = new Document(mystream);

                                        docBasic.Pages.Add(docAdd.Pages);

                                        //大於9M的要先存檔
                                        if (pdfFileSize > 9437184)
                                        {
                                            pdf_file_path = Path.Combine(ConfigPath.FtpDirPath, string.Format("{0}_{1}_{2}.pdf", start_date.ToString("yyyyMMdd"), item.Key, fileNameCount.ToString().PadLeft(3, '0')));

                                            this.WriteLog(Log.Mode.LogMode.DEBUG, string.Format("pdfFileSize:{0}、pdf_file_path:{1}", pdfFileSize, pdf_file_path));

                                            content = Path.GetFileNameWithoutExtension(pdf_file_path) + "|" + cif_ID + "|" + batch.T_EMAIL_1 + "|" + batch.TXN_DATE.ToString("yyyyMMdd");

                                            this.WriteLog(Log.Mode.LogMode.DEBUG, string.Format("content:{0}", content));

                                            pdf_file_path.DeleteSigleFile();

                                            docBasic.Encrypt(cif_ID, cif_ID, 0, CryptoAlgorithm.AESx128);
                                            docBasic.Save(pdf_file_path);
                                            mystream.Close();
                                            docBasic.Pages.Clear();
                                            docBasic.Dispose();
                                            docBasic = null;

                                            docBasic = new Document();

                                            streamWriter.WriteLine(content);

                                            fileNameCount     += 1;
                                            fileNameOKCount   += 1;
                                            pdfFileSize        = 0;
                                            isPDFSizeTooLength = true;
                                        }
                                        else
                                        {
                                            isPDFSizeTooLength = false;
                                            content            = "|" + cif_ID + "|" + batch.T_EMAIL_1 + "|" + batch.TXN_DATE.ToString("yyyyMMdd");
                                        }
                                    }
                                    catch (System.Exception ex)
                                    {
                                        this.WriteLog(Log.Mode.LogMode.ERROR, ex.ToString());

                                        utility.DBLog(SysCode.E013, "Batch", batch.T_MNEMONIC, string.Format("{0}::{1}", Path.GetFileNameWithoutExtension(pdf_file_path), ex.Message));
                                    }
                                }

                                if (!isPDFSizeTooLength)
                                {
                                    pdf_file_path = Path.Combine(ConfigPath.FtpDirPath, string.Format("{0}_{1}_{2}.pdf", start_date.ToString("yyyyMMdd"), item.Key, fileNameCount.ToString().PadLeft(3, '0')));

                                    content = Path.GetFileNameWithoutExtension(pdf_file_path) + content;

                                    pdf_file_path.DeleteSigleFile();

                                    docBasic.Encrypt(cif_ID, cif_ID, 0, CryptoAlgorithm.AESx128);
                                    docBasic.Save(pdf_file_path);
                                    docBasic.Dispose();

                                    this.WriteLog(Log.Mode.LogMode.DEBUG, string.Format("content:{0}", content));
                                    fileNameOKCount += 1;
                                    streamWriter.WriteLine(content);
                                }
                            }
                            //else this.WriteLog(Log.Mode.LogMode.INFO, string.Format("已存在於準備上傳,將略過 ({0})", pdf_file_path));
                        }

                        streamWriterOK.WriteLine(string.Format("{0}.txt", start_date.ToString("yyyyMMdd")) + "," + fileNameOKCount);

                        streamWriter.Flush();
                        streamWriterOK.Flush();
                    }
                }

                this.WriteWorkingDateSwitch(utility);
            }
            catch (System.Exception ex)
            {
                this.WriteLog(Log.Mode.LogMode.ERROR, ex.ToString());
            }
            finally
            {
                if (utility != null)
                {
                    utility.CloseConn();

                    utility = null;
                }

                dt = null;

                para = null;

                GC.Collect(); GC.WaitForPendingFinalizers();

                EFilingMailService.RealTimeTimerFlag = false;
            }
        }
示例#22
0
        public PdfManipulator()
        {
            var licensePdf = new License();

            licensePdf.SetLicense("Aspose.Total.lic");
        }
示例#23
0
 public static void ApplyLicense()
 {
     Aspose.Pdf.License l2 = new Aspose.Pdf.License();
     l2.SetLicense("ASPOSE-DE-CCO-121128--140416092055-DE-SCO-157407.txt");
     l2.Embedded = true;
 }
示例#24
0
        public bool ParsePayslip(string oPayslipPath)
        {
            try
            {
                string     oDelimiter = "   ";
                int        index = 1;
                double     oTotalCredit = 0, oTotalDebit = 0, oGrossPayment = 0, oNetPayment = 0;
                DataAccess oDA = new DataAccess();

                Aspose.Pdf.License lic = new Aspose.Pdf.License();
                lic.SetLicense("TempLicense.lic");

                Document oPayslipDoc = new Document(oPayslipPath);

                TextAbsorber oPayslipExtracter = new TextAbsorber();
                oPayslipDoc.Pages.Accept(oPayslipExtracter);

                //extract data from pay-slip
                string[] oPayRecords = oPayslipExtracter.Text.Split('\n');

                //get company name
                string oCompanyName = oPayRecords[0].Trim();

                //get company address
                string oCompanyAddress = oPayRecords[1].Trim();

                //get payment month and year
                string[] oPayMonthYear = oPayRecords[2].Trim().Split('/');
                string   oPaymentMonth = oPayMonthYear[0].Substring(oPayMonthYear[0].Length - 3);
                int      oPaymentYear  = int.Parse(oPayMonthYear[1]);

                //get payroll number and employee name
                string[] oTemp          = Regex.Split(oPayRecords[3].Trim(), oDelimiter);
                int      oPayrollNumber = -1;
                string   oEmployeeName  = string.Empty;

                foreach (string val in oTemp)
                {
                    if (string.IsNullOrWhiteSpace(val))
                    {
                        continue;
                    }

                    if (index == 1 || index == 3)
                    {
                        index++;
                        continue;
                    }

                    if (index == 2)
                    {
                        oPayrollNumber = int.Parse(val.Trim());
                    }
                    if (index == 4)
                    {
                        oEmployeeName = val.Trim();
                    }

                    index++;
                }

                //get designation and department
                oTemp = Regex.Split(oPayRecords[4].Trim(), oDelimiter);
                string oDesignation = string.Empty, oDepartment = string.Empty;
                index = 1;

                foreach (string val in oTemp)
                {
                    if (string.IsNullOrWhiteSpace(val))
                    {
                        continue;
                    }

                    if (index == 1 || index == 3)
                    {
                        index++;
                        continue;
                    }

                    if (index == 2)
                    {
                        oDesignation = val.Trim();
                    }
                    if (index == 4)
                    {
                        oDepartment = val.Trim();
                    }

                    index++;
                }

                //get bank account number and remarks
                oTemp = Regex.Split(oPayRecords[5].Trim(), oDelimiter);
                long   oAccountNumber = -1;
                string oRemarks       = string.Empty;
                index = 1;

                foreach (string val in oTemp)
                {
                    if (string.IsNullOrWhiteSpace(val))
                    {
                        continue;
                    }

                    if (index == 1 || index == 3)
                    {
                        index++;
                        continue;
                    }

                    if (index == 2)
                    {
                        oAccountNumber = long.Parse(val.Trim());
                    }
                    if (index == 4)
                    {
                        oRemarks = val.Trim();
                    }

                    index++;
                }

                //remove existing records
                string oSQL  = string.Format("DELETE FROM eCanarysPayslip WHERE PaymentMonth='{0}' AND PaymentYear={1}", oPaymentMonth, oPaymentYear);
                bool   oFlag = oDA.ExecuteQuery(oSQL);
                if (!oFlag)
                {
                    return(false);
                }

                //get credit and debit payments
                string oCreditType     = string.Empty;
                double oCreditedAmount = 0;
                string oDebitType      = string.Empty;
                double oDebitedAmount  = 0;

                for (int i = 8; i < oPayRecords.Length; i++)
                {
                    if (string.IsNullOrWhiteSpace(oPayRecords[i]))
                    {
                        continue;
                    }

                    oTemp = Regex.Split(oPayRecords[i].Trim(), oDelimiter);
                    if (oTemp[0].Equals("Total"))
                    {
                        break;
                    }

                    index           = 1;
                    oCreditType     = string.Empty;
                    oCreditedAmount = 0;
                    oDebitType      = string.Empty;
                    oDebitedAmount  = 0;

                    foreach (string val in oTemp)
                    {
                        if (string.IsNullOrWhiteSpace(val))
                        {
                            continue;
                        }

                        if (index == 1)
                        {
                            oCreditType = val.Trim();
                        }

                        if (index == 2)
                        {
                            oCreditedAmount = double.Parse(val.Trim());
                        }

                        if (index == 3)
                        {
                            oDebitType = val.Trim();
                        }

                        if (index == 4)
                        {
                            oDebitedAmount = double.Parse(val.Trim());
                        }

                        index++;
                    }

                    oTotalCredit += oCreditedAmount;
                    oTotalDebit  += oDebitedAmount;

                    //insert payment records
                    oSQL  = "INSERT INTO eCanarysPayslip VALUES('{0}','{1}','{2}','{3}',{4},{5},'{6}','{7}','{8}',{9},'{10}','{11}',{12},'{13}',{14})";
                    oSQL  = string.Format(oSQL, Guid.NewGuid().ToString(), oCompanyName, oCompanyAddress, oPaymentMonth, oPaymentYear, oPayrollNumber, oEmployeeName, oDesignation, oDepartment, oAccountNumber, oRemarks, oCreditType, oCreditedAmount, oDebitType, oDebitedAmount);
                    oFlag = oDA.ExecuteQuery(oSQL);
                }

                //calc gross and net payment
                oGrossPayment = oTotalCredit + oTotalDebit;
                oNetPayment   = oTotalCredit - oTotalDebit;

                return(oFlag);
            }
            catch
            {
                return(false);
            }
        }
        static void Main(string[] args)
        {
            stopwatch.Start();

            writeToLog("Application PDBOT Started...");
            Console.WriteLine("Application PDBOT Started...");

            //license details
            Aspose.Words.License asposeWordsLicense = new Aspose.Words.License();
            asposeWordsLicense.SetLicense("Aspose.Words.lic");
            Aspose.Pdf.License asposePdfLisence = new Aspose.Pdf.License();
            asposePdfLisence.SetLicense("Aspose.Pdf.lic");

            string hflDocumentPath = null;
            string path = @"C:\Users\51210\Desktop\Customers\SG Finans\Oppgraderings Prosjekt SG Finans\BL0019\pdbot_control.xml";
            XmlDocument controlXMl = null;
            XmlNamespaceManager nsmngr = null;

            //Lists for saving values from control xml
            List<string> documentKeyswordsList = null;
            List<string> globalsKeywordsList = null;
            Aspose.Words.Document docTemplate = null;
            //load xml document
            try
            {
                controlXMl = new XmlDocument();
                controlXMl.Load(path);
                nsmngr = new XmlNamespaceManager(controlXMl.NameTable);
                nsmngr.AddNamespace("pdbot", "www.canon.no/pdbot");

                writeToLog("Control xml loaded successfuly");
            }
            catch (Exception e)
            {
                Console.WriteLine("Application PDBOT failed with error " + e.StackTrace);
                writeToLog("Error loading control xml " + e.StackTrace);
                Console.ReadKey();
            }
            //----------------------------------------------------------------------------------------------------------------------------------

            //get information from control xml nodes
            if (controlXMl != null)
            {
                try
                {
                    //get global document keys and value
                    //select Globals/Keys/Key
                   globalsKeywordsList = new List<string>();
                   XmlNodeList keyNodes = controlXMl.SelectNodes("//pdbot:Globals//pdbot:Keys//pdbot:Key", nsmngr);

                   if (keyNodes.Count != 0)
                   {
                       foreach (XmlNode KeyNode in keyNodes)
                       {
                           string keyword = KeyNode["Keyword"].InnerText;
                           string value = KeyNode["Value"].InnerText;
                           string KeywordAndValue = keyword + "|" + value;
                           globalsKeywordsList.Add(KeywordAndValue);

                       }
                       writeToLog("Global keywords and value read");
                   }
                    //---------------------------------------------------------------------------------------------------------------------------

                    //get Global sections
                    //select Globals/Sections/section
                    List<string> sectionsList = new List<string>();
                    XmlNodeList sectionNodes = controlXMl.SelectNodes("//pdbot:Globals//pdbot:Sections//pdbot:Section", nsmngr);
                    if (sectionNodes.Count != 0)
                    {
                        foreach (XmlNode sectionNode in sectionNodes)
                        {
                            string name = sectionNode["Name"].InnerText;
                            sectionsList.Add(name);

                        }
                        writeToLog("Global Section names read");
                    }
                    //---------------------------------------------------------------------------------------------------------------------------

                    //get all documents in the control xml
                    XmlNodeList documentNodes = controlXMl.SelectNodes("//pdbot:Docs//pdbot:Doc", nsmngr);

                    //get all document information
                    //get document content - Fields, Keys, paragraphkeywords, sections, copies and pagewatermarkings
                    foreach (XmlNode documentNode in documentNodes)
                    {
                       //get document template information
                        List<string> documentFieldsList = new List<string>();
                        string templateFormat = documentNode["TemplateFormat"].InnerText;
                        string repositoryTemplate = documentNode["RepositoryTemplate"].InnerText;
                        //---------------------------------------------------------------------------------------------------------------------------

                        //get document field names and value
                        //select Docs/Doc/DocContent/Fields
                        XmlNodeList fieldNodes = documentNode.SelectNodes("pdbot:DocContent//pdbot:Fields//pdbot:Field", nsmngr);
                        if (fieldNodes.Count != 0)
                        {
                            foreach (XmlNode fieldNode in fieldNodes)
                            {
                                string fieldName = fieldNode["FieldName"].InnerText;
                                string fieldNameValue = fieldNode["Value"].InnerText;

                                string fieldNameWithValue = fieldName + "|" + fieldNameValue;
                                documentFieldsList.Add(fieldNameWithValue);

                            }
                            writeToLog("Document archive fields read");
                        }
                        //---------------------------------------------------------------------------------------------------------------------------

                        //get document keywords and value
                        //select Docs/Doc/DocContent/Keys
                        documentKeyswordsList = new List<string>();
                        XmlNodeList docKeyNodes = documentNode.SelectNodes("pdbot:DocContent//pdbot:Keys//pdbot:Key", nsmngr);
                        if (docKeyNodes.Count != 0)
                        {
                            foreach (XmlNode docKeyNode in docKeyNodes)
                            {
                                string keyword = docKeyNode["Keyword"].InnerText;
                                string value = docKeyNode["Value"].InnerText;
                                string keywordWithValue = keyword + "|" + value;

                                documentKeyswordsList.Add(keywordWithValue);

                            }
                            writeToLog("Document keys read");
                        }
                        //---------------------------------------------------------------------------------------------------------------------------

                        //get document paragraphs and value
                        //select Docs/Doc/DocContent/ParagraphKeywords/Paragraph
                        List<string> paragraphKeywordsList = new List<string>();
                        XmlNodeList paragraphNodes = documentNode.SelectNodes("pdbot:DocContent//pdbot:ParagraphKeywords//pdbot:Paragraph", nsmngr);
                        if (paragraphNodes.Count != 0)
                        {
                            foreach (XmlNode paragraphNode in paragraphNodes)
                            {
                                string keyword = paragraphNode["Keyword"].InnerText;
                                string value = paragraphNode["Value"].InnerText;
                                string keywordWithValue = keyword + "|" + value;
                                paragraphKeywordsList.Add(keywordWithValue);

                            }
                            writeToLog("Document paragragh keys read");
                        }
                        //---------------------------------------------------------------------------------------------------------------------------

                        //get document sections
                        //select Docs/Doc/DocContent/Sections/Section
                        XmlNodeList docSectionNodes = documentNode.SelectNodes("pdbot:DocContent//pdbot:Sections//pdbot:Section", nsmngr);
                        if (docSectionNodes.Count != 0)
                        {
                            foreach (XmlNode docSectionNode in docSectionNodes)
                            {
                                string name = docSectionNode["Name"].InnerText;

                                if (!sectionsList.Contains(name))
                                {
                                    sectionsList.Add(name);
                                }

                            }
                            writeToLog("Document sections read");
                        }
                        //---------------------------------------------------------------------------------------------------------------------------

                        //get PageWatermarkings
                        //select Docs/Doc/PageWatermarkings/PageWatermarking
                        XmlNode hflPageWatermarkingsNodes = documentNode.SelectSingleNode("pdbot:PageWatermarkings//pdbot:PageWatermarking", nsmngr);
                        hflDocumentPath = hflPageWatermarkingsNodes["ResourceFile"].InnerText;

                        //select Docs/Doc/PageWatermarkings/PageWatermarking/Watermark
                        XmlNodeList pageWatermarkingsNodes = documentNode.SelectNodes("pdbot:PageWatermarkings//pdbot:PageWatermarking//pdbot:Watermark", nsmngr);

                        List<string> waterMarkings = new List<string>();
                        //get watermark values
                        if (pageWatermarkingsNodes.Count != 0)
                        {
                            foreach (XmlNode watermarkNode in pageWatermarkingsNodes)
                            {
                                string wmark = watermarkNode.InnerText;

                                waterMarkings.Add(wmark);
                            }
                            writeToLog("PageWatermarkings dokument variables read");
                        }
                        //---------------------------------------------------------------------------------------------------------------------------

                        //get PageInserts
                        //select Docs/Doc/PageInserts/Inserts
                        XmlNode PageInsertNodes = documentNode.SelectSingleNode("pdbot:PageInserts//pdbot:Inserts", nsmngr);
                        //---------------------------------------------------------------------------------------------------------------------------

                        //get copies information
                        //select Docs/Doc/Copies/Copy
                        List<string> copiesList = new List<string>();
                        XmlNodeList copyNodes = documentNode.SelectNodes("pdbot:Copies//pdbot:Copy", nsmngr);
                        if (copyNodes.Count != 0)
                        {
                            foreach (XmlNode copyNode in copyNodes)
                            {
                                string name = copyNode["Name"].InnerText;
                                string stampText = copyNode["StampText"].InnerText;
                                string flatten = copyNode["Flatten"].InnerText;
                                string outputFile = copyNode["OutputFile"].InnerText;

                                string copyValues = name + "|" + stampText + "|" + flatten + "|" + outputFile;
                                copiesList.Add(copyValues);

                            }
                            writeToLog("Copies document variables read.");
                        }
                        //---------------------------------------------------------------------------------------------------------------------------

                        //replace variables from word template with keywords and values
                        //loop through all the fields in the document and replace content with values from control xml:
                        //load word document template
                        try
                        {
                            //Read RepositoryTemplate
                            string keyword = null;
                            string value = null;
                            repositoryTemplate = repositoryTemplate.Replace("xml", "docx");
                            docTemplate = new Aspose.Words.Document(repositoryTemplate);
                            writeToLog("Document template " + docTemplate.OriginalFileName.ToString() + " loaded succesfully");
                            //--------------------------------------------------------------------------------------------------------------------------

                            if (docTemplate != null)
                            {
                                //Remove content controls/sections which will not be used
                                if (sectionsList.Count != 0)
                                {
                                    var ccntrls = docTemplate.GetChildNodes(NodeType.StructuredDocumentTag, true);
                                    foreach (var ccntrl in ccntrls)
                                    {

                                        var sdt = ccntrl as StructuredDocumentTag;
                                        var section = sdt.Title;
                                        if (!sectionsList.Contains(section))
                                        {
                                            sdt.Remove();
                                        }
                                    }
                                    writeToLog("Sections which will not be used in the document removed from template");
                                }
                                //--------------------------------------------------------------------------------------------------------------------------

                                //loop through all the fields in the document and replace content with values from control xml:
                                //replace word template variables/keywords with document values
                                if (documentKeyswordsList.Count != 0)
                                {
                                    foreach (var key in documentKeyswordsList)
                                    {
                                        //split keywords and value
                                        string[] keywordWithValues = key.Split('|');

                                        keyword = keywordWithValues[keywordWithValues.Length - 2];
                                        value = keywordWithValues[keywordWithValues.Length - 1];

                                        //loop through all the fields in the document and replace content with values from control xml:
                                        docTemplate.Range.Replace(keyword, value, false, false);
                                    }
                                    writeToLog("Document template variables replaced with document keywords and values");
                                    //---------------------------------------------------------------------------------------------------------------------------
                                 }

                                //replace word template variables/keywords with global document values
                                if (globalsKeywordsList.Count != 0)
                                {
                                    foreach (var key in globalsKeywordsList)
                                    {
                                        //split keywords and value
                                        string[] keywordWithValues = key.Split('|');

                                        keyword = keywordWithValues[keywordWithValues.Length - 2];
                                        value = keywordWithValues[keywordWithValues.Length - 1];

                                        docTemplate.Range.Replace(keyword, value, false, false);
                                    }
                                    writeToLog("Document template variables replaced with global keywords and values");
                                }
                                //---------------------------------------------------------------------------------------------------------------------------

                                //replace word template paragraphs variables/keywords with document paragraphs values from control xml
                                if (paragraphKeywordsList.Count != 0)
                                {
                                    foreach (var key in paragraphKeywordsList)
                                    {
                                        //split keywords and value
                                        string[] keywordWithValues = key.Split('|');

                                        keyword = keywordWithValues[keywordWithValues.Length - 2];
                                        value = keywordWithValues[keywordWithValues.Length - 1];

                                        //add a line break in paragraphs with line breaks
                                        if (value.Contains(@"\n"))
                                        {
                                            string[] paragraphLines = value.Split('\n');
                                            foreach (var line in paragraphLines)
                                            {
                                                string paragraphText = value.Replace(@"\n", ControlChar.LineBreak);
                                                docTemplate.Range.Replace(keyword, paragraphText, false, false);
                                            }
                                     }
                                        else
                                        {
                                            docTemplate.Range.Replace(keyword, value, false, false);
                                        }
                                    }
                                    writeToLog("Document template paragraph variables replaced with paragraoh keywords and values");
                                }
                                //---------------------------------------------------------------------------------------------------------------------------

                                //Table building!!!!------------------------------------

                               //NB! THIS WILL ONLY WORK WITH TEMPLATE THAT HAS ONLY ONE TABLES!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                                //select Docs/Doc/DocContent/table/Row
                                List<string> tableCellKeyList = new List<string>();
                                XmlNodeList rowNodes = documentNode.SelectNodes("pdbot:DocContent//pdbot:Table//pdbot:Row", nsmngr);
                                if (rowNodes.Count != 0)
                                {
                                    Aspose.Words.Tables.Table table = null;
                                    Aspose.Words.Tables.Row firstRow = null;
                                    foreach (XmlNode rowNode in rowNodes)
                                    {
                                        //select the table to insert rows. 1 represents table no.
                                         table = (Aspose.Words.Tables.Table)docTemplate.GetChild(NodeType.Table, 1, true);
                                        //clone the first table row
                                         firstRow = (Aspose.Words.Tables.Row)table.LastRow.Clone(true);
                                        XmlNodeList cellKeyNodes = rowNode.SelectNodes("pdbot:CellKey", nsmngr);

                                        foreach (XmlNode cellKeyNode in cellKeyNodes)
                                        {
                                            string cellKey = cellKeyNode["Key"].InnerText;
                                            string cellValue = cellKeyNode["Value"].InnerText;

                                            docTemplate.Range.Replace(cellKey, cellValue, false, false);
                                        }
                                        //Insert a new table row after the current row (template row):
                                        table.AppendChild(firstRow);
                                    }
                                    //Delete the last template table row after the table is created
                                    table.LastRow.Remove();

                                }
                                writeToLog("Tabel cell keys and keywords read from control xml and replaced in the document template");
                                //---------------------------------------------------------------------------------------------------------------------------

                                //produce document copies
                                foreach (var copy in copiesList)
                                {
                                    //split copy values
                                    string[] copyValues = copy.Split('|');

                                    string name = copyValues[copyValues.Length - 4];
                                    string stampText = copyValues[copyValues.Length - 3];
                                    string slatten = copyValues[copyValues.Length - 2];
                                    outputFile = copyValues[copyValues.Length - 1];

                                    //manage pagebreaks problem - remove pagebreak and insert sectionbreak - new page
                                    RemovePageBreaks(docTemplate);

                                    ////save document
                                    saveDoc(docTemplate, outputFile);

                                    ////watermark and stamp final document
                                    WaterMarkDocument(outputFile, hflDocumentPath, stampText, waterMarkings);

                                }
                                //---------------------------------------------------------------------------------------------------------------------------

                            }

                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Application failed with error " + e.Message + "." + e.StackTrace);
                            writeToLog("Error loading document template " + docTemplate.OriginalFileName.ToString() + "," + e.StackTrace);
                            Console.ReadKey();
                        }

                    }

                }
                catch (Exception e)
                {
                    Console.WriteLine("Application failed with error: " + e.Message + "." + e.StackTrace);
                    writeToLog("Error reading control xml " + e.StackTrace);
                    Console.ReadKey();
                }

                //save pdbot control xml in the same temp folder as the produced documents
                string outputfilename = outputFile.Remove(outputFile.Remove(outputFile.Length - 1).LastIndexOf('\\') + 1);
                outputfilename = outputfilename + "pdbot_control.xml";

                controlXMl.Save(outputfilename);
            }
            controlXMl = null;

            //stopwatch.Stop();
            //Console.WriteLine("Time used: " + stopwatch.Elapsed.Seconds + " Seconds");
            //Console.ReadKey();
            //---------------------------------------------------------------------------------------------------------------------------------------------
        }
示例#26
0
        static AsposePdfTextExtractor()
        {
            var licence = new License();

            licence.SetLicense("Aspose.Total.lic");
        }
示例#27
0
文件: Program.cs 项目: natav/MiscCode
        static void Main(string[] args)
        {
            try
            {
                Aspose.Pdf.License license = new Aspose.Pdf.License();
                // Set license
                license.SetLicense("Aspose.Pdf.lic");

                //Console.WriteLine("License set successfully.");

                Console.WriteLine("Type in the full path for pdf report you would like to convert:");

                // Load source PDF file
                //Document doc = new Document("D:\\Aspose\\Input\\Aspose_input.pdf");
                var pdfFile = Console.ReadLine().Trim();

                if (!FileExists(pdfFile))
                {
                    Console.WriteLine("File doesn't exist! Exiting...");
                    System.Threading.Thread.Sleep(5000);
                    Environment.Exit(0);
                }
                else if (Path.GetExtension(pdfFile).ToUpper() != ".PDF")
                {
                    Console.WriteLine("File isn't pdf! Exiting...");
                    System.Threading.Thread.Sleep(5000);
                    Environment.Exit(0);
                }


                Console.WriteLine($"{Environment.NewLine}Converting...{Environment.NewLine}");

                Document doc = new Document(pdfFile);

                // Instantiate HTML Save options object
                HtmlSaveOptions newOptions = new HtmlSaveOptions();
                newOptions.PartsEmbeddingMode             = HtmlSaveOptions.PartsEmbeddingModes.EmbedAllIntoHtml;
                newOptions.RemoveEmptyAreasOnTopAndBottom = true;
                newOptions.SplitIntoPages           = false;
                newOptions.HtmlMarkupGenerationMode = HtmlSaveOptions.HtmlMarkupGenerationModes.WriteAllHtml;
                newOptions.FixedLayout = true;

                // This is just optimization for IE and can be omitted
                newOptions.LettersPositioningMethod = HtmlSaveOptions.LettersPositioningMethods.UseEmUnitsAndCompensationOfRoundingErrorsInCss;
                newOptions.RasterImagesSavingMode   = HtmlSaveOptions.RasterImagesSavingModes.AsEmbeddedPartsOfPngPageBackground;
                newOptions.FontSavingMode           = HtmlSaveOptions.FontSavingModes.SaveInAllFormats;

                // Output file path
                string outHtmlFile = Path.Combine(Directory.GetCurrentDirectory(), "Converted_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".html");

                doc.Save(outHtmlFile, newOptions);

                Console.WriteLine($"PDF converted to HTML successfully:{Environment.NewLine} {outHtmlFile}");
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Read();
            }
        }
示例#28
0
        public void ProcessRequest(HttpContext context)
        {
            this.MyUtility.InitLog("Images");

            context.Response.Clear();

            string data = string.Empty, message = string.Empty;

            SysCode code = SysCode.A000;

            string session_key = string.Empty, file_id = string.Empty, file_full_path = string.Empty, year_and_month = string.Empty, user_id = string.Empty;

            int file_type = 0, file_seq = 0;

            string[] para_arry = null;

            List <IDataParameter> para = null;

            DataTable dt = null;

            string strSql = string.Empty;

            Aspose.Pdf.License license = new Aspose.Pdf.License();

            license.SetLicense("Aspose.Pdf.lic");
            try
            {
                #region 取得參數

                data = context.GetRequest("data").DecryptDES();

                if (String.IsNullOrEmpty(data))
                {
                    throw new Utility.ProcessException(string.Format("參數為空值"), ref code, SysCode.E004);
                }

                this.MyUtility.WriteLog(Mode.LogMode.DEBUG, context, string.Format("DATA.Parameter:{0}", data));

                #endregion

                para_arry = data.Split('|');

                if (!para_arry.Length.Equals(7))
                {
                    throw new Utility.ProcessException(string.Format("參數不足{0}/7", para_arry.Length), ref code, SysCode.E004);
                }

                file_id = para_arry[0];

                file_type = Convert.ToInt32(para_arry[1]);

                year_and_month = para_arry[2];

                session_key = para_arry[3];

                file_full_path = para_arry[4];

                file_seq = Convert.ToInt32(para_arry[5]);

                user_id = para_arry[6];

                bool exists = File.Exists(file_full_path);

                if (!exists && file_type < 10)
                {
                    throw new Utility.ProcessException(string.Format("調閱檔案不存在"), ref code, SysCode.E006);
                }

                if (!exists && file_type.Equals(11))
                {
                    DataRow[] dr = null;

                    strSql = this.MyUtility.Select.FILE_TABLE_NOT_IMAGE(year_and_month, file_id, ref para);

                    #region SQL Debug

                    this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, strSql);

                    this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, para.ToLog());

                    #endregion

                    dt = this.MyUtility.DBConn.GeneralSqlCmd.ExecuteToDataTable(strSql, para);

                    string pdf_file_path = string.Empty;

                    if (dt.Rows.Count > 0)
                    {
                        dr = dt.Select(string.Format("FILE_TYPE=1"));

                        if (dr != null && dr.Length > 0)
                        {
                            pdf_file_path = dr[0]["FILE_ROOT"].ToString().Trim().FilePathCombine(dr[0]["FILE_PATH"].ToString().Trim());
                        }
                    }
                    exists = File.Exists(pdf_file_path);

                    this.MyUtility.WriteLog(context, string.Format("PDF.Path:{0},{1}", pdf_file_path, exists));

                    if (!exists)
                    {
                        throw new Utility.ProcessException(string.Format("PDF不存在"), ref code, SysCode.E006);
                    }

                    #region PDF 切割
                    try
                    {
                        using (Document pdfDocument = new Document(pdf_file_path))
                        {
                            Aspose.Pdf.Devices.Resolution resolution = new Aspose.Pdf.Devices.Resolution(150);

                            Aspose.Pdf.Devices.JpegDevice jpegDeviceLarge = new Aspose.Pdf.Devices.JpegDevice(resolution);

                            if (file_seq <= 0 || file_seq > pdfDocument.Pages.Count)
                            {
                                this.MyUtility.WriteLog(Mode.LogMode.ERROR, context, string.Format("PDF.Pages.Count:{0},FILE_SEQ:{1}", pdfDocument.Pages.Count, file_seq));

                                throw new Utility.ProcessException(string.Format("查無影像檔及無法從PDF內拆檔"), ref code, SysCode.E005);
                            }
                            jpegDeviceLarge.Process(pdfDocument.Pages[file_seq], file_full_path);

                            if (!File.Exists(file_full_path))
                            {
                                throw new Utility.ProcessException(string.Format("頁次{0}拆檔失敗", file_seq), ref code, SysCode.E005);
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                        this.MyUtility.WriteLog(Mode.LogMode.ERROR, context, ex.ToString());

                        throw new Utility.ProcessException(ex.Message, ref code, SysCode.E005);
                    }
                    #endregion
                }
                this.MyUtility.DBLog(context, code, "Images", session_key, user_id, data);

                string file_ext = Path.GetExtension(file_full_path).Remove(0, 1);

                if (file_type < 10)
                {
                    this.MyUtility.ResponseFile(context, file_full_path, file_ext);
                }
                else
                {
                    this.MyUtility.DrawImage(context, file_full_path, file_ext);
                }
            }
            catch (System.Exception ex)
            {
                message = ex.Message;

                this.MyUtility.WriteLog(Mode.LogMode.ERROR, context, ex.ToString());

                code = !code.Equals(SysCode.A000) ? code : SysCode.E999;

                this.MyUtility.DBLog(context, code, "Images", session_key, user_id, !String.IsNullOrEmpty(data) ? string.Format("{0}\r\n{1}", data, ex.Message) : ex.Message);

                this.MyUtility.DrawMessage(context, ex.Message);

                this.MyUtility.SendEMail(context, "Images", session_key, code);
            }
            finally
            {
                license = null;

                dt = null;

                para = null;

                this.MyUtility.CloseConn();

                GC.Collect(); GC.WaitForPendingFinalizers();
            }
        }
示例#29
0
        public void ProcessRequest(HttpContext context)
        {
            this.MyUtility.InitLog("GetImageBase64");

            context.Response.Clear();
            context.Response.ContentType = "application/json";

            string json = string.Empty, data = string.Empty, message = string.Empty;

            SysCode code = SysCode.B000;

            XmlDocument xmlDoc = null;

            string xPath = string.Empty, strSql = string.Empty;

            List <IDataParameter> para = null;

            DataTable dt = null;

            string USERID = string.Empty;

            string year_and_month = string.Empty;

            string session_key = string.Empty, session_info = string.Empty;

            Aspose.Pdf.License license = new Aspose.Pdf.License();

            license.SetLicense("Aspose.Pdf.lic");

            IMAGE_BASE64_CLASS.IMAGE_BASE64_ITEM[] image_item_list = null;
            try
            {
                #region 取得參數

                data = context.GetRequest("data");

                if (String.IsNullOrEmpty(data))
                {
                    throw new Utility.ProcessException(string.Format("參數為空值"), ref code, SysCode.E004);
                }

                this.MyUtility.WriteLog(Mode.LogMode.DEBUG, context, string.Format("DATA.JSON:{0}", data));

                #endregion

                xmlDoc = JsonConvert.DeserializeXmlNode(data);

                XmlNode xmlNodeProcessInfo = xmlDoc.SelectSingleNode(xPath = string.Format("./CHANGINGTEC/PROCESS_INFO"));

                if (xmlNodeProcessInfo == null)
                {
                    throw new Utility.ProcessException(xPath, ref code, SysCode.E003);
                }

                USERID = xmlNodeProcessInfo.SelectSingleNode(string.Format("USERID"), ref code, false);

                session_key = xmlNodeProcessInfo.SelectSingleNode(string.Format("SESSION_KEY"), ref code, false);

                this.MyUtility.WriteLog(context, string.Format("SESSION_KEY:{0}", session_key));

                if (String.IsNullOrEmpty(session_key))
                {
                    year_and_month = xmlNodeProcessInfo.SelectSingleNode(string.Format("YM"), ref code);

                    this.MyUtility.CheckAndCreateTable(context, year_and_month, ref code);

                    string CHANNEL_CODE     = xmlNodeProcessInfo.SelectSingleNode(string.Format("CHANNEL_CODE"), ref code);
                    string TXN_TYPE         = xmlNodeProcessInfo.SelectSingleNode(string.Format("TXN_TYPE"), ref code);
                    string TXN_ID           = xmlNodeProcessInfo.SelectSingleNode(string.Format("TXN_ID"), ref code);
                    string REPORT_SERIAL_NO = xmlNodeProcessInfo.SelectSingleNode(string.Format("REPORT_SERIAL_NO"), ref code);
                    string GUID             = xmlNodeProcessInfo.SelectSingleNode(string.Format("GUID"), ref code);

                    this.MyUtility.DBLog(context, SysCode.B001, "GetImageBase64", string.Empty, USERID, session_info = string.Format("{0}_{1}_{2}_{3}_{4}_{5}", year_and_month, CHANNEL_CODE, TXN_TYPE, TXN_ID, REPORT_SERIAL_NO, GUID));

                    strSql = this.MyUtility.Select.FILE_TABLE(year_and_month, CHANNEL_CODE, TXN_TYPE, TXN_ID, REPORT_SERIAL_NO, GUID, ref para);

                    #region SQL Debug

                    this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, strSql);

                    this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, para.ToLog());

                    #endregion

                    dt = this.MyUtility.DBConn.GeneralSqlCmd.ExecuteToDataTable(strSql, para);

                    if (dt.Rows.Count.Equals(0))
                    {
                        year_and_month = year_and_month.GetPreviousYM();

                        this.MyUtility.CheckAndCreateTable(context, year_and_month, ref code);

                        strSql = this.MyUtility.Select.FILE_TABLE(year_and_month, CHANNEL_CODE, TXN_TYPE, TXN_ID, REPORT_SERIAL_NO, GUID, ref para);

                        #region SQL Debug

                        this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, strSql);

                        this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, para.ToLog());

                        #endregion

                        dt = this.MyUtility.DBConn.GeneralSqlCmd.ExecuteToDataTable(strSql, para);
                    }
                }
                else
                {
                    year_and_month = session_key.Split('-')[0];

                    this.MyUtility.CheckAndCreateTable(context, year_and_month, ref code);

                    this.MyUtility.DBLog(context, SysCode.B001, "GetImageBase64", string.Empty, USERID, session_info = string.Format("{0}_{1}", year_and_month, session_key));

                    strSql = this.MyUtility.Select.FILE_TABLE(year_and_month, session_key, ref para);

                    #region SQL Debug

                    this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, strSql);

                    this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, para.ToLog());

                    #endregion

                    dt = this.MyUtility.DBConn.GeneralSqlCmd.ExecuteToDataTable(strSql, para);
                }
                if (dt.Rows.Count.Equals(0))
                {
                    throw new Utility.ProcessException(string.Format("查無資料"), ref code, SysCode.E007);
                }

                this.MyUtility.DBLog(context, SysCode.A001, "GetImageBase64", session_key = dt.Rows[0]["SESSION_KEY"].ToString(), USERID, string.Empty);

                this.MyUtility.WriteLog(context, string.Format("SESSION_KEY:{0}", session_key));

                DataRow[] dr_pdf = dt.Select(string.Format("FILE_TYPE=1"));

                string pdf_file_full_path = string.Empty;

                bool pdf_exists = false;

                if (dr_pdf.Length > 0)
                {
                    string pdf_file_root = dr_pdf[0]["FILE_ROOT"].ToString();

                    string pdf_file_path = dr_pdf[0]["FILE_PATH"].ToString();

                    pdf_file_full_path = pdf_file_root.FilePathCombine(pdf_file_path);

                    pdf_exists = File.Exists(pdf_file_full_path);

                    this.MyUtility.WriteLog(context, string.Format("{0},{1}", pdf_file_full_path, pdf_exists));
                }
                DataRow[] dr_image = dt.Select(string.Format("FILE_TYPE=11"));

                this.MyUtility.WriteLog(context, string.Format("Image.Count:{0}", dr_image.Length));

                if (dr_image.Length.Equals(0))
                {
                    throw new Utility.ProcessException(string.Format("查無資料"), ref code, SysCode.E007);
                }

                image_item_list = new IMAGE_BASE64_CLASS.IMAGE_BASE64_ITEM[dr_image.Length];

                for (int i = 0; i < dr_image.Length; i++)
                {
                    session_key = dr_image[i]["SESSION_KEY"].ToString();

                    string file_id = dr_image[i]["FILE_ID"].ToString();

                    int file_seq = Convert.ToInt16(dr_image[i]["FILE_SEQ"].ToString());

                    string file_root = dr_image[i]["FILE_ROOT"].ToString();

                    string file_path = dr_image[i]["FILE_PATH"].ToString();

                    string file_full_path = file_root.FilePathCombine(file_path);

                    bool exists = File.Exists(file_full_path);

                    this.MyUtility.WriteLog(context, string.Format("{0},{1},{2}", file_seq, file_full_path, exists));

                    if (!exists && pdf_exists)
                    {
                        #region PDF 切割
                        try
                        {
                            using (Document pdfDocument = new Document(pdf_file_full_path))
                            {
                                Aspose.Pdf.Devices.Resolution resolution = new Aspose.Pdf.Devices.Resolution(150);

                                Aspose.Pdf.Devices.JpegDevice jpegDeviceLarge = new Aspose.Pdf.Devices.JpegDevice(resolution);

                                if (file_seq <= 0 || file_seq > pdfDocument.Pages.Count)
                                {
                                    this.MyUtility.WriteLog(Mode.LogMode.ERROR, context, string.Format("PDF.Pages.Count:{0},FILE_SEQ:{1}", pdfDocument.Pages.Count, file_seq));

                                    throw new Utility.ProcessException(string.Format("查無影像檔及無法從PDF內拆檔"), ref code, SysCode.E005);
                                }
                                jpegDeviceLarge.Process(pdfDocument.Pages[file_seq], file_full_path);

                                if (!File.Exists(file_full_path))
                                {
                                    throw new Utility.ProcessException(string.Format("頁次{0}拆檔失敗", file_seq), ref code, SysCode.E005);
                                }
                            }
                        }
                        catch (System.Exception ex)
                        {
                            this.MyUtility.WriteLog(Mode.LogMode.ERROR, context, ex.ToString());

                            throw new Utility.ProcessException(ex.Message, ref code, SysCode.E005);
                        }
                        #endregion
                    }
                    if (!File.Exists(file_full_path))
                    {
                        throw new Utility.ProcessException(string.Format("頁次{0}圖檔不存在", file_seq), ref code, SysCode.E001);
                    }

                    image_item_list[i] = new IMAGE_BASE64_CLASS.IMAGE_BASE64_ITEM()
                    {
                        FILE_ID = file_id, BODY = file_full_path.FileSerialize()
                    };
                }
                this.MyUtility.DBLog(context, SysCode.B000, "GetImageBase64", session_key, USERID, session_info);
            }
            catch (System.Exception ex)
            {
                message = ex.Message;

                this.MyUtility.WriteLog(Mode.LogMode.ERROR, context, ex.ToString());

                code = !code.Equals(SysCode.B000) ? code : SysCode.E999;

                this.MyUtility.DBLog(context, code, "GetImageBase64", session_key, USERID, ex.Message);

                this.MyUtility.SendEMail(context, "GetImageBase64", session_key, code);
            }
            finally
            {
                json = JsonConvert.SerializeObject(new IMAGE_BASE64_RESPOSE()
                {
                    CHANGINGTEC = new IMAGE_BASE64_SYSTEM_CLASS()
                    {
                        SYSTEM = new IMAGE_BASE64_SYSTEM_INFO_CLASS()
                        {
                            //CODE = code.Equals(SysCode.B000) ? SysCode.A000.ToString() : code.Equals(SysCode.E007) ? SysCode.A003.ToString() : code.ToString(),
                            CODE      = code.Equals(SysCode.B000) ? SysCode.A000.ToString() : code.ToString(),
                            MESSAGE   = message.EncryptBase64(),
                            CASE_INFO = new IMAGE_BASE64_CLASS()
                            {
                                JPG_ITEM = image_item_list
                            }
                        }
                    }
                });
                dt = null;

                license = null;

                xmlDoc = null;

                para = null;

                this.MyUtility.CloseConn();

                xmlDoc = null;

                GC.Collect(); GC.WaitForPendingFinalizers();

                context.Response.Write(json);
                context.Response.End();
            }
        }
        /// <summary>
        ///
        /// </summary>
        private void StartBATCH_CIF()
        {
            Form1.BATCH_CaseIDTimerFlag = true;

            Utility utility = null;

            string strSql = string.Empty;

            List <IDataParameter> para = null;

            DataTable dt = null;

            //todo 確認是否需要先複制再合檔?
            //string file_temp_dir_path = Path.Combine(ConfigPath.TempDirPath, Guid.NewGuid().ToString());

            try
            {
                utility = new Utility();

                this.InitLog("BATCH_CIF");

                if (utility.XDocSetting == null)
                {
                    this.WriteLog(Mode.LogMode.ERROR, string.Format("沒有設定檔"));

                    return;
                }
                //string last_working_time = (string)utility.XDocSetting.Root.Descendants("Timer").Where(x => (string)x.Element("name") == "Batch").FirstOrDefault().Element("lastWorkingTime");

                //bool check_working = String.IsNullOrEmpty(last_working_time);

                //if (!check_working)
                //{
                //    check_working = !DateTime.Parse(last_working_time).ToString("yyyyMMdd").Equals(DateTime.Now.AddSeconds(this.BATCH_CaseIDTimer_Interval / 1000).ToString("yyyyMMdd"));
                //}
                //if (check_working)
                //{
                //    string startTime = (string)utility.XDocSetting.Root.Descendants("Timer").Where(x => (string)x.Element("name") == "Batch").FirstOrDefault().Element("start");

                //    if (String.IsNullOrEmpty(startTime) || startTime.Length != 4) throw new Exception(string.Format("每日固定執行時間設定錯誤"));

                //    DateTime working_time = DateTime.Parse(string.Format("{0} {1}:{2}:00", DateTime.Now.ToString("yyyy/MM/dd"), startTime.Substring(0, 2), startTime.Substring(2, 2)));

                //    this.WriteLog(Mode.LogMode.INFO, string.Format("預計開始執行時間:{0}", working_time.ToString("yyyy/MM/dd HH:mm:ss")));

                //    TimeSpan ts = DateTime.Now - working_time;

                //    check_working = ts.TotalSeconds >= 0 && ts.TotalSeconds <= (this.BATCH_CaseIDTimer_Interval / 1000);

                //    this.WriteLog(Mode.LogMode.INFO, string.Format("比對時間結果:{0},{1}", check_working ? "準備開始" : "時間未到", ts.TotalSeconds.ToString()));
                //}
                //if (!check_working) return;

                DateTime start_date = DateTime.Now.AddDays(-1);

                this.WriteLog(Mode.LogMode.INFO, string.Format("準備執行 {0} 的作業", start_date.ToString("yyyy/MM/dd")));


                strSql = utility.Select.BATCH_CIF_INFO(start_date.ToString("yyyy/MM/dd 00:00:00"), start_date.ToString("yyyy/MM/dd 23:59:59"), start_date.ToString("yyyyMM"), ref para);

                #region SQL Debug

                this.WriteLog(Log.Mode.LogMode.DEBUG, strSql);

                this.WriteLog(Log.Mode.LogMode.DEBUG, para.ToLog());

                #endregion

                dt = utility.DBConn.GeneralSqlCmd.ExecuteToDataTable(strSql, para);

                this.WriteLog(Mode.LogMode.INFO, string.Format("共有{0}筆資料", dt.Rows.Count));

                if (dt.Rows.Count.Equals(0))
                {
                    this.WriteLastWorkingTime(utility); return;
                }
                string message = string.Empty;

                var query = from batch in dt.AsEnumerable()
                            select new
                {
                    CREATE_DATETIME      = batch.Field <DateTime>("CREATE_DATETIME"),
                    SESSION_KEY          = batch.Field <string>("SESSION_KEY"),
                    TXN_DATE             = batch.Field <DateTime>("TXN_DATE"),
                    TXN_ACCOUNT          = batch.Field <string>("TXN_ACCOUNT"),
                    BRANCH_ID            = batch.Field <string>("BRANCH_ID"),
                    FILE_ID              = batch.Field <string>("FILE_ID"),
                    FILE_CREATE_DATETIME = batch.Field <DateTime>("CREATE_DATETIME"),
                    FILE_SEQ             = batch.Field <Int16>("FILE_SEQ"),
                    FILE_ROOT            = batch.Field <string>("FILE_ROOT"),
                    FILE_PATH            = batch.Field <string>("FILE_PATH"),
                    PDF            = batch.Field <string>("PDF"),
                    FILE_TYPE      = batch.Field <Int16>("FILE_TYPE"),
                    T_MNEMONIC     = batch.Field <string>("T_MNEMONIC"),
                    T_EMAIL_SIGN_1 = batch.Field <string>("T_EMAIL_SIGN_1"),
                    T_EMAIL_1      = batch.Field <string>("T_EMAIL_1")
                };

                var queryG = query.GroupBy(o => o.T_MNEMONIC);

                Aspose.Pdf.License licenseWordsTxt = new Aspose.Pdf.License();
                licenseWordsTxt.SetLicense("Aspose.Pdf.lic");

                //if (!Directory.Exists(file_temp_dir_path)) Directory.CreateDirectory(file_temp_dir_path);

                string txt_file_path = Path.Combine(ConfigPath.FtpDirPath, string.Format("{0}.txt", start_date.ToString("yyyyMMdd")));

                txt_file_path.DeleteSigleFile();

                StreamWriter streamWriter = new StreamWriter(txt_file_path);

                foreach (var item in queryG)
                {
                    this.WriteLog(Log.Mode.LogMode.INFO, string.Format("準備產生{0}", item.Key));

                    Document doc = new Document();

                    string pdf_file_path = Path.Combine(ConfigPath.FtpDirPath, string.Format("{0}_{1}_001.pdf", start_date.ToString("yyyyMMdd"), item.Key));

                    string content = string.Empty;
                    string cif_ID  = string.Empty;

                    //if (!File.Exists(pdf_file_path))
                    {
                        long pdfFileSize        = 0;
                        bool isPDFSizeTooLength = false;
                        int  fileNameCount      = 1;

                        foreach (var batch in item)
                        {
                            try
                            {
                                utility.DBLog(SysCode.A010, "Batch", batch.T_MNEMONIC, string.Format("開始產生PDF:{0}", Path.GetFileNameWithoutExtension(pdf_file_path)));

                                string file_root = batch.FILE_ROOT;

                                string file_path = batch.FILE_PATH;

                                string file_full_path = file_root.FilePathCombine(file_path);

                                bool exists = File.Exists(file_full_path);

                                if (!exists)
                                {
                                    this.WriteLog(Log.Mode.LogMode.ERROR, message = string.Format("SESSION_KEY:{0},CIF_ID:{1},FILE_ID:{2}::檔案不存在({3})", batch.SESSION_KEY, batch.T_MNEMONIC, batch.FILE_ID, file_full_path));
                                    continue;
                                }

                                switch (batch.T_MNEMONIC.Length)
                                {
                                case 9:
                                case 11:
                                    cif_ID = batch.T_MNEMONIC.Substring(0, batch.T_MNEMONIC.Length - 2);
                                    break;

                                default:
                                    cif_ID = batch.T_MNEMONIC;
                                    break;
                                }
                                // Load the source image file to Stream object
                                FileStream fs = new FileStream(file_full_path, FileMode.Open, FileAccess.Read);

                                pdfFileSize += fs.Length;

                                byte[] tmpBytes = new byte[fs.Length];
                                fs.Read(tmpBytes, 0, int.Parse(fs.Length.ToString()));

                                MemoryStream mystream = new MemoryStream(tmpBytes);

                                // Instantiate BitMap object with loaded image stream
                                Bitmap b = new Bitmap(mystream);

                                // Add a page to pages collection of document
                                Page page = doc.Pages.Add();

                                // Set margins so image will fit, etc.
                                page.PageInfo.Margin.Bottom = 0;
                                page.PageInfo.Margin.Top    = 0;
                                page.PageInfo.Margin.Left   = 0;
                                page.PageInfo.Margin.Right  = 0;

                                page.CropBox = new Aspose.Pdf.Rectangle(0, 0, b.Width, b.Height);
                                // Create an image object
                                Aspose.Pdf.Image image1 = new Aspose.Pdf.Image();
                                // Add the image into paragraphs collection of the section
                                page.Paragraphs.Add(image1);
                                // Set the image file stream
                                image1.ImageStream = mystream;

                                image1.ImageScale = 0.95F;

                                //大於9M的要先存檔
                                if (pdfFileSize > 9437184)
                                {
                                    pdf_file_path = Path.Combine(ConfigPath.FtpDirPath, string.Format("{0}_{1}_{2}.pdf", start_date.ToString("yyyyMMdd"), item.Key, fileNameCount.ToString().PadLeft(3, '0')));

                                    this.WriteLog(Log.Mode.LogMode.DEBUG, string.Format("pdfFileSize:{0}、pdf_file_path:{1}", pdfFileSize, pdf_file_path));

                                    content = Path.GetFileNameWithoutExtension(pdf_file_path) + ":" + cif_ID + ":" + batch.T_EMAIL_1 + ":" + batch.TXN_DATE.ToString("yyyyMMdd");

                                    pdf_file_path.DeleteSigleFile();

                                    doc.Encrypt("23113343", "23113343", 0, CryptoAlgorithm.AESx128);
                                    doc.Save(pdf_file_path);
                                    mystream.Close();
                                    doc.Pages.Clear();
                                    doc.Dispose();
                                    doc = null;

                                    doc = new Document();

                                    streamWriter.WriteLine(content);

                                    fileNameCount     += 1;
                                    pdfFileSize        = 0;
                                    isPDFSizeTooLength = true;
                                }
                                else
                                {
                                    isPDFSizeTooLength = false;

                                    content = Path.GetFileNameWithoutExtension(pdf_file_path) + ":" + cif_ID + ":" + batch.T_EMAIL_1 + ":" + batch.TXN_DATE.ToString("yyyyMMdd");
                                }
                            }
                            catch (System.Exception ex)
                            {
                                this.WriteLog(Log.Mode.LogMode.ERROR, ex.ToString());

                                utility.DBLog(SysCode.E013, "Batch", batch.T_MNEMONIC, string.Format("{0}::{1}", Path.GetFileNameWithoutExtension(pdf_file_path), ex.Message));
                            }
                        }

                        if (!isPDFSizeTooLength)
                        {
                            pdf_file_path = Path.Combine(ConfigPath.FtpDirPath, string.Format("{0}_{1}_{2}.pdf", start_date.ToString("yyyyMMdd"), item.Key, fileNameCount.ToString().PadLeft(3, '0')));

                            pdf_file_path.DeleteSigleFile();

                            doc.Encrypt("23113343", "23113343", 0, CryptoAlgorithm.AESx128);
                            doc.Save(pdf_file_path);
                            doc.Dispose();

                            streamWriter.WriteLine(content);
                        }
                    }
                    //else this.WriteLog(Log.Mode.LogMode.INFO, string.Format("已存在於準備上傳,將略過 ({0})", pdf_file_path));
                }
                streamWriter.Close();

                this.WriteLastWorkingTime(utility);
            }
            catch (System.Exception ex)
            {
                this.WriteLog(Log.Mode.LogMode.ERROR, ex.ToString());

                this.WriteLog(Mode.LogMode.INFO, string.Format("將於{0}秒後重試", this.BATCH_CaseIDTimer.Interval / 1000));
            }
            finally
            {
                if (utility != null)
                {
                    utility.CloseConn();

                    utility = null;
                }
                dt = null;

                para = null;

                GC.Collect(); GC.WaitForPendingFinalizers();

                Form1.BATCH_CaseIDTimerFlag = false;
            }
        }