Example #1
0
        private void ExportAsImage(string strFile, string strExportPath)
        {
            if (!Directory.Exists(strExportPath))
            {
                Directory.CreateDirectory(strExportPath);
            }
            Acrobat.AcroPDDoc pdf = new AcroPDDoc();
            pdf.Open(strFile);

            int pageCount = Convert.ToInt32(txtPage.Text);
            int count     = pdf.GetNumPages();

            for (int i = 0; i < count; i++)
            {
                if (i == pageCount)
                {
                    break;
                }
                listMsg.Items.Add($"正在导出第{i + 1}页(共{count}页)");
                listMsg.TopIndex = listMsg.Items.Count - 1;
                int zoom = 1;
                while (true)
                {
                    try
                    {
                        CAcroPDPage page      = (CAcroPDPage)pdf.AcquirePage(i);
                        CAcroRect   pdfRect   = (Acrobat.CAcroRect)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.Rect", "");
                        CAcroPoint  pdfPoint  = (Acrobat.CAcroPoint)page.GetSize();
                        int         imgWidth  = (int)((double)pdfPoint.x * zoom);
                        int         imgHeight = (int)((double)pdfPoint.y * zoom);

                        //设置裁剪矩形的大小为当前页的大小
                        pdfRect.Left   = 0;
                        pdfRect.right  = (short)imgWidth;
                        pdfRect.Top    = 0;
                        pdfRect.bottom = (short)imgHeight;


                        page.CopyToClipboard(pdfRect, 0, 0, (short)(100 * zoom));
                        Object obj = Clipboard.GetData(DataFormats.Bitmap);
                        using (Bitmap bitmap = (Bitmap)obj)
                        {
                            SavePicture(bitmap, strExportPath, Path.GetFileNameWithoutExtension(strFile), (i + 1).ToString());
                        }
                    }
                    catch (Exception e)
                    {
                        continue;
                    }

                    break;
                }
            }
        }
Example #2
0
        private string GetTextInPdf(AcroPDDoc pdDoc)
        {
            AcroPDPage page;
            int        TotalNumberOfPages = pdDoc.GetNumPages();
            string     pageText           = "";

            for (int i = 0; i < TotalNumberOfPages; i++)
            {
                page = (AcroPDPage)pdDoc.AcquirePage(i);
                object        jso, jsNumWords, jsWord;
                List <string> words = new List <string>();
                try
                {
                    jso = pdDoc.GetJSObject();
                    if (jso != null)
                    {
                        object[] args = new object[] { i };
                        jsNumWords = jso.GetType().InvokeMember("getPageNumWords", BindingFlags.InvokeMethod, null, jso, args, null);
                        int numWords = Int32.Parse(jsNumWords.ToString());
                        for (int j = 0; j <= numWords; j++)
                        {
                            object[] argsj = new object[] { i, j, false };
                            jsWord = jso.GetType().InvokeMember("getPageNthWord", BindingFlags.InvokeMethod, null, jso, argsj, null);
                            words.Add((string)jsWord);
                        }
                    }
                    foreach (string word in words)
                    {
                        pageText += word;
                    }
                }
                catch
                {
                }
            }
            return(pageText);
        }
        private void createCombinedPdf_noFoldouts(
            IOrderedEnumerable<CockleFilePdf> files_no_foldouts,
            TypeOfCombinedPdf typeOfCombinedPdf,
            bool centerPdf = false)
        {
            CAcroApp app = new AcroApp();           // Acrobat
            CAcroPDDoc doc = new AcroPDDoc();       // First document
            CAcroPDDoc docToAdd = new AcroPDDoc();  // Next documents

            try
            {
                int numPages = 0, numPagesToAdd = 0;
                foreach (var f in files_no_foldouts)
                {
                    if (f.Rank == 0) // both 0
                    {
                        doc.Open(f.FullName);
                        numPages = doc.GetNumPages();
                    }
                    else if (f.Rank != 0 && numPages == 0)
                    {
                        doc.Open(f.FullName);
                        numPages = doc.GetNumPages();
                    }
                    else
                    {
                        if (!docToAdd.Open(f.FullName)) { break; }
                        numPagesToAdd = docToAdd.GetNumPages();
                        if (!doc.InsertPages(numPages - 1, docToAdd, 0, numPagesToAdd, 0)) { break; }
                        if (!docToAdd.Close()) { break; }
                        numPages = doc.GetNumPages();
                    }
                }
                doc.Save(1, CombinedPdfFilename);
                doc.Close();
                // use reflection to center the pdf
                if (centerPdf)
                {
                    var opened = doc.Open(CombinedPdfFilename);
                    if (opened)
                    {
                        object js_object = doc.GetJSObject();
                        Type js_type = js_object.GetType();
                        object[] js_param = { };
                        string script_name = string.Empty;
                        int? cover_length = null;
                        if (typeOfCombinedPdf == TypeOfCombinedPdf.Appendix
                            && files_no_foldouts.All(x => x.CoverLength == null))
                        {
                            script_name = Models.Utilities.AcrobatJS.Javascripts
                                [Models.Utilities.LocalJavascripts.center_letter_no_cover];
                        }
                        else if (files_no_foldouts.All(x => x.CoverLength == null))
                        {
                            script_name = Models.Utilities.AcrobatJS.Javascripts
                                [Models.Utilities.LocalJavascripts.center_letter_no_cover];
                        }
                        else
                        {
                            cover_length = files_no_foldouts.Where(x => x.FileType == SourceFileTypeEnum.Cover).FirstOrDefault().CoverLength;
                            switch (cover_length)
                            {
                                case 48:
                                default:
                                    script_name = Models.Utilities.AcrobatJS.Javascripts
                                        [Models.Utilities.LocalJavascripts.center_letter_48pica];
                                    break;
                                case 49:
                                    script_name = Models.Utilities.AcrobatJS.Javascripts
                                        [Models.Utilities.LocalJavascripts.center_letter_49pica];
                                    break;
                                case 50:
                                    script_name = Models.Utilities.AcrobatJS.Javascripts
                                        [Models.Utilities.LocalJavascripts.center_letter_50pica];
                                    break;
                                case 51:
                                    script_name = Models.Utilities.AcrobatJS.Javascripts
                                        [Models.Utilities.LocalJavascripts.center_letter_51pica];
                                    break;
                            }
                        }

                        js_type.InvokeMember(script_name,
                            System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance,
                            null, js_object, js_param);
                        // test that the file exists
                        doc.Save(1, CombinedPdfFilename);
                    }
                    else
                    {
                        throw new Exception("Could not center pdf.");
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            finally
            {
                doc.Close();
                app.CloseAllDocs();
                app.Exit();

                doc = null;
                docToAdd = null;
                app = null;

                GC.Collect();
            }
        }
        private bool insertFoldoutsIntoOriginals(CockleFilePdf parent, CockleFilePdf foldout)
        {
            bool insertSuccessful = true;
            if (parent.PageRange == null || foldout.PageRange == null) { return false; }

            CAcroApp app = new AcroApp();           // Acrobat
            CAcroPDDoc doc = new AcroPDDoc();       // First document
            CAcroPDDoc docToAdd = new AcroPDDoc();  // Next documents

            try
            {

                doc.Open(parent.FullName);
                docToAdd.Open(foldout.FullName);

                int numPagesParent = doc.GetNumPages();
                int numPagesFoldout = docToAdd.GetNumPages();

                // ROTATE IF RECOMMENDED
                //if (foldout.PageRange.Rotation == PageRangePdf.ROTATE_ENUM.CLOCKWISE)
                //{
                //    // reflection to access acrobat javascript
                //    object jso = docToAdd.GetJSObject();
                //    Type type = jso.GetType();
                //    object[] getRotatePageParams = { 0, numPagesFoldout - 1, 90 };
                //    object rotatePage = type.InvokeMember("setPageRotations",
                //        System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance,
                //        null, jso, getRotatePageParams);
                //}
                //else if (foldout.PageRange.Rotation == PageRangePdf.ROTATE_ENUM.COUNTERCLOCKWISE)
                //{
                //    // reflection to access acrobat javascript
                //    object jso = docToAdd.GetJSObject();
                //    Type type = jso.GetType();
                //    object[] getRotatePageParams = { 0, numPagesFoldout - 1, 270 };
                //    object rotatePage = type.InvokeMember("setPageRotations",
                //        System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance,
                //        null, jso, getRotatePageParams);
                //}
                //else
                //{
                //    // do nothing
                //}

                if (parent.PageRange.TotalPages == foldout.PageRange.TotalPages)
                {
                    // check 1: phantom file was never updated    
                    if (parent.PageRange.FirstPage == 1 && foldout.PageRange.FirstPage != 1)
                    {
                        // if true, simply swap, page for page
                        doc.ReplacePages(0, docToAdd, 0, parent.PageRange.TotalPages, 0);
                    }
                    // check 2: all page numbers match, just do full replacement
                    else if (parent.PageRange.FirstPage == foldout.PageRange.FirstPage &&
                        parent.PageRange.LastPage == foldout.PageRange.LastPage)
                    {
                        doc.ReplacePages(0, docToAdd, 0, parent.PageRange.TotalPages, 0);
                    }
                    // not sure what else to check for here
                }
                else
                {
                    int InsertionPoint = (int)foldout.PageRange.FirstPage - (int)parent.PageRange.FirstPage;

                    if (!doc.DeletePages(InsertionPoint, InsertionPoint + numPagesFoldout - 1))
                    {
                        insertSuccessful = false;
                    }
                    if (!doc.InsertPages(InsertionPoint - 1, docToAdd, 0, numPagesFoldout, 0))
                    {
                        insertSuccessful = false;
                    }
                }
                docToAdd.Close();
                doc.Save(1, parent.FullName);
                //System.IO.Path.Combine(System.IO.Path.GetDirectoryName(parent.FullName), "testfile.pdf"));

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            finally
            {
                doc.Close();
                app.CloseAllDocs();
                app.Exit();

                doc = null;
                docToAdd = null;
                app = null;

                GC.Collect();
            }
            return insertSuccessful;
        }
        public string GetFetchLatestReport(FetchLatestReport Data)
        {
            try
            {
                // int Reporttype = 8; pageText = "6010001"; string shortpath = string.Empty; string Fromdate = string.Empty; string Todate = string.Empty; string[] datecheckarr;
                int   Reporttype = Data.ReportName; pageText = Data.CustomerAccount; string shortpath = string.Empty; string Fromdate = string.Empty; string Todate = string.Empty; string[] datecheckarr;
                Int64 schemeid = 0;
                List <SchemeMasterdata> dataList = new List <SchemeMasterdata>();
                switch (Reporttype)
                {
                case 1:
                    Reportname = "BANK BOOK Client" + ".pdf";
                    break;

                case 2:
                    Reportname = "Current Portfolio Clientwise" + ".pdf";
                    break;

                case 3:
                    Reportname = "Performance Appraisal Clientwise" + ".pdf";
                    break;

                case 4:
                    Reportname = "Portfolio Appraisal Clientwise" + ".pdf";
                    break;

                case 5:
                    Reportname = "Portfolio Fact Sheet" + ".pdf";
                    break;

                case 6:
                    Reportname = "Statement of Capital Gain clientwise" + ".pdf";
                    break;

                case 7:
                    Reportname = "Statement of Dividend Clientwise" + ".pdf";
                    break;

                case 8:
                    Reportname = "Statement of Expenses Clientwise" + ".pdf";
                    break;

                case 9:
                    Reportname = "Transaction Statement Cleintwise" + ".pdf";
                    break;
                }

                string SourceDirectorypath = ""; string[] files; string pdffilename = ""; string DestinationDirectorypath = "";
                SourceDirectorypath      = HttpContext.Current.Server.MapPath("//FAMSIN//");
                DestinationDirectorypath = HttpContext.Current.Server.MapPath("//FAMSOUT//");
                files = Directory.GetFiles(SourceDirectorypath, "*.pdf");
                if (files.Length > 0)
                {
                    foreach (string file in files)
                    {
                        pdffilename = Path.GetFileName(file);
                        if (pdffilename == Reportname && pageText != "")
                        {
                            FORM_NAME = SourceDirectorypath + Reportname;
                            CAcroApp acroApp = new AcroAppClass();
                            acroApp.Show();
                            string datewisedata = string.Empty; string pagefromdate = ""; string pagelastindex = "";
                            string Pagescheme = string.Empty; string DatabasePagescheme = string.Empty;
                            Dictionary <Int64, string> Schemelist = new Dictionary <Int64, string>();
                            FAMSEntities context = new FAMSEntities();
                            try
                            {
                                var results = context.MultipleResults("[dbo].[BindSchememaster]").With <SchemeMasterdata>()
                                              .Execute("@Querytype", "@Cust_code", "BindScheme", pageText);

                                foreach (var schemedatab in results)
                                {
                                    dataList = schemedatab.Cast <SchemeMasterdata>().ToList();
                                    if (dataList.Count > 0)
                                    {
                                        for (int i = 0; i < dataList.Count; i++)
                                        {
                                            Schemelist.Add(Convert.ToInt32(dataList[i].SMDID), Convert.ToString(dataList[i].SchemaNumber.ToString()));
                                        }
                                    }
                                }

                                //   break;
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }

                            CAcroAVDoc avDoc = new AcroAVDocClass();
                            if (!avDoc.Open(FORM_NAME, ""))
                            {
                                //string szMsg = "Cannot open" + FORM_NAME + ".\n";
                                //Console.WriteLine(szMsg);
                                //return;
                            }
                            AcroPDDoc  doc = (AcroPDDoc)avDoc.GetPDDoc();
                            AcroPDPage page; Object newDoc = null; ArrayList kk = new ArrayList();
                            int        pages = doc.GetNumPages();
                            object     jso, jsNumWords, jsWord;
                            jso = doc.GetJSObject();
                            for (int i = 0; i < pages; i++)
                            {
                                page = (AcroPDPage)doc.AcquirePage(i);
                                List <string> words = new List <string>();
                                try
                                {
                                    if (jso != null)
                                    {
                                        object[] argsy = new object[] { i };
                                        jsNumWords = jso.GetType().InvokeMember("getPageNumWords",
                                                                                System.Reflection.BindingFlags.InvokeMethod, null, jso, argsy, null);
                                        int numWords = Int32.Parse(jsNumWords.ToString());
                                        for (int j = 0; j <= numWords; j++)
                                        {
                                            object[] argsj = new object[] { i, j, false };
                                            jsWord = jso.GetType().InvokeMember("getPageNthWord", System.Reflection.BindingFlags.InvokeMethod, null, jso, argsj, null);
                                            words.Add((string)jsWord);
                                        }
                                    }
                                    for (int x = 0; x < words.Count; x++)
                                    {
                                        int result = String.Compare(words[x].ToString().Trim(), pageText.Trim());
                                        if (result == 0)
                                        {
                                            newDoc         = null;
                                            pagelastindex += i + ",";
                                            if (Reporttype == 1 || Reporttype == 6 || Reporttype == 7 || Reporttype == 8 || Reporttype == 9)
                                            {
                                                if (string.IsNullOrEmpty(datewisedata))
                                                {
                                                    pagefromdate = "From";
                                                    for (int m = x; m < words.Count; m++)
                                                    {
                                                        int datecheck = String.Compare(words[m].ToString().Trim(), pagefromdate.Trim());
                                                        if (datecheck == 0)
                                                        {
                                                            for (int y = m + 1; y < m + 8; y++)
                                                            {
                                                                datewisedata += words[y].ToString();
                                                            }
                                                            datecheckarr = datewisedata.Replace("\n", "").Replace("\r", "").Trim().Split('T');
                                                            Fromdate     = datecheckarr[0].ToString().Trim();
                                                            Todate       = datecheckarr[1].ToString().Replace("o", "").Trim();
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                            else if (Reporttype == 2)
                                            {
                                                if (string.IsNullOrEmpty(datewisedata))
                                                {
                                                    pagefromdate = "Report";
                                                    for (int m = x; m < words.Count; m++)
                                                    {
                                                        int datecheck = String.Compare(words[m].ToString().Trim(), pagefromdate.Trim());
                                                        if (datecheck == 0)
                                                        {
                                                            for (int y = m + 3; y < m + 6; y++)
                                                            {
                                                                datewisedata += words[y].ToString();
                                                            }
                                                            Fromdate = datewisedata.Replace("\n", "").Replace("\r", "").Trim();
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                            else if (Reporttype == 3 || Reporttype == 4)
                                            {
                                                if (string.IsNullOrEmpty(datewisedata))
                                                {
                                                    pagefromdate = "As";
                                                    for (int m = x; m < words.Count; m++)
                                                    {
                                                        int datecheck = String.Compare(words[m].ToString().Trim(), pagefromdate.Trim());
                                                        if (datecheck == 0)
                                                        {
                                                            for (int y = m + 2; y < m + 5; y++)
                                                            {
                                                                datewisedata += words[y].ToString();
                                                            }
                                                            Fromdate = datewisedata.Replace("\n", "").Replace("\r", "").Trim();
                                                            break;
                                                        }
                                                    }
                                                }
                                            }

                                            else if (Reporttype == 5)
                                            {
                                                if (string.IsNullOrEmpty(datewisedata))
                                                {
                                                    pagefromdate = "As";
                                                    for (int m = 0; m < words.Count; m++)
                                                    {
                                                        int datecheck = String.Compare(words[m].ToString().Trim(), pagefromdate.Trim());
                                                        if (datecheck == 0)
                                                        {
                                                            for (int y = m + 2; y < m + 5; y++)
                                                            {
                                                                datewisedata += words[y].ToString();
                                                            }
                                                            Fromdate = datewisedata.Replace("\n", "").Replace("\r", "").Trim();
                                                            break;
                                                        }
                                                    }
                                                }
                                            }

                                            //DMSNEWEntities context = new DMSNEWEntities();
                                            //Dictionary<Int64, string> Partnerid = new Dictionary<Int64, string>();
                                            //Partnerid = context.DMS_Partner().AsEnumerable().Select(x => new { Partid = x.PartnerId, PartCode = x.PartnerCode }).Distinct().ToDictionary(o => o.Partid, o => o.PartCode);
                                            if (string.IsNullOrEmpty(Pagescheme))
                                            {
                                                for (int m = 0; m < words.Count; m++)
                                                {
                                                    if (Schemelist.Count > 0)
                                                    {
                                                        for (int count = 0; count < Schemelist.Count; count++)
                                                        {
                                                            var element = Schemelist.ElementAt(count);
                                                            var Key     = element.Key;
                                                            var Value   = element.Value;
                                                            DatabasePagescheme = Value;
                                                            string kk1         = words[m].ToString();
                                                            int    schemecheck = String.Compare(words[m].ToString().Replace("\n", "").Replace("\r", "").Trim(), DatabasePagescheme.Trim());
                                                            if (schemecheck == 0)
                                                            {
                                                                Pagescheme = words[m].ToString();
                                                                schemeid   = Key;
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    //  }
                                }
                                catch
                                {
                                }
                            }
                            try
                            {
                                if (pagelastindex != "")
                                {
                                    string[] data = pagelastindex.Split(',');
                                    kk.Add(data[0]);
                                    if (data.Length > 2)
                                    {
                                        kk.Add(data[data.Length - 2]);
                                    }
                                }
                                if (kk.Count > 0)
                                {
                                    if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/Customerwisedata/" + Reporttype + "/" + pageText)))
                                    {
                                        Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Customerwisedata/" + Reporttype + "/" + pageText));
                                    }
                                    string filename   = string.Empty;
                                    string targetPath = string.Empty;
                                    filename = pageText + "_" + datewisedata.Replace("\n", "").Replace("\r", "").Trim().Replace(" ", "").Replace("/", "-") + ".pdf";
                                    object[] extractPagesParam = kk.ToArray();
                                    //kk.ToArray();

                                    newDoc = jso.GetType().InvokeMember(
                                        "extractPages",
                                        BindingFlags.InvokeMethod |
                                        BindingFlags.Public |
                                        BindingFlags.Instance,
                                        null, jso, extractPagesParam);

                                    targetPath = HttpContext.Current.Server.MapPath("~/Customerwisedata/" + Reporttype + "/" + pageText + "/" + @"\" + filename);
                                    shortpath  = "Customerwisedata/" + Reporttype + "/" + pageText + "/" + filename;
                                    object[] saveAsParam = { targetPath };
                                    newDoc.GetType().InvokeMember(
                                        "saveAs", System.Reflection.BindingFlags.InvokeMethod, null, newDoc, saveAsParam);


                                    if (pageText != "" && Reporttype != 0 && pageText != "0")
                                    {
                                        FAMSEntities dbcontext = new FAMSEntities();


                                        var results = dbcontext.MultipleResults("[dbo].[BindSchememaster]").With <Responsecls>()
                                                      .Execute("@Querytype", "@Fromdate", "@Todate", "@Cust_code", "@Schemeid", "@Shortpath", "@Reporttype", "@ReportName", "InsertAllReportHistoryData", Fromdate.Trim(), Todate.Trim(), pageText, Convert.ToString(schemeid), shortpath, Convert.ToString(Reporttype), Reportname);
                                    }
                                }
                            }
                            catch { }

                            avDoc.Close(0);
                            avDoc.ClearSelection();
                            acroApp.CloseAllDocs();
                            doc.Close();
                            acroApp.Hide();
                            acroApp.Exit();
                            //string pname = "Acrobat";
                            //string localMachineName = Environment.MachineName;
                            //var runningProcess = Process.GetProcesses(localMachineName);
                            //int c= runningProcess.Count();
                            //foreach (var process in runningProcess)
                            //{
                            //    if (process.ProcessName.Trim() == pname)
                            //    {
                            //        process.Kill();
                            //    }

                            //}
                            //string sourceFile = System.IO.Path.Combine(SourceDirectorypath, pdffilename);
                            //String Todaysdate = DateTime.Now.ToString("yyyy-MM-dd");
                            //if (!Directory.Exists(DestinationDirectorypath + Todaysdate))
                            //{
                            //    var DIR = Directory.CreateDirectory(DestinationDirectorypath + Todaysdate);

                            //}

                            //string destFile = System.IO.Path.Combine(DestinationDirectorypath + Todaysdate, pdffilename);
                            //System.IO.File.Copy(sourceFile, destFile, true);

                            //if (File.Exists(destFile))
                            //{

                            //     System.IO.File.Delete(sourceFile);
                            //}
                        }

                        /////////////Move file from source to destination
                    }
                }
            }
            catch (Exception ex) { }

            return("1");
        }