Beispiel #1
0
        public static void Run(string outputPdfPath)
        {
            // Create the document's layout from a DLEX template
            DocumentLayout documentLayout = new DocumentLayout(Util.GetResourcePath("DLEX/Invoice.dlex"));

            InvoiceExampleData.Order order      = InvoiceExampleData.Order11077;
            NameValueLayoutData      layoutData = new NameValueLayoutData();

            layoutData.Add("OrderID", order.OrderID);
            layoutData.Add("OrderDate", order.OrderDate);
            layoutData.Add("CustomerID", order.CustomerID);
            layoutData.Add("ShippedDate", order.ShippedDate);
            layoutData.Add("ShipperName", order.ShipperName);
            layoutData.Add("BillTo", order.BillTo);
            layoutData.Add("ShipTo", order.ShipTo);
            layoutData.Add("Freight", order.Freight);
            layoutData.Add("OrderDetails", order.OrderDetails);

            // Layout the document using the parameters and set it's properties
            Document document = documentLayout.Layout(layoutData);

            document.Author = "DynamicPDF ReportWriter";
            document.Title  = "Invoice Example";

            // Outputs the document to a file
            document.Draw(outputPdfPath);
        }
Beispiel #2
0
        public static void Run(string outputPdfPath)
        {
            // Create the document's layout from a DLEX template
            DocumentLayout layoutReport = new DocumentLayout(Util.GetResourcePath("DLEX/FormFill.dlex"));

            // Specify the data.
            NameValueLayoutData layoutData = new NameValueLayoutData();
            W4Data w4Data = new W4Data
            {
                FirstNameAndI = "Alex B.",
                LastName      = "Smith",
                SSN           = "123-45-6789",
                HomeAddress   = "456 Green Road",
                IsSingle      = true,
                CityStateZip  = "Somewhere, Earth  12345",
                Allowances    = 2
            };

            layoutData.Add("W4Data", w4Data);

            // Layout the document and save the PDF
            Document document = layoutReport.Layout(layoutData);

            document.Author = "DynamicPDF ReportWriter";
            document.Title  = "Form Fill Example";

            document.Draw(outputPdfPath);
        }
        public static string GetInformationAboutCurrentPage(DocumentLayout currentDocumentLayout, LayoutPage currentPage, DocumentPosition currentPosition)
        {
            string returnedInformation = "";

            int currentPageIndex = currentDocumentLayout.GetPageIndex(currentPage);
            int totalPageCount   = currentDocumentLayout.GetFormattedPageCount();

            // get information about page content using a LayoutVisitor descendant
            CustomDocumentLayoutVisitor visitor = new CustomDocumentLayoutVisitor();

            visitor.Visit(currentPage);

            // get information about page bounds using PageArea properties
            PageAreaProperties pageAreaProperties = CaculatePageAreaProperties(currentPage.PageAreas[0], currentPosition);

            returnedInformation += String.Format("\r\nPage: {0} of {1}\r\n", currentPageIndex + 1, totalPageCount);
            returnedInformation += String.Format("Current page range: {0} - {1}\r\n", currentPage.MainContentRange.Start, currentPage.MainContentRange.Start + currentPage.MainContentRange.Length - 1);
            returnedInformation += String.Format("Images count: {0}\r\n", visitor.ImagesCount);
            returnedInformation += String.Format("Tables count: {0}\r\n", visitor.TablesCount);
            returnedInformation += String.Format("Text Boxes count: {0}\r\n", visitor.TextBoxesCount);
            returnedInformation += String.Format("Paragraphs count: {0}\r\n", visitor.ParagraphsCount);
            returnedInformation += String.Format("Text lines count: {0}\r\n", visitor.TextLinesCount);
            returnedInformation += String.Format("Words (text blocks) count: {0}\r\n", visitor.WordsCount);

            returnedInformation += String.Format("\r\nColumn: {0} of {1}\r\n", pageAreaProperties.currentColumnIndex, pageAreaProperties.columnCount);
            returnedInformation += String.Format("Current COLUMN content bounds: {0}\r\n", pageAreaProperties.currentColumnBounds);
            returnedInformation += String.Format("Current PAGE content bounds: {0}\r\n", pageAreaProperties.currentPageBounds);

            return(returnedInformation);
        }
Beispiel #4
0
        private static void AnalyseLayout()
        {
            string imageFile = @"D:\Self-Study\OpenSources\Tesseract\original\phototest.tif";
            //imageFile = @"D:\Self-Study\OpenSources\Tesseract\original\eurotext.tif";

            TesseractProcessor processor = new TesseractProcessor();

            processor.InitForAnalysePage();
            processor.SetPageSegMode(ePageSegMode.PSM_AUTO);

            using (Bitmap bmp = Bitmap.FromFile(imageFile) as Bitmap)
            {
                DocumentLayout doc = processor.AnalyseLayout(bmp);
                Console.WriteLine(doc.ToString());

                using (Image tmp = new Bitmap(bmp.Width, bmp.Height)) // prevents one-byte index format
                {
                    using (Graphics grph = Graphics.FromImage(tmp))
                    {
                        Rectangle rect = new Rectangle(0, 0, tmp.Width, tmp.Height);

                        grph.DrawImage(bmp, rect, rect, GraphicsUnit.Pixel);

                        grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                        foreach (Block block in doc.Blocks)
                        {
                            DrawBlock(grph, block);
                        }
                    }

                    tmp.Save(@"D:\temp\page_layout_test2.bmp");
                }
            }
        }
Beispiel #5
0
    static oTesseractRequest __ocrExecute2(oTesseractRequest req, Bitmap bitmap)
    {
        using (TesseractProcessor processor = new TesseractProcessor())
        {
            processor.InitForAnalysePage();
            using (GreyImage greyImage = GreyImage.FromImage(bitmap))
            {
                //greyImage.Save(ImageFormat.Bmp, outFile2);

                ImageThresholder thresholder = new AdaptiveThresholder();
                using (BinaryImage binImage = thresholder.Threshold(greyImage))
                {
                    DocumentLayout doc = null;
                    switch (req.command)
                    {
                    case TESSERACT_COMMAND.GET_TEXT:
                        //string s = tes.GetText().Trim();
                        //req.output_text = s;
                        //req.output_count = s.Length;
                        req.ok = 1;
                        break;

                    default:
                        unsafe
                        {
                            doc = processor.AnalyseLayoutBinaryImage(
                                binImage.BinaryData, greyImage.Width, greyImage.Height);
                        }
                        if (doc != null)
                        {
                            var bs = new List <string>();
                            if (doc.Blocks.Count > 0)
                            {
                                for (int i = 0; i < doc.Blocks.Count; i++)
                                {
                                    for (int j = 0; j < doc.Blocks[i].Paragraphs.Count; j++)
                                    {
                                        bs.AddRange(doc.Blocks[j].Paragraphs[j].Lines
                                                    .Select(x => string.Format(
                                                                "{0}_{1}_{2}_{3}", x.Left, x.Top, x.Right, x.Bottom)));
                                    }
                                }
                            }
                            req.output_format = "left_top_right_bottom";
                            req.output_text   = string.Join("|", bs.ToArray());
                            req.output_count  = bs.Count;
                            req.ok            = 1;
                        }
                        break;
                    }
                }
            }
        }

        return(req);
    }
        public static void Run()
        {
            var jsonData = JsonConvert.DeserializeObject(File.ReadAllText(Util.GetPath("Resources/Data/SimpleReportData.json")));

            DocumentLayout layoutReport = new DocumentLayout(Util.GetPath("Resources/DLEXs/SimpleReportWithCoverPageFromJSON.dlex"));

            NameValueLayoutData layoutData = new NameValueLayoutData();

            layoutData.Add("ReportCreatedFor", "Alex Smith");
            layoutData.Add("Products", jsonData);

            Document document = layoutReport.Layout(layoutData);

            document.Draw(Util.GetPath("Output/SimpleReportWithCoverPageFromJSON.pdf"));
        }
