Pdf-lib: Rotate an image around it's center

Created on 8 Jul 2020  路  2Comments  路  Source: Hopding/pdf-lib

When I add an image to a page via the following code, it gets positioned to the bottom left of the page:

page.drawImage(img, {
  x: 0,
  y: 0,
  width,
  height,
});

Now I want to rotate the image by 180掳:

page.drawImage(img, {
  x: 0,
  y: 0,
  width,
  height,
  rotate: degrees(180),
});

Because the transformation origin is bottom left, the image will not be visible because it was rotated out of the page. Is it somehow possible to rotate the image based on the center of itself, so that the image is still visible on the bottom left but upside down?

All 2 comments

Solved it, here is my code:

page.pushOperators(
  pushGraphicsState(),
  concatTransformationMatrix(
    1,
    0,
    0,
    1,
    originX,
    originY,
  ),
  concatTransformationMatrix(
    cos(angle),
    sin(angle),
    -sin(angle),
    cos(angle),
    0,
    0,
  ),
  concatTransformationMatrix(
    1,
    0,
    0,
    1,
    -1 * originX,
    -1 * originY,
  ),
);
page.drawImage(img, {
  x: originX - (width / 2),
  y: originY - (height / 2),
  width: width,
  height: height,
});
page.pushOperators(
  popGraphicsState(),
);

Solved it, here is my code:

page.pushOperators(
  pushGraphicsState(),
  concatTransformationMatrix(
    1,
    0,
    0,
    1,
    originX,
    originY,
  ),
  concatTransformationMatrix(
    cos(angle),
    sin(angle),
    -sin(angle),
    cos(angle),
    0,
    0,
  ),
  concatTransformationMatrix(
    1,
    0,
    0,
    1,
    -1 * originX,
    -1 * originY,
  ),
);
page.drawImage(img, {
  x: originX - (width / 2),
  y: originY - (height / 2),
  width: width,
  height: height,
});
page.pushOperators(
  popGraphicsState(),
);

Hi understood your logic but still not able to understand what is originX and originY.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

matthopson picture matthopson  路  4Comments

kevinswartz picture kevinswartz  路  8Comments

MarcGodard picture MarcGodard  路  3Comments

dhollenbeck picture dhollenbeck  路  4Comments

faxemaxee picture faxemaxee  路  6Comments