itext setRotateContent Flag 用法不清楚

itext setRotateContent Flag usage not clear

我正在使用 pdfstamper水印 添加到现有的 pdf 中。当我保持标志 setRotateContent(true) 时,水印出现在正确的位置,但是当我保持它为 false 时,水印放错了位置。 由于某些限制,我无法共享代码。

我正在分享案例

原始 PDF

使用 setRotateContent(false)

使用 setRotateContent(true)

所以我的问题是 setRotateContent() 究竟是如何工作的。我也试过 Api 页面。但是所有的例子都是 setRotateContent(false).

So my question is how exactly does the setRotateContent() works

作为背景知识,您需要知道每个 PDF 页面都包含一个属性 Rotate,指定为 "The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90. Default value: 0."

如果您想向具有 non-trivial 旋转 值(即 360 的倍数)的页面添加内容,则有两种截然不同的情况:

  • 要么你想在相对于页面坐标系的位置和方向上添加一些东西,不管页面最终如何旋转,
  • 或者您想在与页面显示方式相关的位置添加内容。

虽然前者很简单,您只需使用给定的坐标和方向,后者需要您读取 Rotate 值并将其计算为您的坐标和角度。

这里的 iText 会尽力帮助您,对于 setRotateContent(true),首先添加对内容过多和内容不足的转换,让您可以简单地继续选择坐标和角度,就好像没有涉及页面旋转一样。

似乎后一种情况被认为比前一种情况更常发生。因此,默认 RotateContent 值为 true。因此,在前一种情况下,您实际上必须使用 setRotateContent(false).

将其关闭

问题是它是如何工作的:这是初始化内容不足和内容过多的方法ByteBuffer表示:

void applyRotation(PdfDictionary pageN, ByteBuffer out) {
    if (!rotateContents)
        return;
    Rectangle page = reader.getPageSizeWithRotation(pageN);
    int rotation = page.getRotation();
    switch (rotation) {
        case 90:
            out.append(PdfContents.ROTATE90);
            out.append(page.getTop());
            out.append(' ').append('0').append(PdfContents.ROTATEFINAL);
            break;
        case 180:
            out.append(PdfContents.ROTATE180);
            out.append(page.getRight());
            out.append(' ');
            out.append(page.getTop());
            out.append(PdfContents.ROTATEFINAL);
            break;
        case 270:
            out.append(PdfContents.ROTATE270);
            out.append('0').append(' ');
            out.append(page.getRight());
            out.append(PdfContents.ROTATEFINAL);
            break;
    }
}

(PdfStamperImp)

static final byte ROTATE90[] = DocWriter.getISOBytes("0 1 -1 0 ");
static final byte ROTATE180[] = DocWriter.getISOBytes("-1 0 0 -1 ");
static final byte ROTATE270[] = DocWriter.getISOBytes("0 -1 1 0 ");
static final byte ROTATEFINAL[] = DocWriter.getISOBytes(" cm\n");

(PdfContents)


PS:虽然RotateContent属性控制是否将这些转换添加到内容过多和内容不足,但有一个类似的机制对于无法被该属性禁用的注释 参见。 .