class SignatureImage
A ReportLab Flowable subclass for embedding signature images in PDFs with automatic fallback to placeholder text when images are unavailable or cannot be loaded.
/tf/active/vicechatdev/CDocs/utils/pdf_utils.py
564 - 609
simple
Purpose
SignatureImage extends ReportLab's Flowable class to provide robust signature image handling in PDF generation. It attempts to load and render a signature image from a file path, and gracefully falls back to displaying placeholder rectangles with descriptive text ('Signature Unavailable' or 'No Signature on File') when the image file doesn't exist or cannot be loaded. This ensures PDF generation continues successfully even when signature images are missing, making it ideal for automated document generation workflows where signature availability may vary.
Source Code
class SignatureImage(Flowable):
"""
Custom flowable for signature images in ReportLab
This class allows embedding signature images in PDFs with fallback
placeholders if the image can't be loaded.
"""
def __init__(self, img_path: str, width: float = 2*inch, height: float = 0.75*inch):
"""
Initialize the signature image flowable
Parameters
----------
img_path : str
Path to the signature image
width : float
Width of the signature image
height : float
Height of the signature image
"""
Flowable.__init__(self)
self.img_path = img_path
self.width = width
self.height = height
def draw(self):
"""Draw the signature image or a placeholder if the image can't be loaded"""
if os.path.exists(self.img_path):
try:
img = Image(self.img_path, self.width, self.height)
img.drawOn(self.canv, 0, 0)
except Exception as e:
# Draw a placeholder if image can't be loaded
self.canv.setStrokeColor(colors.grey)
self.canv.rect(0, 0, self.width, self.height)
self.canv.setFont("Helvetica", 8)
self.canv.drawString(5, self.height/2, "Signature Unavailable")
logger.warning(f"Could not load signature image: {str(e)}")
else:
# Draw a placeholder if file doesn't exist
self.canv.setStrokeColor(colors.grey)
self.canv.rect(0, 0, self.width, self.height)
self.canv.setFont("Helvetica", 8)
self.canv.drawString(5, self.height/2, "No Signature on File")
logger.warning(f"Signature image not found: {self.img_path}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
Flowable | - |
Parameter Details
img_path: String path to the signature image file. Can be absolute or relative path. The class checks for file existence before attempting to load. Supports image formats compatible with ReportLab's Image class (PNG, JPEG, GIF, etc.).
width: Float value specifying the width of the signature image in ReportLab units. Defaults to 2 inches (2*inch). This width is used both for rendering the image and for the placeholder rectangle if the image cannot be loaded.
height: Float value specifying the height of the signature image in ReportLab units. Defaults to 0.75 inches (0.75*inch). This height is used both for rendering the image and for the placeholder rectangle if the image cannot be loaded.
Return Value
Instantiation returns a SignatureImage object that is a Flowable, which can be added to ReportLab document templates (like SimpleDocTemplate) and will be rendered when the PDF is built. The draw() method does not return a value but renders content directly to the canvas (self.canv) provided by the ReportLab framework.
Class Interface
Methods
__init__(self, img_path: str, width: float = 2*inch, height: float = 0.75*inch)
Purpose: Initialize the SignatureImage flowable with image path and dimensions
Parameters:
img_path: String path to the signature image filewidth: Width of the signature image in ReportLab units (default: 2 inches)height: Height of the signature image in ReportLab units (default: 0.75 inches)
Returns: None (constructor)
draw(self)
Purpose: Render the signature image or a placeholder rectangle with text to the PDF canvas. Called automatically by ReportLab during PDF generation.
Returns: None - renders directly to self.canv (the canvas provided by ReportLab framework)
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
img_path |
str | Path to the signature image file, set during initialization | instance |
width |
float | Width of the signature image or placeholder in ReportLab units | instance |
height |
float | Height of the signature image or placeholder in ReportLab units | instance |
canv |
reportlab.pdfgen.canvas.Canvas | Canvas object provided by ReportLab framework during rendering, used in draw() method to render content | instance |
Dependencies
reportlaboslogging
Required Imports
import os
import logging
from reportlab.lib import colors
from reportlab.lib.units import inch
from reportlab.platypus import Image
from reportlab.platypus import Flowable
Usage Example
from reportlab.platypus import SimpleDocTemplate, Flowable
from reportlab.lib.units import inch
from reportlab.lib import colors
from reportlab.platypus import Image
import os
import logging
logger = logging.getLogger(__name__)
# Create a SignatureImage instance with default dimensions
sig_image = SignatureImage('path/to/signature.png')
# Create with custom dimensions
sig_image_custom = SignatureImage(
img_path='signatures/john_doe.png',
width=3*inch,
height=1*inch
)
# Add to a ReportLab document
doc = SimpleDocTemplate('document.pdf')
story = []
story.append(sig_image)
doc.build(story)
# The draw() method is called automatically by ReportLab during PDF generation
# You typically don't call it directly
Best Practices
- Always ensure the logger is properly configured before using this class to capture warning messages about missing or unloadable signature images
- Use ReportLab units (inch, cm) for width and height parameters to ensure consistent sizing across different PDF configurations
- The class is designed to be added to ReportLab story lists and should not have its draw() method called directly - let the ReportLab framework handle rendering
- Verify signature image paths are correct and accessible before PDF generation to avoid placeholder rendering, though the class handles missing files gracefully
- Consider the aspect ratio when setting custom width and height to avoid distorting signature images
- The class logs warnings but does not raise exceptions, ensuring PDF generation continues even with missing signatures - monitor logs for signature availability issues
- Signature images should be in formats supported by ReportLab's Image class (PNG, JPEG recommended for best quality)
- The placeholder text is positioned at height/2, so very small heights may result in text being cut off or poorly positioned
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class SignatureImage_v1 95.5% similar
-
class SignatureGenerator 59.8% similar
-
class SignatureManager 55.9% similar
-
function main_v32 50.3% similar
-
class Watermarker 45.3% similar