Skip to content

Commit

Permalink
DOC: Page vs Content scaling (#1208)
Browse files Browse the repository at this point in the history
Closes #1035
  • Loading branch information
MartinThoma authored Aug 6, 2022
1 parent a6b8fa6 commit cb3f66e
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
6 changes: 6 additions & 0 deletions PyPDF2/_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,12 @@ def translate(self, tx: float = 0, ty: float = 0) -> "Transformation":
def scale(
self, sx: Optional[float] = None, sy: Optional[float] = None
) -> "Transformation":
"""
Scale the contents of a page towards the origin of the coordinate system.
Typically, that is the lower-left corner of the page. That can be
changed by translating the contents / the page boxes.
"""
if sx is None and sy is None:
raise ValueError("Either sx or sy must be specified")
if sx is None:
Expand Down
63 changes: 63 additions & 0 deletions docs/user/cropping-and-transforming.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,66 @@ op = Transformation().rotate(45).translate(tx=50)
```

![](merge-translated.png)


## Scaling

PyPDF2 offers two ways to scale: The page itself and the contents on a page.
Typically, you want to combine both.

![](scaling.png)

### Scaling a Page (the Canvas)

```python
from PyPDF2 import PdfReader, PdfWriter

# Read the input
reader = PdfReader("resources/side-by-side-subfig.pdf")
page = reader.pages[0]

# Scale
page.scale(0.5)

# Write the result to a file
writer = PdfWriter()
writer.add_page(page)
writer.write("out.pdf")
```

If you wish to have more control, you can adjust the various page boxes
directly:

```python
from PyPDF2.generic import RectangleObject

mb = page.mediabox

page.mediabox = RectangleObject((mb.left, mb.bottom, mb.right, mb.top))
page.cropbox = RectangleObject((mb.left, mb.bottom, mb.right, mb.top))
page.trimbox = RectangleObject((mb.left, mb.bottom, mb.right, mb.top))
page.bleedbox = RectangleObject((mb.left, mb.bottom, mb.right, mb.top))
page.artbox = RectangleObject((mb.left, mb.bottom, mb.right, mb.top))
```

### Scaling the content

The content is scaled towords the origin of the coordinate system. Typically,
that is the lower-left corner.

```python
from PyPDF2 import PdfReader, PdfWriter, Transformation

# Read the input
reader = PdfReader("resources/side-by-side-subfig.pdf")
page = reader.pages[0]

# Scale
op = Transformation().scale(sx=0.7, sy=0.7)
page.add_transformation(op)

# Write the result to a file
writer = PdfWriter()
writer.add_page(page)
writer.write("out-pg-transform.pdf")
```
Binary file added docs/user/scaling.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit cb3f66e

Please sign in to comment.