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

loo*_*nis 1 java draw pdfbox

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

\n

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

\n

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

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

这是最终结果:如您所见,图像被放置在左上角(旋转前的 0,0 坐标)并且没有旋转。

\n

s

\n

我尝试玩drawImage(PDImageXObject image, Matrix matrix)没有成功。

\n

这是原始文档pdf,旋转 90\xc2\xb0

\n

Til*_*err 5

以下是旋转 90\xc2\xb0 的页面的解决方案:

\n
PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);\nPDImageXObject image = ....\ncs.saveGraphicsState();\ncs.transform(Matrix.getRotateInstance(Math.toRadians(90), page.getCropBox().getWidth() + page.getCropBox().getLowerLeftX(), 0));\ncs.drawImage(image, 0, 0);\ncs.restoreGraphicsState();\ncs.close();\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

页面旋转270\xc2\xb0的解决方案:

\n
cs.transform(Matrix.getRotateInstance(Math.toRadians(270), 0, page.getCropBox().getHeight() + page.getCropBox().getLowerLeftY()));\n
Run Code Online (Sandbox Code Playgroud)\n

对于 180\xc2\xb0:

\n
cs.transform(Matrix.getRotateInstance(Math.toRadians(180), page.getCropBox().getWidth() + page.getCropBox().getLowerLeftX(), page.getCropBox().getHeight() + page.getCropBox().getLowerLeftY()));\n
Run Code Online (Sandbox Code Playgroud)\n