Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New feature: Gradient patterns #1334

Merged
merged 18 commits into from
Jan 5, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions fpdf/fpdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,10 @@ def __init__(
self._drawing_graphics_state_registry = GraphicsStateDictRegistry()
# map page numbers to a set of GraphicsState names:
self.graphics_style_names_per_page_number = defaultdict(set)
self.shadings_per_page_number = defaultdict(set)
self.patterns_per_page_number = defaultdict(set)
self._shading_registry = {}
self._pattern_registry = {}
andersonhc marked this conversation as resolved.
Show resolved Hide resolved

self._record_text_quad_points = False

Expand Down Expand Up @@ -1265,6 +1269,25 @@ def drawing_context(self, debug_stream=None):
# The drawing API makes use of features (notably transparency and blending modes) that were introduced in PDF 1.4:
self._set_min_pdf_version("1.4")

@contextmanager
@check_page
def use_pattern(self, shading):
"""
Create a context for using a shading pattern on the current page.
"""
if shading not in self._shading_registry:
self._shading_registry[shading] = f"Sh{len(self._shading_registry) + 1}"
pattern = shading.get_pattern()
if pattern not in self._pattern_registry:
self._pattern_registry[pattern] = "P" + str(len(self._pattern_registry) + 1)
self._out(f"/Pattern cs /{self._pattern_registry[pattern]} scn")
self.shadings_per_page_number[self.page].add(self._shading_registry[shading])
self.patterns_per_page_number[self.page].add(self._pattern_registry[pattern])
try:
yield
finally:
self._out(self.draw_color.serialize().lower())

def _current_graphic_style(self):
gs = GraphicsStyle()
gs.allow_transparency = self.allow_images_transparency
Expand Down
8 changes: 7 additions & 1 deletion fpdf/linearization.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,14 @@ def bufferize(self):
font_objs_per_index = self._add_fonts()
img_objs_per_index = self._add_images()
gfxstate_objs_per_name = self._add_gfxstates()
shading_objs_per_name = self._add_shadings()
pattern_objs_per_name = self._add_patterns()
resources_dict_obj = self._add_resources_dict(
font_objs_per_index, img_objs_per_index, gfxstate_objs_per_name
font_objs_per_index,
img_objs_per_index,
gfxstate_objs_per_name,
shading_objs_per_name,
pattern_objs_per_name,
)
# Part 9: Objects not associated with pages, if any
for embedded_file in fpdf.embedded_files:
Expand Down
70 changes: 65 additions & 5 deletions fpdf/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,12 +149,14 @@ def __init__(


class PDFResources(PDFObject):
def __init__(self, proc_set, font, x_object, ext_g_state):
def __init__(self, proc_set, font, x_object, ext_g_state, shading, pattern):
super().__init__()
self.proc_set = proc_set
self.font = font
self.x_object = x_object
self.ext_g_state = ext_g_state
self.shading = shading
self.pattern = pattern


class PDFFontStream(PDFContentStream):
Expand Down Expand Up @@ -889,14 +891,37 @@ def _add_gfxstates(self):
gfxstate_objs_per_name[name] = gfxstate_obj
return gfxstate_objs_per_name

def _add_shadings(self):
shading_objs_per_name = OrderedDict()
for shading, name in self.fpdf._shading_registry.items():
for function in shading.functions:
self._add_pdf_obj(function, "function")
shading_obj = shading.get_shading_object()
self._add_pdf_obj(shading_obj, "shading")
shading_objs_per_name[name] = shading_obj
return shading_objs_per_name

def _add_patterns(self):
pattern_objs_per_name = OrderedDict()
for pattern, name in self.fpdf._pattern_registry.items():
self._add_pdf_obj(pattern, "pattern")
pattern_objs_per_name[name] = pattern
return pattern_objs_per_name

def _insert_resources(self, page_objs):
font_objs_per_index = self._add_fonts()
img_objs_per_index = self._add_images()
gfxstate_objs_per_name = self._add_gfxstates()
shading_objs_per_name = self._add_shadings()
pattern_objs_per_name = self._add_patterns()
# Insert /Resources dicts:
if self.fpdf.single_resources_object:
resources_dict_obj = self._add_resources_dict(
font_objs_per_index, img_objs_per_index, gfxstate_objs_per_name
font_objs_per_index,
img_objs_per_index,
gfxstate_objs_per_name,
shading_objs_per_name,
pattern_objs_per_name,
)
for page_obj in page_objs:
page_obj.resources = resources_dict_obj
Expand All @@ -916,22 +941,37 @@ def _insert_resources(self, page_objs):
if gfx_name
in self.fpdf.graphics_style_names_per_page_number[page_number]
}
page_shading_objs_per_name = {
shading_name: shading_objs_per_name[shading_name]
for shading_name in self.fpdf.shadings_per_page_number[page_number]
}
page_pattern_objs_per_name = {
pattern_name: pattern_objs_per_name[pattern_name]
for pattern_name in self.fpdf.patterns_per_page_number[page_number]
}
page_obj.resources = self._add_resources_dict(
page_font_objs_per_index,
page_img_objs_per_index,
page_gfxstate_objs_per_name,
page_shading_objs_per_name,
page_pattern_objs_per_name,
)

def _add_resources_dict(
self, font_objs_per_index, img_objs_per_index, gfxstate_objs_per_name
self,
font_objs_per_index,
img_objs_per_index,
gfxstate_objs_per_name,
shading_objs_per_name,
pattern_objs_per_name,
):
# From section 10.1, "Procedure Sets", of PDF 1.7 spec:
# > Beginning with PDF 1.4, this feature is considered obsolete.
# > For compatibility with existing consumer applications,
# > PDF producer applications should continue to specify procedure sets
# > (preferably, all of those listed in Table 10.1).
proc_set = "[/PDF /Text /ImageB /ImageC /ImageI]"
font, x_object, ext_g_state = None, None, None
font, x_object, ext_g_state, shading, pattern = None, None, None, None, None

if font_objs_per_index:
font = pdf_dict(
Expand All @@ -956,9 +996,29 @@ def _add_resources_dict(
for name, gfxstate_obj in gfxstate_objs_per_name.items()
}
)
if shading_objs_per_name:
shading = pdf_dict(
{
f"/{name}": pdf_ref(shading_obj.id)
for name, shading_obj in shading_objs_per_name.items()
}
)

if pattern_objs_per_name:
pattern = pdf_dict(
{
f"/{name}": pdf_ref(pattern_obj.id)
for name, pattern_obj in pattern_objs_per_name.items()
}
)

resources_obj = PDFResources(
proc_set=proc_set, font=font, x_object=x_object, ext_g_state=ext_g_state
proc_set=proc_set,
font=font,
x_object=x_object,
ext_g_state=ext_g_state,
shading=shading,
pattern=pattern,
)
self._add_pdf_obj(resources_obj)
return resources_obj
Expand Down
191 changes: 191 additions & 0 deletions fpdf/pattern.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
"""
Handles the creation of patterns and gradients
"""

from abc import ABC
from typing import List, Union

from .drawing import convert_to_device_color
from .syntax import Name, PDFArray, PDFObject


class Pattern(PDFObject):

def __init__(self, shading: Union["LinearGradient", "RadialGradient"]):
super().__init__()
self.type = Name("Pattern")
self.pattern_type = 2
andersonhc marked this conversation as resolved.
Show resolved Hide resolved
self._shading = shading

@property
def shading(self):
return f"{self._shading.get_shading_object().id} 0 R"


class Type2Function(PDFObject):
"""Transition between 2 colors"""

def __init__(self, color_1, color_2):
super().__init__()
self.function_type = 2
andersonhc marked this conversation as resolved.
Show resolved Hide resolved
self.domain = "[0 1]"
self.c0 = f'[{" ".join(str(c) for c in color_1.colors)}]'
self.c1 = f'[{" ".join(str(c) for c in color_2.colors)}]'
self.n = 1


class Type3Function(PDFObject):
"""When multiple colors are used, a type 3 function is necessary to stitch type 2 functions together
and define the bounds between each color transition"""

def __init__(self, functions, bounds):
super().__init__()
self.function_type = 3
andersonhc marked this conversation as resolved.
Show resolved Hide resolved
self.domain = "[0 1]"
self._functions = functions
self.bounds = f"[{' '.join(str(bound) for bound in bounds)}]"
self.encode = f"[{' '.join("0 1" for _ in functions)}]"
self.n = 1

@property
def functions(self):
return f"[{' '.join(f"{f.id} 0 R" for f in self._functions)}]"


class Shading(PDFObject):
def __init__(
self,
shading_type: int, # 2 for axial shading, 3 for radial shading
background,
color_space,
coords,
function,
extend_before,
extend_after,
):
super().__init__()
self.shading_type = shading_type
self.background = (
f'[{" ".join(str(c) for c in background.colors)}]' if background else None
)
self.color_space = Name(color_space)
self.coords = coords
self.function = f"{function.id} 0 R"
self.extend = f'[{"true" if extend_before else "false"} {"true" if extend_after else "false"}]'


class Gradient(ABC):
def __init__(self, colors, background, extend_before, extend_after):
self.colors = []
self.color_space = None
for color in colors:
current_color = (
convert_to_device_color(color)
if isinstance(color, str)
else convert_to_device_color(*color)
)
self.colors.append(current_color)
if not self.color_space:
self.color_space = current_color.__class__.__name__
if self.color_space != current_color.__class__.__name__:
raise ValueError(
"All colors in a gradient must be of the same color space"
)
self.background = None
if background:
self.background = (
convert_to_device_color(background)
if isinstance(background, str)
else convert_to_device_color(*background)
)
if self.background and self.background.__class__.__name__ != self.color_space:
raise ValueError(
"The background color must be of the same color space as the gradient"
)
self.extend_before = extend_before
self.extend_after = extend_after
self.functions = self.generate_functions()
self.pattern = Pattern(self)
self._shading_object = None
self.coords = None
self.shading_type = 0

def generate_functions(self):
andersonhc marked this conversation as resolved.
Show resolved Hide resolved
if len(self.colors) < 2:
raise ValueError("A gradient must have at least two colors")
if len(self.colors) == 2:
return [Type2Function(self.colors[0], self.colors[1])]
number_of_colors = len(self.colors)
functions = []
for i in range(number_of_colors - 1):
functions.append(Type2Function(self.colors[i], self.colors[i + 1]))
functions.append(
Type3Function(
functions[:],
[(i + 1) / (number_of_colors - 1) for i in range(number_of_colors - 2)],
)
)
return functions

def get_shading_object(self):
if not self._shading_object:
self._shading_object = Shading(
shading_type=self.shading_type,
background=self.background,
color_space=self.color_space,
coords=PDFArray(self.coords),
function=self.functions[-1],
extend_before=self.extend_before,
extend_after=self.extend_after,
)
return self._shading_object

def get_pattern(self):
return self.pattern


class LinearGradient(Gradient):
def __init__(
self,
fpdf,
from_x: int,
from_y: int,
to_x: int,
to_y: int,
colors: List,
background=None,
extend_before=False,
extend_after=False,
):
super().__init__(colors, background, extend_before, extend_after)
coords = [from_x, fpdf.h - from_y, to_x, fpdf.h - to_y]
self.coords = [fpdf.k * c for c in coords]
self.shading_type = 2


class RadialGradient(Gradient):
def __init__(
self,
fpdf,
start_circle_x: int,
start_circle_y: int,
start_circle_radius: int,
end_circle_x: int,
end_circle_y: int,
end_circle_radius: int,
colors: List,
background=None,
extend_before=False,
extend_after=False,
):
super().__init__(colors, background, extend_before, extend_after)
coords = [
start_circle_x,
fpdf.h - start_circle_y,
start_circle_radius,
end_circle_x,
fpdf.h - end_circle_y,
end_circle_radius,
]
self.coords = [fpdf.k * c for c in coords]
self.shading_type = 3
2 changes: 1 addition & 1 deletion fpdf/syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ class PDFArray(list):
def serialize(self, _security_handler=None, _obj_id=None):
if all(isinstance(elem, str) for elem in self):
serialized_elems = " ".join(self)
elif all(isinstance(elem, int) for elem in self):
elif all(isinstance(elem, (int, float)) for elem in self):
serialized_elems = " ".join(str(elem) for elem in self)
else:
serialized_elems = "\n".join(
Expand Down
Binary file added test/pattern/linear_gradient_diagonal.pdf
Binary file not shown.
Binary file added test/pattern/linear_gradient_extend.pdf
Binary file not shown.
Binary file not shown.
Binary file added test/pattern/linear_gradient_vertical.pdf
Binary file not shown.
Binary file added test/pattern/radial_gradient.pdf
Binary file not shown.
Binary file not shown.
Loading
Loading