Apache PDFBox 旋转 PDImageXObject

djb*_*djb 5 java pdf transformation matrix pdfbox

我正在使用 2.0.0-SNAPSHOT,我想将页面设置为横向并旋转我的图片。所以我已经做到了page.setRotation(90);

使用 PDFBox 和 AffineTransform 似乎存在错误

这段代码没有做任何我期望的事情:

AffineTransform at = new AffineTransform(w, 0, 0, h, 20, 20);
at.translate(0.5, 1);
at.rotate(Math.toRadians(90));
Run Code Online (Sandbox Code Playgroud)

宽度和高度必须很小才能将图像保持在页面上,自身旋转会挤压图像,并且在旋转之前平移似乎会将图像缩放得很大。

这是一个错误,还是我只是不理解 PDFBox?

Til*_*err 5

不要进行额外的翻译,而是在创建 AT 时放置翻译。请记住,旋转是围绕左下轴进行的,因此将宽度 w 添加到 x 位置。

\n\n
    PDPage page = new PDPage();\n    document.addPage(page);\n    page.setRotation(90);\n    PDPageContentStream contentStream = new PDPageContentStream(document, page);\n\n    int x = 150;\n    int y = 300;\n\n    // draw unrotated\n    contentStream.drawXObject(ximage, x, y, ximage.getWidth() / 2, ximage.getHeight() / 2);\n\n    // draw 90\xc2\xb0 rotated, placed on the right of the first image\n    AffineTransform at = new AffineTransform(ximage.getHeight() / 2, 0, 0, ximage.getWidth() / 2, x + ximage1.getWidth(), y);\n    at.rotate(Math.toRadians(90));\n    contentStream.drawXObject(ximage, at);\n
Run Code Online (Sandbox Code Playgroud)\n\n

这将绘制图像两次,一次正常,一次旋转 90\xc2\xb0,并定位到右侧。“/2”用于缩放 50%,您当然可以使用其他因子。请注意,“/2”不用于初始 x 位置,因为(缩放的)宽度需要两次。一次定位到旧位置(因为轴!),一次将其移动到右侧以使图像不重叠。

\n\n

另请注意,对于页面旋转, getHeight() 和 getWidth() 是相反的。

\n