简体   繁体   English

Pdfbox:在旋转页面中绘制图像

[英]Pdfbox : Draw image in rotated page

I have a simple A4 pdf document with a property /Rotate 90 : The original version of my pdf is landscape but printed portrait.我有一个简单的 A4 pdf 文档,其属性为/Rotate 90 :我的 pdf 的原始版本是横向但打印的纵向。

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"));
}

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.这是最终结果:正如您所看到的,图像被放置在左上角(旋转前的 0,0 坐标)并且没有旋转。

秒

I tried playing with drawImage(PDImageXObject image, Matrix matrix) without success.我尝试使用drawImage(PDImageXObject image, Matrix matrix)没有成功。

Here is the orignal document pdf with 90° rotation这是旋转 90°的原始文档pdf

Here's a solution for a page that is rotated 90°:这是旋转 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.如果它只是图像,那么您不需要保存/恢复。

Solution for a page that is rotated 270°:页面旋转 270° 的解决方案:

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

For 180°:对于 180°:

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

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

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