### Install Dependencies with Poetry Source: https://github.com/jobsta/reportbro-lib/blob/master/CONTRIBUTING.md Install the project dependencies using Poetry, the recommended dependency management tool for ReportBro Lib. ```bash poetry install ``` -------------------------------- ### Install reportbro-lib Source: https://github.com/jobsta/reportbro-lib/blob/master/README.rst Install the ReportBro library using pip. Refer to the framework API documentation for more information on configuration and usage. ```shell pip install reportbro-lib ``` -------------------------------- ### Flask Web API for Report Generation Source: https://context7.com/jobsta/reportbro-lib/llms.txt A complete Flask endpoint example that accepts report definitions and data, generates PDF or XLSX, and streams the output. This pattern is typical for server-side ReportBro usage with a frontend designer. ```python import json from flask import Flask, request, Response from reportbro import Report, ReportBroError app = Flask(__name__) @app.route('/api/report/generate', methods=['POST']) def generate_report(): body = request.get_json() report_definition = body.get('report') data = body.get('data', {}) output_format = body.get('outputFormat', 'pdf') # 'pdf' or 'xlsx' report = Report( report_definition=report_definition, data=data, is_test_data=False, page_limit=500, allow_external_image=True, ) if report.errors: return {'errors': report.errors}, 400 try: if output_format == 'xlsx': file_data = report.generate_xlsx() mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' filename = 'report.xlsx' else: file_data = report.generate_pdf() mime = 'application/pdf' filename = 'report.pdf' except ReportBroError as e: return {'error': e.error['msg_key'], 'detail': e.error.get('info')}, 422 return Response( file_data, mimetype=mime, headers={'Content-Disposition': f'attachment; filename="{filename}"'} , ) if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Instantiate Report with Basic Options Source: https://context7.com/jobsta/reportbro-lib/llms.txt Loads a report definition and runtime data to create a Report instance. Check report.errors for validation issues before rendering. ```python import json from reportbro import Report # Load the report definition exported from ReportBro Designer with open('invoice.json', 'r') as f: report_definition = json.load(f) # Runtime data — keys must match parameter names defined in the Designer data = { 'invoice_number': 'INV-2024-001', 'invoice_date': '2024-05-01', 'customer_name': 'Acme Corp', 'items': [ {'description': 'Widget A', 'quantity': 10, 'unit_price': '9.99'}, {'description': 'Widget B', 'quantity': 5, 'unit_price': '24.50'}, ], 'tax_rate': '0.08', } # Basic instantiation report = Report( report_definition=report_definition, data=data, is_test_data=False, # False = production data page_limit=500, # max pages (prevents runaway loops) ) # Check for validation errors before rendering if report.errors: for err in report.errors: print(f"Error: {err['msg_key']} on field '{err['field']}' (object {err['object_id']})") else: print("Report ready to render.") ``` -------------------------------- ### Report.__init__ - Advanced Options Source: https://context7.com/jobsta/reportbro-lib/llms.txt Provides advanced options for report instantiation, including custom fonts, image permissions, encoding strategies, spreadsheet conversion options, and user-defined expression functions. ```APIDOC ## Report.__init__ - Advanced Options ### Description Provides advanced options for report instantiation, including custom fonts, image permissions, encoding strategies, spreadsheet conversion options, and user-defined expression functions. ### Parameters - **report_definition** (dict) - Required - The report definition loaded from ReportBro Designer. - **data** (dict) - Required - Runtime data for the report. Keys must match parameter names defined in the Designer. - **is_test_data** (bool) - Optional - Defaults to False. Set to True for test data. - **additional_fonts** (list) - Optional - List of dictionaries specifying custom fonts. - **page_limit** (int) - Optional - Maximum number of pages to prevent runaway loops. - **request_headers** (dict) - Optional - Headers to use when fetching remote images. - **encode_error_handling** (str) - Optional - Error handling strategy for encoding ('strict', 'ignore', 'replace'). - **core_fonts_encoding** (str) - Optional - Encoding for core fonts. - **spreadsheet_options** (dict) - Optional - Options for spreadsheet generation (e.g., `strings_to_numbers`, `strings_to_formulas`, `strings_to_urls`). - **allow_local_image** (bool) - Optional - Allow local file path image sources. - **allow_external_image** (bool) - Optional - Allow remote HTTP(S) image sources. - **custom_functions** (dict) - Optional - Dictionary of user-defined functions available in expressions. ``` -------------------------------- ### Report.__init__ - Basic Instantiation Source: https://context7.com/jobsta/reportbro-lib/llms.txt Instantiates a report by combining a JSON report definition with runtime data. Validates parameters, processes data types, evaluates expressions, and prepares all document elements for rendering. The resulting object exposes `generate_pdf()` and `generate_xlsx()` methods. ```APIDOC ## Report.__init__ - Basic Instantiation ### Description Instantiates a report by combining a JSON report definition with runtime data. Validates parameters, processes data types, evaluates expressions, and prepares all document elements for rendering. The resulting object exposes `generate_pdf()` and `generate_xlsx()` methods. ### Parameters - **report_definition** (dict) - Required - The report definition loaded from ReportBro Designer. - **data** (dict) - Required - Runtime data for the report. Keys must match parameter names defined in the Designer. - **is_test_data** (bool) - Optional - Defaults to False. Set to True for test data. - **page_limit** (int) - Optional - Maximum number of pages to prevent runaway loops. ``` -------------------------------- ### Instantiate Report with Advanced Options Source: https://context7.com/jobsta/reportbro-lib/llms.txt Configures a Report instance with custom fonts, image handling, encoding, spreadsheet options, and user-defined expression functions. Ensure custom fonts are correctly path-ed. ```python import json from reportbro import Report with open('report.json', 'r') as f: report_definition = json.load(f) data = {'title': 'Annual Summary', 'year': '2024'} # Custom expression function available inside Designer expressions def double(x): return x * 2 report = Report( report_definition=report_definition, data=data, is_test_data=False, additional_fonts=[ { 'value': 'opensans', 'filename': 'fonts/OpenSans-Regular.ttf', 'bold_filename': 'fonts/OpenSans-Bold.ttf', 'italic_filename': 'fonts/OpenSans-Italic.ttf', 'bold_italic_filename': 'fonts/OpenSans-BoldItalic.ttf', } ], page_limit=1000, request_headers={'User-Agent': 'MyApp/1.0'}, # for fetching remote images encode_error_handling='replace', # 'strict' | 'ignore' | 'replace' core_fonts_encoding='windows-1252', spreadsheet_options={ 'strings_to_numbers': False, 'strings_to_formulas': True, 'strings_to_urls': True, }, allow_local_image=True, # allow file:path image sources allow_external_image=True, # allow http(s):// image sources (downloaded at render time) custom_functions={'double': double}, ) if not report.errors: print("Report with advanced options ready.") ``` -------------------------------- ### Run All Tests with Pytest Source: https://github.com/jobsta/reportbro-lib/blob/master/tests/README.md Execute the entire test suite using pytest. Ensure you are in the root directory of the project. ```bash poetry run pytest ``` -------------------------------- ### Clone ReportBro Lib Repository Source: https://github.com/jobsta/reportbro-lib/blob/master/CONTRIBUTING.md Clone the ReportBro Lib repository to your local machine after forking it. Navigate into the cloned directory to begin development. ```bash git clone [https://github.com/YOUR_USERNAME/reportbro-lib.git](https://github.com/YOUR_USERNAME/reportbro-lib.git) cd reportbro-lib ``` -------------------------------- ### Push Branch to Origin Source: https://github.com/jobsta/reportbro-lib/blob/master/CONTRIBUTING.md After making changes and committing them, push your local branch to your forked repository on GitHub. ```bash git push origin your-branch-name ``` -------------------------------- ### Create a New Feature Branch Source: https://github.com/jobsta/reportbro-lib/blob/master/CONTRIBUTING.md Create a new branch for your feature development, based on the primary 'master' branch. Alternatively, use a 'bugfix' prefix for issue-related fixes. ```bash git checkout -b feature/your-awesome-feature ``` ```bash git checkout -b bugfix/issue-number-short-description ``` -------------------------------- ### Report.generate_pdf Source: https://context7.com/jobsta/reportbro-lib/llms.txt Renders the report and returns the PDF as bytes, or writes it to a file if filename is provided. The add_watermark flag overlays a ReportBro watermark. ```APIDOC ## `Report.generate_pdf` — Render to PDF Renders the report and returns the PDF as `bytes`, or writes it to a file if `filename` is provided. The `add_watermark` flag overlays a ReportBro watermark (used for the free/AGPL edition). ### Method Signature `generate_pdf(filename: Optional[str] = None, add_watermark: bool = False) -> bytes` ### Parameters - **filename** (Optional[str]): If provided, the PDF will be written to this file path. Otherwise, the PDF is returned as bytes. - **add_watermark** (bool): If True, a ReportBro watermark is added to the PDF. Defaults to False. ### Returns - `bytes`: The generated PDF content if `filename` is not provided. ### Example Usage ```python import json from reportbro import Report with open('invoice.json', 'r') as f: report_definition = json.load(f) data = {'customer': 'Jane Doe', 'total': '199.99'} report = Report(report_definition=report_definition, data=data) if not report.errors: # Return as bytes (e.g. to send over HTTP) pdf_bytes = report.generate_pdf() print(f"Generated PDF: {len(pdf_bytes)} bytes") # Or save directly to a file report.generate_pdf(filename='output/invoice.pdf') # Page count is available after generation print(f"Total pages: {report.get_page_count()}") else: for err in report.errors: print(f"Validation error: {err}") ``` ``` -------------------------------- ### Generate XLSX from Report Definition Source: https://context7.com/jobsta/reportbro-lib/llms.txt Renders a report as an XLSX spreadsheet, returning bytes or saving to a file. The `spreadsheet_options` can be used to configure parsing behavior, such as converting strings to numbers. ```python import json from reportbro import Report with open('sales_report.json', 'r') as f: report_definition = json.load(f) data = { 'report_title': 'Q1 Sales', 'rows': [ {'region': 'North', 'sales': '45200.00'}, {'region': 'South', 'sales': '38750.00'}, {'region': 'East', 'sales': '52100.00'}, ] } report = Report( report_definition=report_definition, data=data, spreadsheet_options={'strings_to_numbers': True}, ) if not report.errors: # Return bytes (stream to client, store in S3, etc.) xlsx_bytes = report.generate_xlsx() print(f"Generated XLSX: {len(xlsx_bytes)} bytes") # Or save to disk report.generate_xlsx(filename='output/sales_q1.xlsx') ``` -------------------------------- ### Generate PDF from Report Definition Source: https://context7.com/jobsta/reportbro-lib/llms.txt Renders a report to PDF, returning bytes or saving to a file. The `add_watermark` flag can overlay a ReportBro watermark. Page count is available after generation. ```python import json from reportbro import Report with open('invoice.json', 'r') as f: report_definition = json.load(f) data = {'customer': 'Jane Doe', 'total': '199.99'} report = Report(report_definition=report_definition, data=data) if not report.errors: # Return as bytes (e.g. to send over HTTP) pdf_bytes = report.generate_pdf() print(f"Generated PDF: {len(pdf_bytes)} bytes") # Or save directly to a file report.generate_pdf(filename='output/invoice.pdf') # Page count is available after generation print(f"Total pages: {report.get_page_count()}") else: for err in report.errors: print(f"Validation error: {err}") ``` -------------------------------- ### Handle ReportBro Errors in Python Source: https://context7.com/jobsta/reportbro-lib/llms.txt Demonstrates how to catch and process ReportBroError and ReportBroInternalError exceptions during report generation. This is useful for identifying data-level or configuration errors. ```python import json from reportbro import Report, ReportBroError, ReportBroInternalError with open('report.json', 'r') as f: report_definition = json.load(f) data = {'amount': 'not-a-number'} # intentionally wrong type try: report = Report( report_definition=report_definition, data=data, is_test_data=False, ) if report.errors: # Soft validation errors (element-level) for err in report.errors: # err is a dict: {msg_key, object_id, field, info, context} print(f"[{err['msg_key']}] field={err['field']} id={err['object_id']} info={err['info']}") else: pdf = report.generate_pdf() except ReportBroError as e: # Hard error during rendering (e.g. image download failed, glyph missing) print(f"Render error: {e.error['msg_key']}, info: {e.error.get('info')}") except ReportBroInternalError as e: # Configuration/programming error (e.g. invalid locale string) print(f"Internal error: {e.msg}") ``` -------------------------------- ### Report.generate_xlsx Source: https://context7.com/jobsta/reportbro-lib/llms.txt Renders the report as an XLSX spreadsheet and returns bytes, or writes to a file. ```APIDOC ## `Report.generate_xlsx` — Render to Excel Renders the report as an XLSX spreadsheet and returns `bytes`, or writes to a file. ### Method Signature `generate_xlsx(filename: Optional[str] = None) -> bytes` ### Parameters - **filename** (Optional[str]): If provided, the XLSX will be written to this file path. Otherwise, the XLSX is returned as bytes. ### Returns - `bytes`: The generated XLSX content if `filename` is not provided. ### Example Usage ```python import json from reportbro import Report with open('sales_report.json', 'r') as f: report_definition = json.load(f) data = { 'report_title': 'Q1 Sales', 'rows': [ {'region': 'North', 'sales': '45200.00'}, {'region': 'South', 'sales': '38750.00'}, {'region': 'East', 'sales': '52100.00'}, ] } report = Report( report_definition=report_definition, data=data, spreadsheet_options={'strings_to_numbers': True}, ) if not report.errors: # Return bytes (stream to client, store in S3, etc.) xlsx_bytes = report.generate_xlsx() print(f"Generated XLSX: {len(xlsx_bytes)} bytes") # Or save to disk report.generate_xlsx(filename='output/sales_q1.xlsx') ``` ``` -------------------------------- ### Report.verify Source: https://context7.com/jobsta/reportbro-lib/llms.txt Traverses all report elements and raises ReportBroError on the first invalid element. Useful for pre-flight validation. ```APIDOC ## `Report.verify` — Validate Without Rendering Traverses all report elements and raises `ReportBroError` on the first invalid element. Useful for pre-flight validation in a web API that accepts report definitions from clients. ### Method Signature `verify()` ### Raises - `ReportBroError`: If an invalid element is found during traversal. ### Example Usage ```python import json from reportbro import Report, ReportBroError with open('user_uploaded_report.json', 'r') as f: report_definition = json.load(f) data = {'name': 'Test'} report = Report(report_definition=report_definition, data=data, is_test_data=True) if report.errors: print("Report definition has errors:", report.errors) else: try: report.verify() print("Report definition is valid.") except ReportBroError as e: print(f"Element validation failed: {e.error['msg_key']} " f"on field '{e.error['field']}' (object {e.error['object_id']})") ``` ``` -------------------------------- ### Run Specific Test with Pytest Source: https://github.com/jobsta/reportbro-lib/blob/master/tests/README.md Run a specific test or a group of tests using the `-k` parameter with pytest. This is useful for targeting individual test cases. ```bash poetry run pytest -k test_report_demo_render[invoice] ``` -------------------------------- ### Extract Test Data from Report Parameters Source: https://context7.com/jobsta/reportbro-lib/llms.txt Static method to extract test data embedded in a report definition's parameters. Returns a ready-to-use data dictionary. Supports Designer version >= 3.0 test data format. Set `include_image_data` to `False` to skip base64 image blobs. ```python import json from reportbro import Report with open('invoice.json', 'r') as f: report_definition = json.load(f) # Extract test data stored inside the report definition parameters test_data = Report.get_test_data( parameter_list=report_definition['parameters'], include_image_data=True, # set False to skip base64 image blobs ) print("Extracted test data keys:", list(test_data.keys())) # e.g. {'customer_name': 'John Doe', 'items': [...], 'logo': 'data:image/png;base64,...'} # Render with the extracted test data report = Report( report_definition=report_definition, data=test_data, is_test_data=True, ) pdf_bytes = report.generate_pdf() print(f"Test PDF generated: {len(pdf_bytes)} bytes") ``` -------------------------------- ### Set PDF/XLSX Creation Date Source: https://context7.com/jobsta/reportbro-lib/llms.txt Sets an explicit creation date embedded in the generated PDF or XLSX metadata. Accepts a datetime string in `YYYY-MM-DD HH:MM:SS` format. Useful for reproducible output. ```python import json from reportbro import Report with open('report.json', 'r') as f: report_definition = json.load(f) data = {'title': 'Archived Report'} report = Report(report_definition=report_definition, data=data) # Set a fixed creation date before rendering report.set_creation_date('2024-01-15 09:30:00') pdf_bytes = report.generate_pdf() # The PDF metadata will show creation date: 2024-01-15 09:30:00 ``` -------------------------------- ### Regenerate Test Report Output Source: https://github.com/jobsta/reportbro-lib/blob/master/tests/README.md Regenerate PDF and XLSX output for available tests. This script is useful when report definitions or data change. ```bash poetry run scripts/regenerate_test_report_output.py [-g GROUP_NAME] [-r REPORT_NAME] [-k] ``` -------------------------------- ### Report.set_creation_date Source: https://context7.com/jobsta/reportbro-lib/llms.txt Sets an explicit creation date embedded in the generated PDF or XLSX metadata. Useful for reproducible output. ```APIDOC ## `Report.set_creation_date` — Set PDF/XLSX Creation Date Sets an explicit creation date embedded in the generated PDF or XLSX metadata. Accepts a datetime string in `YYYY-MM-DD HH:MM:SS` format. Useful for reproducible output (e.g. testing, archiving). ### Method Signature `set_creation_date(creation_date: str)` ### Parameters - **creation_date** (str): The date and time string in `YYYY-MM-DD HH:MM:SS` format. ### Example Usage ```python import json from reportbro import Report with open('report.json', 'r') as f: report_definition = json.load(f) data = {'title': 'Archived Report'} report = Report(report_definition=report_definition, data=data) # Set a fixed creation date before rendering report.set_creation_date('2024-01-15 09:30:00') pdf_bytes = report.generate_pdf() # The PDF metadata will show creation date: 2024-01-15 09:30:00 ``` ``` -------------------------------- ### Report.get_test_data Source: https://context7.com/jobsta/reportbro-lib/llms.txt Static method that extracts test data embedded in a report definition's parameters. Returns a ready-to-use data dict. ```APIDOC ## `Report.get_test_data` — Extract Test Data from Parameters Static method that extracts test data embedded in a report definition's parameters (set via ReportBro Designer). Returns a ready-to-use data dict. Supports Designer version >= 3.0 test data format. ### Method Signature `get_test_data(parameter_list: list, include_image_data: bool = False) -> dict` ### Parameters - **parameter_list** (list): A list of parameters from the report definition, typically `report_definition['parameters']`. - **include_image_data** (bool): Set to True to include base64 encoded image blobs in the test data. Defaults to False. ### Returns - `dict`: A dictionary containing the extracted test data. ### Example Usage ```python import json from reportbro import Report with open('invoice.json', 'r') as f: report_definition = json.load(f) # Extract test data stored inside the report definition parameters test_data = Report.get_test_data( parameter_list=report_definition['parameters'], include_image_data=True, # set False to skip base64 image blobs ) print("Extracted test data keys:", list(test_data.keys())) # e.g. {'customer_name': 'John Doe', 'items': [...], 'logo': 'data:image/png;base64,...'} # Render with the extracted test data report = Report( report_definition=report_definition, data=test_data, is_test_data=True, ) pdf_bytes = report.generate_pdf() print(f"Test PDF generated: {len(pdf_bytes)} bytes") ``` ``` -------------------------------- ### Validate Report Definition Without Rendering Source: https://context7.com/jobsta/reportbro-lib/llms.txt Traverses report elements to validate them without rendering. Raises `ReportBroError` on the first invalid element. Useful for pre-flight validation in web APIs. ```python import json from reportbro import Report, ReportBroError with open('user_uploaded_report.json', 'r') as f: report_definition = json.load(f) data = {'name': 'Test'} report = Report(report_definition=report_definition, data=data, is_test_data=True) if report.errors: print("Report definition has errors:", report.errors) else: try: report.verify() print("Report definition is valid.") except ReportBroError as e: print(f"Element validation failed: {e.error['msg_key']} " f"on field '{e.error['field']}' (object {e.error['object_id']})") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.