Created
February 27, 2024 21:29
-
-
Save hyperstown/88a44b28313549a43255f590f4915b1a to your computer and use it in GitHub Desktop.
Simple Border for FPDF2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fpdf import FPDF | |
from fpdf.drawing import Point | |
class Border: | |
top_left = None | |
top_right = None | |
def __init__(self, pdf, width=0.8): | |
self.pdf = pdf | |
self.width = width | |
self.pdf_margin = pdf.l_margin | |
@property | |
def start_x(cls): | |
return (cls.pdf.w - (cls.pdf.w * cls.width)) / 2 | |
@property | |
def end_x(cls): | |
return cls.start_x + (cls.pdf.w * cls.width) | |
def __enter__(self): | |
self.pdf.set_left_margin(self.start_x) | |
self.top_left = Point(self.start_x, self.pdf.y) | |
self.top_right = Point(self.end_x, self.pdf.y) | |
self.pdf.line(*self.top_left, *self.top_right) | |
return self | |
def __exit__(self, exc_type, exc_value, traceback): | |
self.pdf.line(self.start_x, self.pdf.y, *self.top_left) | |
self.pdf.line(self.start_x, self.pdf.y, self.end_x, self.pdf.y) | |
self.pdf.line(self.end_x, self.pdf.y, *self.top_right) | |
self.pdf.set_left_margin(self.pdf_margin) | |
return False | |
class PDF(FPDF): | |
def border(self, *args, **kwargs): | |
return Border(self, *args, **kwargs) | |
""" | |
Simple borders for FPDF2 | |
Use borders with with statement. | |
# Caveats: | |
- Doesn't support page breaks (make sure border fits in one page) | |
- Doesn't support relative margin modification, will restart after border end. | |
# Example usage: | |
``` | |
pdf = PDF() | |
pdf.add_page() | |
pdf.set_font("Helvetica", "B", size=10) | |
pdf.cell(0, 10, "Example border:", align='C') | |
pdf.ln(10) | |
with pdf.border(width=0.8) as border: | |
pdf.cell(0, None, "This text will be displayed in border") | |
pdf.ln(4) | |
pdf.cell(0, None, "And this text as well") | |
pdf.ln(4) | |
pdf.cell(0, None, "And here we're again outside the border") | |
pdf.ln(4) | |
pdf.output("fpdf2_borders.pdf") | |
``` | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment