繁体   English   中英

Apache PDFBox旋转PDImageXObject

[英]Apache PDFBox rotate PDImageXObject

我正在玩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));

宽度和高度必须很小才能使图像保持在页面上,旋转自身来掠夺图像,并且在旋转之前进行平移似乎会使图像变大。

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

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

    PDPage page = new PDPage();
    document.addPage(page);
    page.setRotation(90);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    int x = 150;
    int y = 300;

    // draw unrotated
    contentStream.drawXObject(ximage, x, y, ximage.getWidth() / 2, ximage.getHeight() / 2);

    // draw 90° rotated, placed on the right of the first image
    AffineTransform at = new AffineTransform(ximage.getHeight() / 2, 0, 0, ximage.getWidth() / 2, x + ximage1.getWidth(), y);
    at.rotate(Math.toRadians(90));
    contentStream.drawXObject(ximage, at);

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

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

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

宽度和高度必须很小才能使图像保持在页面上,旋转自身来掠夺图像,并且在旋转之前进行平移似乎会使图像变大。

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

这不是一个错误,它只是数学。 你只需要知道,如果你有一个AffineTransform at然后调用at.translate(...)at.rotate(...) ,你不要将仿射变换的平移/旋转部分设置为给定值,而是通过前一个转换和平移/旋转组合替换您的转换。

这意味着,例如

AffineTransform at = new AffineTransform(w, 0, 0, h, 20, 20);
at.translate(0.5, 1);

不一样的

AffineTransform at = new AffineTransform(w, 0, 0, h, 20.5, 21);

正如你所料,但相反

AffineTransform at = new AffineTransform(w, 0, 0, h, 20 + w/2, 20 + h);

这就是为什么宽度和高度必须很小以保持页面上的图像 - translate(0.5, 1)否则推得很远。

由于您构成转换的顺序很重要,如果按此顺序创建转换,您可能会更高兴:

AffineTransform at = AffineTransform.getTranslateInstance(0.5, 1);
at.rotate(Math.toRadians(90));
af.concatenate(new AffineTransform(w, 0, 0, h, 20, 20));

PS:正如蒂尔曼所说: 请记住,旋转位于左下角 ,因此这种构图也会在屏幕外旋转。 只需将h+20添加到初始翻译的x坐标即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM