In PDF graphics, transformations such as scaling, rotating, and translating objects are essential for precise content positioning and layout. These transformations are represented using transformation matrices. While it's possible to apply transformations sequentially, combining them into a single matrix simplifies calculations, improves performance, and ensures consistent results.
A transformation matrix in PDFs is a 3×3 matrix used to modify the position, scale, and orientation of graphical objects. The general format is:
[a b 0] [c d 0] [e f 1]
a
and d
: Control scaling in the X and Y directions.b
and c
: Control skewing and rotation.e
and f
: Control translation (movement) in the X and Y directions.[0 0 1]
is constant and represents a homogeneous coordinate system.When you perform multiple transformations sequentially, each transformation modifies the Current Transformation Matrix (CTM). However, applying transformations in sequence increases computational overhead and can lead to errors due to floating-point precision. By combining transformations into a single matrix:
Scaling adjusts the size of an object along the X and Y axes. The scaling matrix is:
[Sx 0 0] [ 0 Sy 0] [ 0 0 1]
Sx
: Scaling factor along the X-axis.Sy
: Scaling factor along the Y-axis.For example, to scale an object to 50% of its size:
[0.5 0 0] [ 0 0.5 0] [ 0 0 1]
Rotation pivots an object around the origin by an angle θ
(in radians). The rotation matrix is:
[cos(θ) -sin(θ) 0] [sin(θ) cos(θ) 0] [ 0 0 1]
For example, to rotate an object by 45 degrees (θ = π/4
):
[0.707 -0.707 0] [0.707 0.707 0] [ 0 0 1]
To combine transformations, multiply the matrices in the order they are applied:
The multiplication rule for two matrices A
and B
is:
C[i][j] = Σ (A[i][k] × B[k][j])
For example, if:
A = [a1 b1 0] [c1 d1 0] [e1 f1 1] B = [a2 b2 0] [c2 d2 0] [e2 f2 1]
The resulting matrix C = A × B
is:
[a1×a2 + b1×c2 a1×b2 + b1×d2 0] [c1×a2 + d1×c2 c1×b2 + d1×d2 0] [e1×a2 + f1×c2 e1×b2 + f1×d2 1]
Suppose you want to:
Scaling:
[0.5 0 0] [ 0 0.5 0] [ 0 0 1]
Rotation:
[0.707 -0.707 0] [0.707 0.707 0] [ 0 0 1]
Translation:
[1 0 0] [0 1 0] [100 200 1]
Combine scaling and rotation:
[0.5×0.707 0.5×-0.707 0] = [0.354 -0.354 0] [0.5×0.707 0.5×0.707 0] [0.354 0.354 0] [ 0 0 1] [ 0 0 1]
Next, combine the result with translation:
[1×0.354 + 0×0 + 100 1×-0.354 + 0×0 + 200 0] = [0.354 -0.354 100] [0×0.354 + 1×0.354 + 0 0×-0.354 + 1×0.354 + 0 0] = [0.354 0.354 200] [ 0 0 1] = [ 0 0 1]
The combined transformation matrix is:
[0.354 -0.354 100] [0.354 0.354 200] [ 0 0 1]
Combined transformation matrices are a powerful tool for optimizing graphics in PDFs. By pre-calculating transformations and applying them efficiently, you can reduce complexity, improve performance, and create precise layouts.
If you'd like to learn more about how to apply these concepts in practical scenarios, check out our related post: How to Figure Out Where Something Will Be Drawn on a PDF Page.