Beispiel #7
0
        internal static void Run(string outputFilePath)
        {
            // Create the document's layout from a DLEX template
            DocumentLayout documentLayout = new DocumentLayout(Util.GetResourcePath("ReportWithSubReport.dlex"));

            // Attach to the ReportDataRequired event
            documentLayout.ReportDataRequired += DocumentLayout_ReportDataRequired;

            NameValueLayoutData layoutData = new NameValueLayoutData();

            layoutData.Add("ReportCreatedFor", "Alex Smith");

            // Layout the document and save the PDF
            Document document = documentLayout.Layout(layoutData);

            document.Draw(outputFilePath);
        }
        // Generates a PDF report using a collection of objects.
        // The collection of objects is in the SimpleReportWithCoverPageExampleData class.
        // This code uses the DynamicPDF ReportWriter for .NET product.
        // Use the ceTe.DynamicPDF namespace for the Document class.
        // Use the ceTe.DynamicPDF.LayoutEngine namespace for the DocumentLayout class.
        static void Main(string[] args)
        {
            // Create DocumentLayout object using the DLEX (report layout) file
            DocumentLayout layoutReport = new DocumentLayout(GetResourcePath("SimpleReportWithCoverPage.dlex"));

            // Create a NameValueLayoutData object with the Data
            NameValueLayoutData layoutData = new NameValueLayoutData();

            layoutData.Add("ReportCreatedFor", "Alex Smith");
            layoutData.Add("Products", SimpleReportWithCoverPageExampleData.Products);

            // Get the Document from the DocumentLayout
            Document document = layoutReport.Layout(layoutData);

            //Save the Document
            document.Draw("output.pdf");
        }
Beispiel #9
0
        public static void Run(string outputPdfPath)
        {
            // Create the document's layout from a DLEX template
            DocumentLayout documentLayout = new DocumentLayout(Util.GetResourcePath("DLEX/ContactListWithGroupBy.dlex"));

            NameValueLayoutData layoutData = new NameValueLayoutData();

            layoutData.Add("Contacts", ContactListWithGroupByExampleData.Contacts);

            // Layout the document using the parameters and set it's properties
            Document document = documentLayout.Layout(layoutData);

            document.Author = "DynamicPDF ReportWriter";
            document.Title  = "Contact List With Group By Example";

            // Outputs the document to a file
            document.Draw(outputPdfPath);
        }
        public static void Run(string outputPdfPath)
        {
            // Create the document's layout from a DLEX template
            DocumentLayout layoutReport = new DocumentLayout(Util.GetResourcePath("DLEX/SimpleSubReport.dlex"));

            NameValueLayoutData layoutData = new NameValueLayoutData();

            layoutData.Add("ProductsByCategory", SimpleSubReportExampleData.ProductsByCategory);

            // Layout the document and set it's properties
            Document document = layoutReport.Layout(layoutData);

            document.Author = "DynamicPDF ReportWriter";
            document.Title  = "Simple SubReport Example";

            // Outputs the document to a file
            document.Draw(outputPdfPath);
        }
Beispiel #11
0
        public static void Run(string outputPdfPath)
        {
            DocumentLayout layoutReport = new DocumentLayout(Util.GetResourcePath("DLEX/SimpleReportWithCoverPage.dlex"));

            NameValueLayoutData layoutData = new NameValueLayoutData();

            layoutData.Add("ReportCreatedFor", "Alex Smith");
            layoutData.Add("Products", SimpleReportWithCoverPageExampleData.Products);

            // Layout the document and set it's properties
            Document document = layoutReport.Layout(layoutData);

            document.Author = "DynamicPDF ReportWriter";
            document.Title  = "Simple Report Example";

            // Outputs the document to a file
            document.Draw(outputPdfPath);
        }
        public static void Run(string outputPdfPath)
        {
            // Create the document's layout from a DLEX template
            DocumentLayout layoutReport = new DocumentLayout(Util.GetResourcePath("DLEX/FormLetter.dlex"));

            // Specify the data.
            NameValueLayoutData layoutData = new NameValueLayoutData();

            layoutData.Add("Name", "Alex Smith");
            layoutData.Add("Address", "456 Green Road\nSomewhere, Earth");
            layoutData.Add("Amount", "$321.00");

            // Layout the document and save the PDF
            Document document = layoutReport.Layout(layoutData);

            document.Author = "DynamicPDF ReportWriter";
            document.Title  = "Form Letter Example";

            document.Draw(outputPdfPath);
        }
Beispiel #13
0
        /// <summary>
        /// Populates the layout radio buttons from disk.
        /// </summary>
        private void PopulateLayoutRadioButtonsFromDisk()
        {
            List <RadioButton> radioButtonList = new List <RadioButton>();
            var           rockConfig           = RockConfig.Load();
            List <string> filenameList         = Directory.GetFiles(".", "*.dplx").ToList();

            foreach (var fileName in filenameList)
            {
                DplxFile       dplxFile       = new DplxFile(fileName);
                DocumentLayout documentLayout = new DocumentLayout(dplxFile);
                RadioButton    radLayout      = new RadioButton();
                if (!string.IsNullOrWhiteSpace(documentLayout.Title))
                {
                    radLayout.Content = documentLayout.Title.Trim();
                }
                else
                {
                    radLayout.Content = fileName;
                }

                radLayout.Tag       = fileName;
                radLayout.IsChecked = rockConfig.LayoutFile == fileName;
                radioButtonList.Add(radLayout);
            }

            if (!radioButtonList.Any(a => a.IsChecked ?? false))
            {
                if (radioButtonList.FirstOrDefault() != null)
                {
                    radioButtonList.First().IsChecked = true;
                }
            }

            lstLayouts.Items.Clear();
            foreach (var item in radioButtonList.OrderBy(a => a.Content))
            {
                lstLayouts.Items.Add(item);
            }
        }
        /// <summary>
        /// Populates the layout radio buttons from disk.
        /// </summary>
        private void PopulateLayoutRadioButtonsFromDisk()
        {
            List<RadioButton> radioButtonList = new List<RadioButton>();
            var rockConfig = RockConfig.Load();
            List<string> filenameList = Directory.GetFiles( ".", "*.dplx" ).ToList();
            foreach ( var fileName in filenameList )
            {
                DplxFile dplxFile = new DplxFile( fileName );
                DocumentLayout documentLayout = new DocumentLayout( dplxFile );
                RadioButton radLayout = new RadioButton();
                if ( !string.IsNullOrWhiteSpace( documentLayout.Title ) )
                {
                    radLayout.Content = documentLayout.Title.Trim();
                }
                else
                {
                    radLayout.Content = fileName;
                }

                radLayout.Tag = fileName;
                radLayout.IsChecked = rockConfig.LayoutFile == fileName;
                radioButtonList.Add( radLayout );
            }

            if ( !radioButtonList.Any( a => a.IsChecked ?? false ) )
            {
                if ( radioButtonList.FirstOrDefault() != null )
                {
                    radioButtonList.First().IsChecked = true;
                }
            }

            lstLayouts.Items.Clear();
            foreach ( var item in radioButtonList.OrderBy( a => a.Content ) )
            {
                lstLayouts.Items.Add( item );
            }
        }
