Pdfbox:在旋转的页面中绘制图像 [英] Pdfbox : Draw image in rotated page

查看:136
本文介绍了Pdfbox:在旋转的页面中绘制图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的A4 pdf文档,其属性为 / Rotate 90 :我的pdf的原始版本为横向但打印为纵向。

I have a simple A4 pdf document with a property /Rotate 90 : The original version of my pdf is landscape but printed portrait.

我正在尝试在portait文档的左下方绘制一个小图像。

I am trying to draw a small image at the bottom left of the portait document.

到目前为止,这是我的代码:

Here is my code so far :

    File file = new File("rotated90.pdf");
    try (final PDDocument doc = PDDocument.load(file)) {
        PDPage page = doc.getPage(0);
        PDImageXObject image = PDImageXObject.createFromFile("image.jpg", doc);
        PDPageContentStream contents = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, false, true);
        contents.drawImage(image, 0, 0);
        contents.close();
        doc.save(new File("newpdf.pdf"));
}

这是最终结果:如您所见,图像位于左上方(是旋转之前的0,0坐标),并且没有旋转。

Here is the end result : As you can see the image was placed at the top left (which was the 0,0 coordinate before rotation) and was not rotated.

我尝试过与 drawImage(PDImageXObject图像,矩阵矩阵)没有成功。

以下是原始文档 pdf旋转90°

推荐答案

以下是将页面旋转90°的解决方案:

Here's a solution for a page that is rotated 90°:

PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);
PDImageXObject image = ....
cs.saveGraphicsState();
cs.transform(Matrix.getRotateInstance(Math.toRadians(90), page.getCropBox().getWidth() + page.getCropBox().getLowerLeftX(), 0));
cs.drawImage(image, 0, 0);
cs.restoreGraphicsState();
cs.close();

如果只是图像,则不需要保存/恢复。

If it is only the image, then you don't need the save/restore.

将页面旋转270°的解决方案:

Solution for a page that is rotated 270°:

cs.transform(Matrix.getRotateInstance(Math.toRadians(270), 0, page.getCropBox().getHeight() + page.getCropBox().getLowerLeftY()));

对于180°:

cs.transform(Matrix.getRotateInstance(Math.toRadians(180), page.getCropBox().getWidth() + page.getCropBox().getLowerLeftX(), page.getCropBox().getHeight() + page.getCropBox().getLowerLeftY()));

这篇关于Pdfbox:在旋转的页面中绘制图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