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

Introducing a rect_clip() function #158

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
28 changes: 28 additions & 0 deletions docs/reference/rect_clip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
## rect_clip ##

```python
with pdf.rect_clip(x=..., y=..., w=..., h=...):
pdf.image(filepath, x, y)
```

### Description ###

Performs image clipping, using the `W` operator.

### Parameters ###

x:
> Abscissa of upper-left corner.

y:
> Ordinate of upper-left corner.

w:
> Width.

h:
> Height.

### See also ###

[image](image.md), [rect](rect.md).
9 changes: 8 additions & 1 deletion fpdf/fpdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from functools import wraps
import math
import errno
import os, sys, zlib, struct, re, tempfile, struct
import contextlib, os, sys, zlib, struct, re, tempfile, struct

from .ttfonts import TTFontFile
from .fonts import fpdf_charwidths
Expand Down Expand Up @@ -2067,3 +2067,10 @@ def code39(self, txt, x, y, w=1.5, h=5.0):
self.rect(x, y, dim[d], h, 'F')
x += dim[d]
x += dim['n']

@check_page
@contextlib.contextmanager
def rect_clip(self, x, y, w, h):
self._out(sprintf('q %.2f %.2f %.2f %.2f re W n\n',x*self.k,(self.h-(y+h))*self.k,w*self.k,h*self.k))
yield
self._out('Q\n')
27 changes: 27 additions & 0 deletions tests/cover/test_rect_clip.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-

"Basic test for rect_clip"

#PyFPDF-cover-test:format=PDF
#PyFPDF-cover-test:fn=rect_clip.pdf
#PyFPDF-cover-test:hash=2ab48819c54cb0b3f48514667441c952

import os
import common
from fpdf import FPDF

@common.add_unittest
def dotest(outputname, nostamp):
pdf = FPDF()
if nostamp:
pdf._putinfo = lambda: common.test_putinfo(pdf)

pdf.add_page()

with pdf.rect_clip(x=16, y=16, w=16, h=16):
pdf.image(os.path.join(common.basepath, "lena.gif"), x=0, y=0)

pdf.output(outputname, 'F')

if __name__ == "__main__":
common.testmain(__file__, dotest)