Beispiel #15
0
        public static void Run(string outputPdfPath)
        {
            //Create the document's layout from a DLEX template
            DocumentLayout documentLayout = new DocumentLayout(Util.GetResourcePath("DLEX/PlaceHolder.dlex"));

            // Retrieve the placeholder for the dynamic image and attach an event to it
            ceTe.DynamicPDF.LayoutEngine.LayoutElements.PlaceHolder barcode = (ceTe.DynamicPDF.LayoutEngine.LayoutElements.PlaceHolder)documentLayout.GetLayoutElementById("Barcode");
            barcode.LaidOut += Barcode_LaidOut;

            // Specify the Data to use when laying out the document
            NameValueLayoutData layoutData = new NameValueLayoutData();

            layoutData.Add("HeaderData", "Popular Websites");
            layoutData.Add("Websites", PlaceHolderExampleData.Websites);

            // Layout the PDF document
            Document document = documentLayout.Layout(layoutData);

            document.Author = "DynamicPDF ReportWriter";
            document.Title  = "PlaceHolder Example";

            // Outputs the document to a file
            document.Draw(outputPdfPath);
        }
        private DocumentLayout GetReportLayout(RockConfig rockConfig)
        {
            // setup report layout and events
            DocumentLayout report = new DocumentLayout(this.Options.LayoutFile);

            //// if there is an imgLogo and the path is "logo.jpg", use the logo specified in rockconfig.
            //// We have to read the layout as Xml first to figure out what the Path of the imgLogo
            XmlDocument layoutXmlDoc = new XmlDocument();

            layoutXmlDoc.Load(this.Options.LayoutFile);
            var imageNodes = layoutXmlDoc.GetElementsByTagName("image");

            foreach (var imageNode in imageNodes.OfType <XmlNode>())
            {
                string imagePath = imageNode.Attributes["path"].Value;
                string imageId   = imageNode.Attributes["id"].Value;
                if (imageId.Equals("imgLogo") && imagePath.Equals(RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase))
                {
                    Image imgLogo = report.GetReportElementById("imgLogo") as Image;
                    if (imgLogo != null)
                    {
                        try
                        {
                            if (!rockConfig.LogoFile.Equals(RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase))
                            {
                                imgLogo.ImageData = ceTe.DynamicPDF.Imaging.ImageData.GetImage(rockConfig.LogoFile);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Error loading Logo Image: " + rockConfig.LogoFile + "\n\n" + ex.Message);
                        }
                    }
                }
            }

            Query query = report.GetQueryById("OuterQuery");

            if (query == null)
            {
                throw new MissingReportElementException("Report requires a QueryElement named 'OuterQuery'");
            }

            query.OpeningRecordSet += mainQuery_OpeningRecordSet;

            Query orgInfoQuery = report.GetQueryById("OrgInfoQuery");

            if (orgInfoQuery == null)
            {
                throw new MissingReportElementException("Report requires a QueryElement named 'OrgInfoQuery'");
            }

            orgInfoQuery.OpeningRecordSet += orgInfoQuery_OpeningRecordSet;

            _accountSummaryQuery = report.GetQueryById("AccountSummaryQuery");

            if (_accountSummaryQuery == null)
            {
                // not required.  Just don't do anything if it isn't there
            }
            else
            {
                _accountSummaryQuery.OpeningRecordSet += delegate(object s, OpeningRecordSetEventArgs ee)
                {
                    // create a recordset for the _accountSummaryQuery which is the GroupBy summary of AccountName, Amount

                    /*
                     * The structure of _transactionsDataTable is
                     *
                     * DateTime TransactionDateTime
                     * string CurrencyTypeValueName
                     * string Summary (main transaction summary)
                     * DataTable Details {
                     *    int AccountId
                     *    string AccountName
                     *    string Summary (detail summary)
                     *    decimal Amount
                     * }
                     */

                    var detailsData = new DataTable();
                    detailsData.Columns.Add("AccountId", typeof(int));
                    detailsData.Columns.Add("AccountName");
                    detailsData.Columns.Add("Amount", typeof(decimal));

                    foreach (var details in _transactionsDataTable.AsEnumerable().Select(a => (a["Details"] as DataTable)))
                    {
                        foreach (var row in details.AsEnumerable())
                        {
                            detailsData.Rows.Add(row["AccountId"], row["AccountName"], row["Amount"]);
                        }
                    }

                    var summaryTable = detailsData.AsEnumerable().GroupBy(g => g["AccountId"]).Select(a => new
                    {
                        AccountName = a.Max(x => x["AccountName"].ToString()),
                        Amount      = a.Sum(x => decimal.Parse(x["Amount"].ToString()))
                    }).OrderBy(o => o.AccountName);

                    ee.RecordSet = new EnumerableRecordSet(summaryTable);
                };
            }

            return(report);
        }
Beispiel #17
0
        /// <summary>
        /// Creates the document.
        /// </summary>
        /// <param name="financialTransactionQry">The financial transaction qry.</param>
        /// <returns></returns>
        public Document RunReport()
        {
            UpdateProgress("Connecting...");

            // Login and setup options for REST calls
            RockConfig rockConfig = RockConfig.Load();

            _rockRestClient = new RockRestClient(rockConfig.RockBaseUrl);
            _rockRestClient.Login(rockConfig.Username, rockConfig.Password);

            _contributionStatementOptionsREST = new Rock.Net.RestParameters.ContributionStatementOptions
            {
                StartDate      = Options.StartDate,
                EndDate        = Options.EndDate,
                AccountIds     = Options.AccountIds,
                PersonId       = Options.PersonId,
                OrderByZipCode = true
            };

            var organizationAddressAttribute = _rockRestClient.GetData <List <Rock.Model.Attribute> >("api/attributes", "Key eq 'OrganizationAddress'").FirstOrDefault();

            if (organizationAddressAttribute != null)
            {
                Guid locationGuid = Guid.Empty;
                if (Guid.TryParse(organizationAddressAttribute.DefaultValue, out locationGuid))
                {
                    _organizationAddressLocation = _rockRestClient.GetDataByGuid <Rock.Model.Location>("api/locations", locationGuid);
                }
            }

            // If we don't have a _organizationAddressLocation, just create an empty location
            _organizationAddressLocation = _organizationAddressLocation ?? new Rock.Model.Location();

            // setup report layout and events
            DocumentLayout report = new DocumentLayout(this.Options.LayoutFile);

            //// if there is an imgLogo and the path is "logo.jpg", use the logo specified in rockconfig.
            //// We have to read the layout as Xml first to figure out what the Path of the imgLogo
            XmlDocument layoutXmlDoc = new XmlDocument();

            layoutXmlDoc.Load(this.Options.LayoutFile);
            var imageNodes = layoutXmlDoc.GetElementsByTagName("image");

            foreach (var imageNode in imageNodes.OfType <XmlNode>())
            {
                string imagePath = imageNode.Attributes["path"].Value;
                string imageId   = imageNode.Attributes["id"].Value;
                if (imageId.Equals("imgLogo") && imagePath.Equals(RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase))
                {
                    Image imgLogo = report.GetReportElementById("imgLogo") as Image;
                    if (imgLogo != null)
                    {
                        try
                        {
                            if (!rockConfig.LogoFile.Equals(RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase))
                            {
                                imgLogo.ImageData = ceTe.DynamicPDF.Imaging.ImageData.GetImage(rockConfig.LogoFile);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Error loading Logo Image: " + rockConfig.LogoFile + "\n\n" + ex.Message);
                        }
                    }
                }
            }


            Query query = report.GetQueryById("OuterQuery");

            if (query == null)
            {
                throw new MissingReportElementException("Report requires a QueryElement named 'OuterQuery'");
            }

            query.OpeningRecordSet += mainQuery_OpeningRecordSet;

            Query orgInfoQuery = report.GetQueryById("OrgInfoQuery");

            if (orgInfoQuery == null)
            {
                throw new MissingReportElementException("Report requires a QueryElement named 'OrgInfoQuery'");
            }

            orgInfoQuery.OpeningRecordSet += orgInfoQuery_OpeningRecordSet;

            _accountSummaryQuery = report.GetQueryById("AccountSummaryQuery");

            if (_accountSummaryQuery == null)
            {
                // not required.  Just don't do anything if it isn't there
            }
            else
            {
                _accountSummaryQuery.OpeningRecordSet += delegate(object s, OpeningRecordSetEventArgs ee)
                {
                    // create a recordset for the _accountSummaryQuery which is the GroupBy summary of AccountName, Amount
                    var summaryTable = _transactionsDataTable.AsEnumerable().GroupBy(g => g["AccountId"]).Select(a => new
                    {
                        AccountName = a.Max(x => x["AccountName"].ToString()),
                        Amount      = a.Sum(x => decimal.Parse(x["Amount"].ToString()))
                    }).OrderBy(o => o.AccountName);

                    ee.RecordSet = new EnumerableRecordSet(summaryTable);
                };
            }

            UpdateProgress("Getting Data...");

            // get outer query data from Rock database via REST now vs in mainQuery_OpeningRecordSet to make sure we have data
            DataSet personGroupAddressDataSet = _rockRestClient.PostDataWithResult <Rock.Net.RestParameters.ContributionStatementOptions, DataSet>("api/FinancialTransactions/GetContributionPersonGroupAddress", _contributionStatementOptionsREST);

            _personGroupAddressDataTable = personGroupAddressDataSet.Tables[0];
            RecordCount = _personGroupAddressDataTable.Rows.Count;

            if (RecordCount > 0)
            {
                Document doc = report.Run();
                return(doc);
            }
            else
            {
                return(null);
            }
        }
        public static string GetInformationAboutCurrentTextBoxContent(LayoutTextBox currentTextBox, DocumentLayout currentLayout)
        {
            string returnedInformation          = "";
            CustomDocumentLayoutVisitor visitor = new CustomDocumentLayoutVisitor();

            visitor.Visit(currentTextBox);

            SubDocument doc = currentLayout.BeginUpdateDocument(currentTextBox);
            string      plainTextContent = doc.GetText(doc.Range);

            currentLayout.EndUpdateDocument(doc);

            returnedInformation += String.Format("Lines count: {0}\r\n", visitor.TextLinesCount);
            returnedInformation += String.Format("Words count: {0}\r\n", visitor.WordsCount);
            returnedInformation += String.Format("Plain text: {0}\r\n", plainTextContent);
            return(returnedInformation);
        }
Beispiel #19
0
        /// <summary>
        /// Updates the current layout of our RowCache to the specified number of
        /// columns. 
        /// </summary>
        /// <param name="layout"></param> 
        private void UpdateDocumentLayout(DocumentLayout layout) 
        {
            // Check if the layout is for a Vertical or Horizontal offset update, 
            // in which case the value can be changed immediately.
            if (layout.ViewMode == ViewMode.SetHorizontalOffset)
            {
                SetHorizontalOffsetInternal(layout.Offset); 
                return;
            } 
            else if (layout.ViewMode == ViewMode.SetVerticalOffset) 
            {
                SetVerticalOffsetInternal(layout.Offset); 
                return;
            }

            //Store off the layout in case we need it later. 
            //(For example, if our viewport is (0,0).
            _documentLayout = layout; 
 
            //Update MaxPagesAcross
            _maxPagesAcross = _documentLayout.Columns; 

            //If we have a non (0,0) Viewport then we can calculate a new layout.
            //Otherwise we set our "Layout Requested" flag so that when we get
            //a non-zero Viewport size we'll compute the requested layout. 
            if (IsViewportNonzero)
            { 
                //If this is a Thumbnails layout, we need to calculate how many 
                //columns we should fit on the pivotRow.
                if (_documentLayout.ViewMode == ViewMode.Thumbnails) 
                {
                    _maxPagesAcross = _documentLayout.Columns = CalculateThumbnailColumns();
                }
 
                //We need to determine the page that has the active focus so we know what page
                //to keep visible in the new layout. 
                int pivotPage = GetActiveFocusPage(); 

                //Ask the RowCache to recalculate the layout based 
                //on the specified pivot page and the number of columns
                //requested.
                //The RowCache will call us back with a
                //RowLayoutCompleted event when the layout is complete 
                //and we'll update the scale and invalidate our layout there.
                _rowCache.RecalcRows(pivotPage, _documentLayout.Columns); 
 
                _isLayoutRequested = false;
            } 
            else
            {
                _isLayoutRequested = true;
            } 
        }
Beispiel #20
0
    static oTesseractRequest __ocrExecute(oTesseractRequest req, Bitmap bitmap)
    {
        using (TesseractProcessor processor = new TesseractProcessor())
        {
            // call SetVariable() method before passing image(api->SetImage(image))
            // 0: otsu
            // 1: isodata local adaptive
            // 2: sauvola local adaptive => not implement yet
            //processor.SetVariable("tessedit_thresholding_method", "0");
            processor.SetVariable("tessedit_thresholding_method", "1");

            //processor.InitForAnalysePage();
            //processor.SetPageSegMode(ePageSegMode.PSM_AUTO_ONLY);
            //var success = processor.Init(req.data_path, req.lang, (int)eOcrEngineMode.OEM_DEFAULT);

            //var imageColor = new Emgu.CV.Mat();
            //var imageCV = new Emgu.CV.Image<Emgu.CV.Structure.Bgr, byte>(bitmap); //Image Class from Emgu.CV
            ////var imageCV = new Emgu.CV.Image<Emgu.CV.Structure.Gray, byte>(bitmap); //Image Class from Emgu.CV
            //var image = imageCV.Mat; //This is your Image converted to Mat

            //if (image.NumberOfChannels == 1)
            //    Emgu.CV.CvInvoke.CvtColor(image, imageColor, Emgu.CV.CvEnum.ColorConversion.Gray2Bgr);
            //else
            //    image.CopyTo(imageColor);

            using (var m0 = new MemoryStream())
            {
                bitmap.Save(m0, ImageFormat.Jpeg);
                //using (Bitmap bmp = Bitmap.FromFile(@"C:\temp\1.jpg") as Bitmap)
                using (Bitmap bmp = new Bitmap(m0))
                {
                    DocumentLayout doc = null;
                    switch (req.command)
                    {
                    case TESSERACT_COMMAND.GET_TEXT:
                        //string s = tes.GetText().Trim();
                        //req.output_text = s;
                        //req.output_count = s.Length;
                        req.ok = 1;
                        break;

                    default:
                        unsafe
                        {
                            doc = processor.AnalyseLayout(bmp);
                        }
                        if (doc != null)
                        {
                            var bs = new List <string>();
                            if (doc.Blocks.Count > 0)
                            {
                                for (int i = 0; i < doc.Blocks.Count; i++)
                                {
                                    for (int j = 0; j < doc.Blocks[i].Paragraphs.Count; j++)
                                    {
                                        bs.AddRange(doc.Blocks[j].Paragraphs[j].Lines
                                                    .Select(x => string.Format(
                                                                "{0}_{1}_{2}_{3}", x.Left, x.Top, x.Right, x.Bottom)));
                                    }
                                }
                            }
                            req.output_format = "left_top_right_bottom";
                            req.output_text   = string.Join("|", bs.ToArray());
                            req.output_count  = bs.Count;
                            req.ok            = 1;
                        }
                        break;
                    }
                }
            }
        }

        return(req);
    }
        // get information about a current text box layout
        public static string GetInformationAboutCurrentTextBox(SubDocument subDocument, DocumentLayout currentLayout, DocumentPosition docPosition)
        {
            string returnedInformation = "!A TEXTBOX CONTENT IS SELECTED!\r\n";

            LayoutIterator layoutIterator     = new LayoutIterator(currentLayout, subDocument.Range);
            LayoutPage     currentTextBoxPage = null;
            LayoutTextBox  currentTextBox     = null;

            while (layoutIterator.MoveNext())
            {
                LayoutElement element = layoutIterator.Current;
                if (element is LayoutTextBox)
                {
                    currentTextBox = (element as LayoutTextBox);
                    if (currentTextBox.Parent is LayoutPage)
                    {
                        currentTextBoxPage = currentTextBox.Parent as LayoutPage;
                    }
                }
                if (element is PlainTextBox)
                {
                    PlainTextBox currentPlaintTextBox = element as PlainTextBox;
                    if (currentPlaintTextBox.Range.Contains(docPosition.ToInt()))
                    {
                        returnedInformation += String.Format("Selected content: {0}\r\n", currentPlaintTextBox.Text);

                        LayoutRow currentRow       = currentPlaintTextBox.Parent as LayoutRow;
                        int       currentLineIndex = currentTextBox.Rows.ToList().IndexOf(currentRow);
                        returnedInformation += String.Format("Line index: {0}\r\n", currentLineIndex + 1);
                        returnedInformation += String.Format("Selected block bounds: {0}\r\n", currentPlaintTextBox.Bounds);
                        break;
                    }
                }
            }

            returnedInformation += String.Format("TEXTBOX bounds: {0}\r\n", currentTextBox.Bounds);
            returnedInformation += String.Format("\r\n!!Content information:\r\n");
            returnedInformation += GetInformationAboutCurrentTextBoxContent(currentTextBox, currentLayout);

            if (currentTextBoxPage != null)
            {
                returnedInformation += PageLayoutHelper.GetInformationAboutCurrentPage(currentLayout, currentTextBoxPage, docPosition);
            }
            return(returnedInformation);
        }
        public static string GetInformationAboutRichEditDocumentLayout(Document currentDocument, DocumentLayout currentDocumentLayout)
        {
            SubDocument      subDocument = currentDocument.CaretPosition.BeginUpdateDocument();
            DocumentPosition docPosition = subDocument.CreatePosition(currentDocument.CaretPosition.ToInt() == 0 ? 0 : currentDocument.CaretPosition.ToInt() - 1);

            ReadOnlyShapeCollection         shapes = subDocument.Shapes.Get(subDocument.CreateRange(docPosition, 1));
            ReadOnlyDocumentImageCollection images = subDocument.Images.Get(subDocument.CreateRange(docPosition, 1));

            if (shapes.Count == 0 && images.Count == 0)
            {
                docPosition = subDocument.CreatePosition(currentDocument.CaretPosition.ToInt());
            }

            string returnedInformation = "";

            // get infromation about a current document element
            returnedInformation += GetInformationAboutCurrentDocumentElement(currentDocument, currentDocumentLayout, subDocument, docPosition);

            // collect information about CURRENT PAGE
            RangedLayoutElement layoutPosition = currentDocumentLayout.GetElement <RangedLayoutElement>(docPosition);

            if (layoutPosition != null)
            {
                int currentPageIndex = currentDocumentLayout.GetPageIndex(layoutPosition);
                returnedInformation += PageLayoutHelper.GetInformationAboutCurrentPage(currentDocumentLayout, currentDocumentLayout.GetPage(currentPageIndex), docPosition);
            }

            currentDocument.CaretPosition.EndUpdateDocument(subDocument);

            return(returnedInformation);
        }
        public static void AnalyseLayout()
        {
            int n_images = Workspace.Images.Length;
            int i_image  = 0;

            for (; i_image < n_images; i_image++)
            {
                string fileName = Workspace.Images[i_image];

                Console.WriteLine("{0} Image: {1}", i_image, fileName);

                string imageFile = Path.Combine(Workspace.InputFolder, fileName);

                string name = Path.GetFileNameWithoutExtension(imageFile);

                string outFile  = Path.Combine(Workspace.OutputFolder, string.Format("Simple1_{0}_layout.bmp", name));
                string outFile2 = Path.Combine(Workspace.OutputFolder, string.Format("Simple1_{0}_grey.bmp", name));
                string outFile3 = Path.Combine(Workspace.OutputFolder, string.Format("Simple1_{0}_bin.bmp", name));

                using (TesseractProcessor processor = new TesseractProcessor())
                {
                    processor.InitForAnalysePage();
                    //processor.SetPageSegMode(ePageSegMode.PSM_AUTO);

                    using (Bitmap bmp = Bitmap.FromFile(imageFile) as Bitmap)
                    {
                        DateTime started = DateTime.Now;
                        DateTime ended   = DateTime.Now;

                        DocumentLayout doc = null;

                        unsafe
                        {
                            started = DateTime.Now;

                            doc = processor.AnalyseLayout(bmp);

                            ended = DateTime.Now;

                            Console.WriteLine("Duration AnalyseLayout: {0} ms", (ended - started).TotalMilliseconds);
                        }
                        Console.WriteLine(doc.ToString());

                        using (Image tmp = new Bitmap(bmp.Width, bmp.Height)) // prevents one-byte index format
                        {
                            using (Graphics grph = Graphics.FromImage(tmp))
                            {
                                Rectangle rect = new Rectangle(0, 0, tmp.Width, tmp.Height);

                                grph.DrawImage(bmp, rect, rect, GraphicsUnit.Pixel);

                                grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                                foreach (Block block in doc.Blocks)
                                {
                                    Render.DrawBlock(grph, block);
                                }
                            }

                            tmp.Save(outFile);
                        }
                    }
                }
            }
        }
Beispiel #24
0
 /// <summary> 
 /// Places a delegate for an UpdateDocumentLayout call on the queue.  We do this for
 /// performance reasons, as changing the document layout takes significant time. 
 /// </summary>
 /// <param name="layout"></param>
 private void QueueUpdateDocumentLayout(DocumentLayout layout)
 { 
     // Increase the count of pending DocumentLayout delegates
     _documentLayoutsPending++; 
     Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Input, 
            new DispatcherOperationCallback(UpdateDocumentLayoutDelegate),
            layout); 
 }
        public static string GetInformationAboutCurrentDocumentElement(Document currentDocument, DocumentLayout currentDocumentLayout, SubDocument currentSubDocument, DocumentPosition docPosition)
        {
            if (currentSubDocument.GetSubDocumentType() == SubDocumentType.TextBox)
            {
                return(TextBoxLayoutHelper.GetInformationAboutCurrentTextBox(currentSubDocument, currentDocumentLayout, docPosition));
            }
            if (currentSubDocument.GetSubDocumentType() == SubDocumentType.Main)
            {
                RangedLayoutElement tableCell = currentDocumentLayout.GetElement(docPosition, LayoutType.TableCell);
                if (tableCell != null)
                {
                    // collect information about TABLE CELL
                    return(DocumentElementLayoutHelper.GetInformationAboutCurrentTableCell(currentDocument, tableCell as LayoutTableCell));
                }

                RangedLayoutElement imageinline = currentDocumentLayout.GetElement(docPosition, LayoutType.InlinePictureBox);
                if (imageinline != null)
                {
                    // collect information about INLINE PICTURE
                    return(DocumentElementLayoutHelper.GetInformationAboutCurrentInlinePicture(imageinline as InlinePictureBox));
                }


                RangedLayoutElement floatingObjectAnchor = currentDocumentLayout.GetElement(docPosition, LayoutType.FloatingObjectAnchorBox);
                if (floatingObjectAnchor != null)
                {
                    // collect information about FLOATING OBJECT
                    return(DocumentElementLayoutHelper.GetInformationAboutCurrentFloatingObject(floatingObjectAnchor as FloatingObjectAnchorBox, currentDocumentLayout));
                }

                RangedLayoutElement regularTextBlock = currentDocumentLayout.GetElement(docPosition, LayoutType.PlainTextBox);
                if (regularTextBlock != null)
                {
                    // collect information about REGULAR TEXT BLOCK
                    return(DocumentElementLayoutHelper.GetInformationAboutRegularTextBlock(regularTextBlock as PlainTextBox, currentDocument));
                }
            }
            return("");
        }
Beispiel #26
0
        /// <summary>
        /// Creates the document.
        /// </summary>
        /// <param name="financialTransactionQry">The financial transaction qry.</param>
        /// <returns></returns>
        public Document RunReport()
        {
            UpdateProgress("Connecting...");

            // Login and setup options for REST calls
            RockConfig rockConfig = RockConfig.Load();

            _rockRestClient = new RockRestClient(rockConfig.RockBaseUrl);
            _rockRestClient.Login(rockConfig.Username, rockConfig.Password);

            // shouldn't happen, but just in case the StartDate isn't set, set it to the first day of the current year
            DateTime firstDayOfYear = new DateTime(DateTime.Now.Year, 1, 1);

            // note: if a specific person is specified, get them even if they don't have an address.
            _contributionStatementOptionsREST = new
            {
                StartDate  = Options.StartDate ?? firstDayOfYear,
                EndDate    = Options.EndDate,
                AccountIds = Options.AccountIds,
                IncludeIndividualsWithNoAddress = Options.PersonId.HasValue || Options.IncludeIndividualsWithNoAddress,
                DataViewId        = Options.DataViewId,
                PersonId          = Options.PersonId,
                OrderByPostalCode = true
            };

            var organizationAddressAttribute = _rockRestClient.GetData <List <Rock.Client.Attribute> >("api/attributes", "Key eq 'OrganizationAddress'").FirstOrDefault();

            if (organizationAddressAttribute != null)
            {
                var organizationAddressAttributeValue = _rockRestClient.GetData <List <Rock.Client.AttributeValue> >("api/AttributeValues", string.Format("AttributeId eq {0}", organizationAddressAttribute.Id)).FirstOrDefault();

                Guid locationGuid = Guid.Empty;
                if (Guid.TryParse(organizationAddressAttributeValue.Value, out locationGuid))
                {
                    _organizationAddressLocation = _rockRestClient.GetData <List <Rock.Client.Location> >("api/locations", string.Format("Guid eq guid'{0}'", locationGuid)).FirstOrDefault();
                }
            }

            // If we don't have a _organizationAddressLocation, just create an empty location
            _organizationAddressLocation = _organizationAddressLocation ?? new Rock.Client.Location();

            // setup report layout and events
            DocumentLayout report = new DocumentLayout(this.Options.LayoutFile);

            //// if there is an imgLogo and the path is "logo.jpg", use the logo specified in rockconfig.
            //// We have to read the layout as Xml first to figure out what the Path of the imgLogo
            XmlDocument layoutXmlDoc = new XmlDocument();

            layoutXmlDoc.Load(this.Options.LayoutFile);
            var imageNodes = layoutXmlDoc.GetElementsByTagName("image");

            foreach (var imageNode in imageNodes.OfType <XmlNode>())
            {
                string imagePath = imageNode.Attributes["path"].Value;
                string imageId   = imageNode.Attributes["id"].Value;
                if (imageId.Equals("imgLogo") && imagePath.Equals(RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase))
                {
                    Image imgLogo = report.GetReportElementById("imgLogo") as Image;
                    if (imgLogo != null)
                    {
                        try
                        {
                            if (!rockConfig.LogoFile.Equals(RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase))
                            {
                                imgLogo.ImageData = ceTe.DynamicPDF.Imaging.ImageData.GetImage(rockConfig.LogoFile);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Error loading Logo Image: " + rockConfig.LogoFile + "\n\n" + ex.Message);
                        }
                    }
                }
            }

            Query query = report.GetQueryById("OuterQuery");

            if (query == null)
            {
                throw new MissingReportElementException("Report requires a QueryElement named 'OuterQuery'");
            }

            query.OpeningRecordSet += mainQuery_OpeningRecordSet;

            Query orgInfoQuery = report.GetQueryById("OrgInfoQuery");

            if (orgInfoQuery == null)
            {
                throw new MissingReportElementException("Report requires a QueryElement named 'OrgInfoQuery'");
            }

            orgInfoQuery.OpeningRecordSet += orgInfoQuery_OpeningRecordSet;

            _accountSummaryQuery = report.GetQueryById("AccountSummaryQuery");

            if (_accountSummaryQuery == null)
            {
                // not required.  Just don't do anything if it isn't there
            }
            else
            {
                _accountSummaryQuery.OpeningRecordSet += delegate(object s, OpeningRecordSetEventArgs ee)
                {
                    // create a recordset for the _accountSummaryQuery which is the GroupBy summary of AccountName, Amount

                    /*
                     * The structure of _transactionsDataTable is
                     *
                     * DateTime TransactionDateTime
                     * string CurrencyTypeValueName
                     * string Summary (main transaction summary)
                     * DataTable Details {
                     *    int AccountId
                     *    string AccountName
                     *    string Summary (detail summary)
                     *    decimal Amount
                     * }
                     */

                    var detailsData = new DataTable();
                    detailsData.Columns.Add("AccountId", typeof(int));
                    detailsData.Columns.Add("AccountName");
                    detailsData.Columns.Add("Amount", typeof(decimal));

                    foreach (var details in _transactionsDataTable.AsEnumerable().Select(a => (a["Details"] as DataTable)))
                    {
                        foreach (var row in details.AsEnumerable())
                        {
                            detailsData.Rows.Add(row["AccountId"], row["AccountName"], row["Amount"]);
                        }
                    }

                    var summaryTable = detailsData.AsEnumerable().GroupBy(g => g["AccountId"]).Select(a => new
                    {
                        AccountName = a.Max(x => x["AccountName"].ToString()),
                        Amount      = a.Sum(x => decimal.Parse(x["Amount"].ToString()))
                    }).OrderBy(o => o.AccountName);

                    ee.RecordSet = new EnumerableRecordSet(summaryTable);
                };
            }

            UpdateProgress("Getting Data...");

            // get outer query data from Rock database via REST now vs in mainQuery_OpeningRecordSet to make sure we have data
            DataSet personGroupAddressDataSet = _rockRestClient.PostDataWithResult <object, DataSet>("api/FinancialTransactions/GetContributionPersonGroupAddress", _contributionStatementOptionsREST);

            _personGroupAddressDataTable = personGroupAddressDataSet.Tables[0];
            RecordCount = _personGroupAddressDataTable.Rows.Count;

            if (RecordCount > 0)
            {
                Document doc = report.Run();
                return(doc);
            }
            else
            {
                return(null);
            }
        }
        // get information about a current floating object
        public static string GetInformationAboutCurrentFloatingObject(FloatingObjectAnchorBox currentObjectAnchor, DocumentLayout currentLayout)
        {
            LayoutFloatingObject currentFloatingObject = currentObjectAnchor.FloatingObjectBox;
            string returnedInformation = "";

            if (currentFloatingObject.Type == LayoutType.FloatingPicture)
            {
                returnedInformation = "!A FLOATING PICTURE IS SELECTED!\r\n";
            }
            else if (currentFloatingObject.Type == LayoutType.TextBox)
            {
                returnedInformation = "!A TEXT BOX IS SELECTED!\r\n";
            }

            returnedInformation += String.Format("Anchor location: {0}\r\n", currentObjectAnchor.Bounds.Location);
            returnedInformation += String.Format("Object bounds: {0}\r\n", currentFloatingObject.Bounds);
            returnedInformation += String.Format("Rotation: {0}\r\n", currentFloatingObject.RotationAngle);

            if (currentFloatingObject.Type == LayoutType.TextBox)
            {
                LayoutTextBox currentTextBox = currentFloatingObject as LayoutTextBox;
                returnedInformation += String.Format("\r\n!!Content information:\r\n");
                returnedInformation += TextBoxLayoutHelper.GetInformationAboutCurrentTextBoxContent(currentTextBox, currentLayout);
            }
            else if (currentFloatingObject.Type == LayoutType.FloatingPicture)
            {
                LayoutFloatingPicture currentFloatingPicture = currentFloatingObject as LayoutFloatingPicture;
                returnedInformation += String.Format("\r\n!!Image properties:\r\n");
                returnedInformation += GetInformationAboutOfficeImage(currentFloatingPicture.Image);
            }

            return(returnedInformation);
        }
        /// <summary>
        /// Creates the document.
        /// </summary>
        /// <param name="financialTransactionQry">The financial transaction qry.</param>
        /// <returns></returns>
        public Document RunReport()
        {
            UpdateProgress( "Connecting..." );

            // Login and setup options for REST calls
            RockConfig rockConfig = RockConfig.Load();

            _rockRestClient = new RockRestClient( rockConfig.RockBaseUrl );
            _rockRestClient.Login( rockConfig.Username, rockConfig.Password );

            // shouldn't happen, but just in case the StartDate isn't set, set it to the first day of the current year
            DateTime firstDayOfYear = new DateTime( DateTime.Now.Year, 1, 1 );

            // note: if a specific person is specified, get them even if they don't have an address. 
            _contributionStatementOptionsREST = new Rock.Net.RestParameters.ContributionStatementOptions
            {
                StartDate = Options.StartDate ?? firstDayOfYear,
                EndDate = Options.EndDate,
                AccountIds = Options.AccountIds,
                IncludeIndividualsWithNoAddress = Options.PersonId.HasValue || Options.IncludeIndividualsWithNoAddress,
                PersonId = Options.PersonId,
                OrderByPostalCode = true
            };

            var organizationAddressAttribute = _rockRestClient.GetData<List<Rock.Client.Attribute>>( "api/attributes", "Key eq 'OrganizationAddress'" ).FirstOrDefault();
            if ( organizationAddressAttribute != null )
            {
                var organizationAddressAttributeValue = _rockRestClient.GetData<List<Rock.Client.AttributeValue>>( "api/AttributeValues", string.Format( "AttributeId eq {0}", organizationAddressAttribute.Id ) ).FirstOrDefault();

                Guid locationGuid = Guid.Empty;
                if ( Guid.TryParse( organizationAddressAttributeValue.Value, out locationGuid ) )
                {
                    _organizationAddressLocation = _rockRestClient.GetData<List<Rock.Client.Location>>( "api/locations", string.Format( "Guid eq guid'{0}'", locationGuid ) ).FirstOrDefault();
                }
            }

            // If we don't have a _organizationAddressLocation, just create an empty location
            _organizationAddressLocation = _organizationAddressLocation ?? new Rock.Client.Location();

            // setup report layout and events
            DocumentLayout report = new DocumentLayout( this.Options.LayoutFile );

            //// if there is an imgLogo and the path is "logo.jpg", use the logo specified in rockconfig.  
            //// We have to read the layout as Xml first to figure out what the Path of the imgLogo
            XmlDocument layoutXmlDoc = new XmlDocument();
            layoutXmlDoc.Load( this.Options.LayoutFile );
            var imageNodes = layoutXmlDoc.GetElementsByTagName( "image" );
            foreach ( var imageNode in imageNodes.OfType<XmlNode>() )
            {
                string imagePath = imageNode.Attributes["path"].Value;
                string imageId = imageNode.Attributes["id"].Value;
                if ( imageId.Equals( "imgLogo" ) && imagePath.Equals( RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase ) )
                {
                    Image imgLogo = report.GetReportElementById( "imgLogo" ) as Image;
                    if ( imgLogo != null )
                    {
                        try
                        {
                            if ( !rockConfig.LogoFile.Equals( RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase ) )
                            {
                                imgLogo.ImageData = ceTe.DynamicPDF.Imaging.ImageData.GetImage( rockConfig.LogoFile );
                            }
                        }
                        catch ( Exception ex )
                        {
                            throw new Exception( "Error loading Logo Image: " + rockConfig.LogoFile + "\n\n" + ex.Message );
                        }
                    }
                }
            }

            Query query = report.GetQueryById( "OuterQuery" );
            if ( query == null )
            {
                throw new MissingReportElementException( "Report requires a QueryElement named 'OuterQuery'" );
            }

            query.OpeningRecordSet += mainQuery_OpeningRecordSet;

            Query orgInfoQuery = report.GetQueryById( "OrgInfoQuery" );
            if ( orgInfoQuery == null )
            {
                throw new MissingReportElementException( "Report requires a QueryElement named 'OrgInfoQuery'" );
            }

            orgInfoQuery.OpeningRecordSet += orgInfoQuery_OpeningRecordSet;

            _accountSummaryQuery = report.GetQueryById( "AccountSummaryQuery" );

            if ( _accountSummaryQuery == null )
            {
                // not required.  Just don't do anything if it isn't there
            }
            else
            {
                _accountSummaryQuery.OpeningRecordSet += delegate( object s, OpeningRecordSetEventArgs ee )
                {
                    // create a recordset for the _accountSummaryQuery which is the GroupBy summary of AccountName, Amount
                    /*
                     The structure of _transactionsDataTable is
                     
                     DateTime TransactionDateTime
                     string CurrencyTypeValueName
                     string Summary (main transaction summary)
                     DataTable Details {
                          int AccountId
                          string AccountName
                          string Summary (detail summary)
                          decimal Amount
                     }
                     */

                    var detailsData = new DataTable();
                    detailsData.Columns.Add( "AccountId", typeof( int ) );
                    detailsData.Columns.Add( "AccountName" );
                    detailsData.Columns.Add( "Amount", typeof( decimal ) );

                    foreach ( var details in _transactionsDataTable.AsEnumerable().Select( a => ( a["Details"] as DataTable ) ) )
                    {
                        foreach ( var row in details.AsEnumerable() )
                        {
                            detailsData.Rows.Add( row["AccountId"], row["AccountName"], row["Amount"] );
                        }
                    }

                    var summaryTable = detailsData.AsEnumerable().GroupBy( g => g["AccountId"] ).Select( a => new
                    {
                        AccountName = a.Max( x => x["AccountName"].ToString() ),
                        Amount = a.Sum( x => decimal.Parse( x["Amount"].ToString() ) )
                    } ).OrderBy( o => o.AccountName );

                    ee.RecordSet = new EnumerableRecordSet( summaryTable );
                };
            }

            UpdateProgress( "Getting Data..." );

            // get outer query data from Rock database via REST now vs in mainQuery_OpeningRecordSet to make sure we have data
            DataSet personGroupAddressDataSet = _rockRestClient.PostDataWithResult<Rock.Net.RestParameters.ContributionStatementOptions, DataSet>( "api/FinancialTransactions/GetContributionPersonGroupAddress", _contributionStatementOptionsREST );
            _personGroupAddressDataTable = personGroupAddressDataSet.Tables[0];
            RecordCount = _personGroupAddressDataTable.Rows.Count;

            if ( RecordCount > 0 )
            {
                Document doc = report.Run();
                return doc;
            }
            else
            {
                return null;
            }
        }
Beispiel #29
0
        /// <summary>
        /// Creates the document.
        /// </summary>
        /// <param name="financialTransactionQry">The financial transaction qry.</param>
        /// <returns></returns>
        public Document RunReport()
        {
            UpdateProgress( "Connecting..." );

            // Login and setup options for REST calls
            RockConfig rockConfig = RockConfig.Load();

            _rockRestClient = new RockRestClient( rockConfig.RockBaseUrl );
            _rockRestClient.Login( rockConfig.Username, rockConfig.Password );

            _contributionStatementOptionsREST = new Rock.Net.RestParameters.ContributionStatementOptions
            {
                StartDate = Options.StartDate,
                EndDate = Options.EndDate,
                AccountIds = Options.AccountIds,
                PersonId = Options.PersonId,
                OrderByZipCode = true
            };

            var organizationAddressAttribute = _rockRestClient.GetData<List<Rock.Model.Attribute>>( "api/attributes", "Key eq 'OrganizationAddress'" ).FirstOrDefault();
            if ( organizationAddressAttribute != null )
            {
                Guid locationGuid = Guid.Empty;
                if ( Guid.TryParse( organizationAddressAttribute.DefaultValue, out locationGuid ) )
                {
                    _organizationAddressLocation = _rockRestClient.GetDataByGuid<Rock.Model.Location>( "api/locations", locationGuid );
                }
            }

            // If we don't have a _organizationAddressLocation, just create an empty location
            _organizationAddressLocation = _organizationAddressLocation ?? new Rock.Model.Location();

            // setup report layout and events
            DocumentLayout report = new DocumentLayout( this.Options.LayoutFile );

            //// if there is an imgLogo and the path is "logo.jpg", use the logo specified in rockconfig.  
            //// We have to read the layout as Xml first to figure out what the Path of the imgLogo
            XmlDocument layoutXmlDoc = new XmlDocument();
            layoutXmlDoc.Load( this.Options.LayoutFile );
            var imageNodes = layoutXmlDoc.GetElementsByTagName( "image" );
            foreach ( var imageNode in imageNodes.OfType<XmlNode>() )
            {
                string imagePath = imageNode.Attributes["path"].Value;
                string imageId =imageNode.Attributes["id"].Value;
                if (imageId.Equals("imgLogo" ) &&  imagePath.Equals( RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase )  )
                {
                    Image imgLogo = report.GetReportElementById( "imgLogo" ) as Image;
                    if ( imgLogo != null )
                    {
                        try
                        {
                            if ( !rockConfig.LogoFile.Equals( RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase ) )
                            {
                                imgLogo.ImageData = ceTe.DynamicPDF.Imaging.ImageData.GetImage( rockConfig.LogoFile );
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception( "Error loading Logo Image: " + rockConfig.LogoFile + "\n\n" + ex.Message);
                        }
                    }
                }
            }


            Query query = report.GetQueryById( "OuterQuery" );
            if ( query == null )
            {
                throw new MissingReportElementException( "Report requires a QueryElement named 'OuterQuery'" );
            }

            query.OpeningRecordSet += mainQuery_OpeningRecordSet;

            Query orgInfoQuery = report.GetQueryById( "OrgInfoQuery" );
            if ( orgInfoQuery == null )
            {
                throw new MissingReportElementException( "Report requires a QueryElement named 'OrgInfoQuery'" );
            }

            orgInfoQuery.OpeningRecordSet += orgInfoQuery_OpeningRecordSet;

            _accountSummaryQuery = report.GetQueryById( "AccountSummaryQuery" );

            if ( _accountSummaryQuery == null )
            {
                // not required.  Just don't do anything if it isn't there
            }
            else
            {
                _accountSummaryQuery.OpeningRecordSet += delegate( object s, OpeningRecordSetEventArgs ee )
                {
                    // create a recordset for the _accountSummaryQuery which is the GroupBy summary of AccountName, Amount
                    var summaryTable = _transactionsDataTable.AsEnumerable().GroupBy( g => g["AccountId"] ).Select( a => new
                    {
                        AccountName = a.Max(x => x["AccountName"].ToString()),
                        Amount = a.Sum( x => decimal.Parse( x["Amount"].ToString() ) )
                    } ).OrderBy( o => o.AccountName );

                    ee.RecordSet = new EnumerableRecordSet( summaryTable );
                };
            }

            UpdateProgress( "Getting Data..." );

            // get outer query data from Rock database via REST now vs in mainQuery_OpeningRecordSet to make sure we have data
            DataSet personGroupAddressDataSet = _rockRestClient.PostDataWithResult<Rock.Net.RestParameters.ContributionStatementOptions, DataSet>( "api/FinancialTransactions/GetContributionPersonGroupAddress", _contributionStatementOptionsREST );
            _personGroupAddressDataTable = personGroupAddressDataSet.Tables[0];
            RecordCount = _personGroupAddressDataTable.Rows.Count;

            if ( RecordCount > 0 )
            {
                Document doc = report.Run();
                return doc;
            }
            else
            {
                return null;
            }
        }