function get_pdf_generator
Factory function that creates and initializes a PDFGenerator instance with registered fonts and optional custom style initialization, using a non-standard instantiation pattern to bypass __init__.
/tf/active/vicechatdev/CDocs/utils/pdf_utils.py
2188 - 2220
moderate
Purpose
This function provides a controlled way to instantiate PDFGenerator objects, particularly useful for avoiding style initialization conflicts when styles have already been registered. It manually sets up the generator's attributes, registers fonts, and conditionally initializes custom styles based on the skip_styles parameter. This is especially useful in testing scenarios or when multiple PDFGenerator instances need to be created without re-registering styles.
Source Code
def get_pdf_generator(skip_styles: bool = False) -> PDFGenerator:
"""
Get a PDFGenerator instance with optional style initialization skipping.
Parameters
----------
skip_styles : bool
Whether to skip custom style initialization to avoid errors
Returns
-------
PDFGenerator
Initialized PDF generator
"""
generator = PDFGenerator.__new__(PDFGenerator)
# Set default attributes
generator.styles = getSampleStyleSheet()
generator.font_dir = settings.FONT_DIR
generator.logo_path = settings.LOGO_PATH
# Register fonts
generator._register_fonts(generator.font_dir)
# Initialize styles only if not skipping
if not skip_styles:
try:
generator._initialize_custom_styles()
except KeyError as e:
# Style already exists, use existing styles
logger.warning(f"Using existing styles due to conflict: {e}")
return generator
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
skip_styles |
bool | False | positional_or_keyword |
Parameter Details
skip_styles: Boolean flag that controls whether custom style initialization should be skipped. When True, only default ReportLab styles are used, avoiding potential KeyError exceptions from duplicate style registration. When False (default), attempts to initialize custom styles and falls back gracefully if conflicts occur. Use True when you know styles are already registered or want to use only default styles.
Return Value
Type: PDFGenerator
Returns a fully initialized PDFGenerator instance with registered fonts and styles. The instance has its styles attribute set to ReportLab's sample stylesheet, font_dir and logo_path configured from settings, and fonts registered. If skip_styles is False and no conflicts occur, custom styles are also initialized. The returned object is ready to generate PDF documents.
Dependencies
reportlabCDocs
Required Imports
from reportlab.lib.styles import getSampleStyleSheet
from CDocs.config import settings
Usage Example
# Basic usage with default style initialization
generator = get_pdf_generator()
# Usage skipping custom styles (useful for testing or avoiding conflicts)
generator = get_pdf_generator(skip_styles=True)
# Use the generator to create PDFs
pdf_content = generator.generate_report(data={'title': 'My Report', 'content': 'Report content'})
# When creating multiple instances in the same session
generator1 = get_pdf_generator()
generator2 = get_pdf_generator(skip_styles=True) # Skip to avoid style re-registration
Best Practices
- Use skip_styles=True when creating multiple PDFGenerator instances in the same process to avoid style registration conflicts
- Ensure settings.FONT_DIR and settings.LOGO_PATH are properly configured before calling this function
- The function uses __new__ to bypass normal __init__ constructor, which is an advanced pattern - understand the PDFGenerator class structure before modifying
- The function gracefully handles KeyError exceptions during style initialization, logging warnings instead of failing
- Consider using skip_styles=True in unit tests to isolate style-related issues
- The returned generator is stateful - create new instances for concurrent PDF generation operations
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class PDFGenerator 53.1% similar
-
function export_to_pdf 48.5% similar
-
function add_formatted_content_to_pdf 45.5% similar
-
function add_formatted_content_to_pdf_v1 44.4% similar
-
function export_to_pdf_v1 43.9% similar