iText 添加水印文本沿左侧边框垂直居中对齐

iText Add watermarking text vertically along the left hand side border center aligned

我需要沿着 PDF 文档的左侧边框垂直添加水印文本。水印文本也应该居中对齐。我检查了 iText 中的几个例子,但还没有完成。感谢任何帮助。

1 http://developers.itextpdf.com/examples/miscellaneous/vertical-text

我看到你的问题已经收到了 3 个接近的投票,原因是 "unclear what you're asking"。请允许我先解释不清楚的地方,然后我会尝试解决问题。

不清楚您是从头开始创建文档还是要向现有文档添加水印:

  • 如果您是从头开始创建文档,则需要使用 页面事件 自动将水印添加到每个页面。这意味着您必须查看 page events section of the documentation. If you didn't know about page events, you probably would have ended up there anyway, by searching for the key word Watermark, where you'd find answers to questions such as How to add text as a header or footer?
  • 如果要将水印添加到现有文档,您需要使用 PdfStamper,一个 class,该 class 在 Manipulating existing PDFs 部分的问题的许多答案中使用官方文档。

你引用了一个关于 Vertical text 的例子让人们感到困惑,这个例子是为了解释 iText 如何支持垂直书写系统,例如日语的书写系统,其中字形写在垂直列中。看到你收到的反对票,我认为造成这种混乱的原因让反对者感到恼火,因为他们可能认为你只是链接到你发现的第一个随机例子,这样你就有借口以防他们问你 "what have you tried?"

现在是解决方案。我不清楚您是要将水印添加到从头开始创建的文档还是现有文档。假设您要向现有文档添加水印。在这种情况下,您需要 WatermarkToTheSide 示例:

public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    int n = reader.getNumberOfPages();
    PdfContentByte canvas;
    Rectangle pageSize;
    float x, y;
    for (int p = 1; p <= n; p++) {
        pageSize = reader.getPageSizeWithRotation(p);
        // left of the page
        x = pageSize.getLeft();
        // middle of the height
        y = (pageSize.getTop() + pageSize.getBottom()) / 2;
        // getting the canvas covering the existing content
        canvas = stamper.getOverContent(p);
        // adding some lines to the left
        ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER,
            new Phrase("This is some extra text added to the left of the page"),
            x + 18, y, 90);
        ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER,
            new Phrase("This is some more text added to the left of the page"),
            x + 34, y, 90);
    }
    stamper.close();
}

请注意,我使用了一个非常特殊的 PDF 来测试它:pages.pdf

此 PDF 包含不同大小、不同方向等的页面。看结果的时候,有一页好像没有水印:side_watermark.pdf

您可能认为第 5 页上的水印不见了。它不是!它在那里,但它是不可见的,因为它是在 CropBox 之外添加的。您可能想要调整我的示例,以便它也考虑到 CropBox 的存在。

假设我做出了错误的假设,假设您的问题是关于从头开始创建文档。在这种情况下,您的问题与 How to add text as a header or footer?

重复

页眉和页脚的唯一区别在于文本的位置。您只需将 header/footer 示例中的两行 showTextAligned() 替换为我在 WatermarkToTheSide 示例中使用的行:

ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER,
    new Phrase("This is some extra text added to the left of the page"),
    x + 18, y, 90);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER,
    new Phrase("This is some more text added to the left of the page"),
    x + 34, y, 90);

如果您的文档是用 A4 页面大小创建的,x 可以替换为 0y 可以替换为 421(这是一半A4 页面的高度)。