Calculate transformation matrix from source to target rect. Notes: The product of four matrices in this sequence: (1) translate correct source corner to origin, (2) rotate, (3) scale, (4) translate to target's top-left corner.
(sr, tr, keep=True, rotate=0)
| 13008 | xref of inserted object (for reuse) |
| 13009 | """ |
| 13010 | def calc_matrix(sr, tr, keep=True, rotate=0): |
| 13011 | """Calculate transformation matrix from source to target rect. |
| 13012 | |
| 13013 | Notes: |
| 13014 | The product of four matrices in this sequence: (1) translate correct |
| 13015 | source corner to origin, (2) rotate, (3) scale, (4) translate to |
| 13016 | target's top-left corner. |
| 13017 | Args: |
| 13018 | sr: source rect in PDF (!) coordinate system |
| 13019 | tr: target rect in PDF coordinate system |
| 13020 | keep: whether to keep source ratio of width to height |
| 13021 | rotate: rotation angle in degrees |
| 13022 | Returns: |
| 13023 | Transformation matrix. |
| 13024 | """ |
| 13025 | # calc center point of source rect |
| 13026 | smp = (sr.tl + sr.br) / 2.0 |
| 13027 | # calc center point of target rect |
| 13028 | tmp = (tr.tl + tr.br) / 2.0 |
| 13029 | |
| 13030 | # m moves to (0, 0), then rotates |
| 13031 | m = Matrix(1, 0, 0, 1, -smp.x, -smp.y) * Matrix(rotate) |
| 13032 | |
| 13033 | sr1 = sr * m # resulting source rect to calculate scale factors |
| 13034 | |
| 13035 | fw = tr.width / sr1.width # scale the width |
| 13036 | fh = tr.height / sr1.height # scale the height |
| 13037 | if keep: |
| 13038 | fw = fh = min(fw, fh) # take min if keeping aspect ratio |
| 13039 | |
| 13040 | m *= Matrix(fw, fh) # concat scale matrix |
| 13041 | m *= Matrix(1, 0, 0, 1, tmp.x, tmp.y) # concat move to target center |
| 13042 | return JM_TUPLE(m) |
| 13043 | |
| 13044 | CheckParent(page) |
| 13045 | doc = page.parent |