我正在使用 iText for Java (5.5.13),并且正在尝试使用 Image 类旋转 PDFTemplates。问题是我无法理解 iText 在旋转图像时使用什么作为原点(如果我很愚蠢,我提前道歉)。
附件是我正在使用的代码
- 我创建一个 PDF 模板
- 用任意颜色填充它
- 从此模板创建图像
- 将图像旋转 90 度
- 设置图像的绝对坐标
- 添加到作者
再次重复第二个矩形,但这次仅旋转 30 度。
这两个形状之间不应该有一个共同的起源吗? (看起来也有不需要的翻译)
// step 1
Rectangle pageSize = PageSize.A4;
Document document = new Document(pageSize);
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(OUTPUT_FILENAME));
// step 3
document.open();
// step 4
float boxWidth = 200;
float boxHeight = 50;
float xStart = pageSize.getWidth()/2;
float yStart = pageSize.getHeight()/2;
// Add one filled rectangle rotated 90 degrees
{
PdfContentByte canvas = writer.getDirectContent();
PdfTemplate textTemplate = canvas.createTemplate(boxWidth, boxHeight);
textTemplate.saveState();
textTemplate.setColorFill(BaseColor.RED);
textTemplate.rectangle(0, 0, boxWidth, boxWidth);
textTemplate.fill();
textTemplate.restoreState();
Image img = Image.getInstance(textTemplate);
img.setInterpolation(true);
img.scaleAbsolute(boxWidth, boxHeight);
img.setAbsolutePosition(xStart, yStart);
img.setRotationDegrees(90);
writer.getDirectContent().addImage(img);
}
// And another rotated 30 degrees
{
PdfContentByte canvas = writer.getDirectContent();
PdfTemplate textTemplate = canvas.createTemplate(boxWidth, boxHeight);
textTemplate.saveState();
textTemplate.setColorFill(BaseColor.BLACK);
textTemplate.rectangle(0, 0, boxWidth, boxWidth);
textTemplate.fill();
textTemplate.restoreState();
Image img = Image.getInstance(textTemplate);
img.setInterpolation(true);
img.scaleAbsolute(boxWidth, boxHeight);
img.setAbsolutePosition(xStart, yStart);
img.setRotationDegrees(30);
writer.getDirectContent().addImage(img);
}
// step 5
document.close();
只是为了添加背景,我这样做是因为我希望能够将文本和图像包装在可旋转和可定位的包含内容(具有固定尺寸的图像类)中,然后我可以使用它来构建页面内布局内容的模型(以尝试使用艺术字算法而不是像 wordle 的算法)。
谢谢!
最佳答案
Shouldn't there be a common origin between the two shapes?? (It looks like there is an unwanted translation too)
这里隐含的假设似乎是模板首先被定位,然后围绕一些明显的特殊点旋转,例如模板的左下角。
事实并非如此。相反,您可以想象模板被旋转,然后确定边界框(边缘与页面边缘平行),并且该边界框的左下角位于您使用 Image.setAbsolutePosition
设置的坐标处。
通过绘制更多矩形,这一点会变得更加明显,例如对于 0°、15°、30°、45°、60°、75° 和 90°:
关于java - iText image.setRotationDegrees() 不保持一致的原点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52153094/