Skip to content

Commit

Permalink
Merge branch 'release/1.4.4' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
erikvw committed Nov 23, 2024
2 parents a958360 + 6d37fce commit 187c41f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,21 @@ preview of a page can be saved as an image, or returned as a BytesIO buffer.

[1]: http://www.reportlab.com/opensource/

Watermarks during testing
=========================
You can add a watermark to each label by passing watermark parameters to the ``save`` or ``save_buffer`` methods:

```python
watermark = ("Sample", ("Helvetica", 12))
sheet.save_buffer(watermark)
```
or

```python
watermark = ("Sample", ("Helvetica", 12))
sheet.save(file_obj, watermark)
```

Examples
========

Expand Down
26 changes: 21 additions & 5 deletions pylabels/sheet.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,7 @@ def add_labels(self, objects, count=1):
# Draw it.
self._draw_label(obj, thiscount)

def _save(self, filelike):
def _save(self, filelike, watermark: tuple[str, tuple[str, int]] | None = None):
# Shade any remaining missing labels if desired.
self._shade_remaining_missing()

Expand All @@ -508,30 +508,46 @@ def _save(self, filelike):
# Render each created page onto the canvas.
for page in self._pages:
renderPDF.draw(page, canvas, 0, 0)
if watermark:
self.draw_watermark(canvas, watermark=watermark)
canvas.showPage()
return canvas

def save(self, filelike):
def save(self, filelike, watermark: tuple[str, tuple[str, int]] | None = None):
"""Save the file as a PDF.
Parameters
----------
filelike: path or file-like object
The filename or file-like object to save the labels under.
Any existing contents will be overwritten.
watermark: tuple like ("Sample", ("Helvetica", 12))
If set prints an opaque gray watermark at a 45-degree
rotation on each label. Useful for testing.
"""
canvas = self._save(filelike)
canvas = self._save(filelike, watermark=watermark)
# Done.
canvas.save()

def save_to_buffer(self) -> BytesIO:
def save_to_buffer(self, watermark: tuple[str, tuple[str, int]] | None = None) -> BytesIO:
buffer = BytesIO()
canvas = self._save(buffer)
canvas = self._save(buffer, watermark=watermark)
canvas.save()
buffer.seek(0)
return buffer

@staticmethod
def draw_watermark(canvas, watermark: tuple[str, tuple[str, int]] | None = None):
if watermark:
canvas.saveState()
canvas.setFont(*watermark[1])
canvas.setFillGray(0.5, 0.5) # Light gray color
canvas.translate(300, 500)
canvas.rotate(45)
canvas.drawCentredString(0, 0, watermark[0])
canvas.restoreState()

def preview(self, page, filelike, format="png", dpi=72, background_colour=0xFFFFFF):
"""Render a preview image of a page.
Expand Down

0 comments on commit 187c41f

Please sign in to comment.