【发布时间】:2018-09-03 16:00:10
【问题描述】:
我正在使用 iText for Java (5.5.13),并且正在尝试使用 Image 类旋转 PDFTemplates。问题是我无法理解 iText 在旋转图像时使用的原点(如果我很愚蠢,我会提前道歉)。
附上我正在使用的代码
- 我创建了一个 PDFTemplate
- 用一些任意颜色填充它
- 从此模板创建图像
- 将图像旋转 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 的艺术文字算法)。
谢谢!
【问题讨论】:
-
在我看来,iText 将旋转模板的边界框定位在给定的绝对坐标处,即旋转模板的位置使其最小 x 坐标为
xStart,其最小y坐标为yStart。 -
顺便说一句,你的
textTemplate.rectangle(0, 0, boxWidth, boxWidth)应该是textTemplate.rectangle(0, 0, boxWidth, boxHeight),也就是说,这两个维度都不是boxWidth。 -
是的,抱歉 - 我整理代码时打错字了。