【问题标题】:iText image.setRotationDegrees() not keeping a consistent originiText image.setRotationDegrees() 没有保持一致的原点
【发布时间】: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
  • 是的,抱歉 - 我整理代码时打错字了。

标签: java itext


【解决方案1】:

这两种形状不应该有共同的起源吗? (好像也有不需要的翻译)

您在这里的隐含假设似乎是模板首先定位然后围绕一些明显的特殊点旋转,例如模板的左下角。

事实并非如此。相反,您可以想象模板旋转,然后确定边界框(边缘与页面边缘平行),并将该边界框的左下角定位在您使用Image.setAbsolutePosition设置的坐标处。

这通过绘制更多的矩形变得更加明显,例如对于 0°、15°、30°、45°、60°、75° 和 90°:

【讨论】:

  • 这真的很有帮助 mkl - 谢谢。作为一个新手,我不确定如何接受这个答案,但它对我有用。
  • “作为一个新手,我不确定如何接受这个答案” - 在答案的左上角,有从顶部底部有一个“向上”箭头(表示赞成)、一个数字(投票数)、一个“向下”箭头(表示反对)和一个勾号(表示接受)。您作为提出问题的人应该能够触发该滴答声。另请参阅tour 页面的顶部。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-09
  • 1970-01-01
  • 2019-07-29
  • 1970-01-01
相关资源
最近更新 更多