问题描述
我有一个简单的A4 pdf文档,其属性为/Rotate 90
:我的pdf的原始版本为横向但打印为纵向。
我正在尝试在portait文档的左下方绘制一个小图像。
到目前为止,这是我的代码:
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);
contents.close();
doc.save(new File("newpdf.pdf"));
}
这是最终结果:如您所见,图像放置在左上角(旋转之前为0,0坐标)并且没有旋转。
我尝试与drawImage(PDImageXObject image,Matrix matrix)
一起玩没有成功。
解决方法
这是将页面旋转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);
cs.restoreGraphicsState();
cs.close();
如果只是图像,则不需要保存/恢复。
将页面旋转270°的解决方案:
cs.transform(Matrix.getRotateInstance(Math.toRadians(270),page.getCropBox().getHeight() + page.getCropBox().getLowerLeftY()));
180°:
cs.transform(Matrix.getRotateInstance(Math.toRadians(180),page.getCropBox().getHeight() + page.getCropBox().getLowerLeftY()));