使用 PDFBox 在所有页面上的特定位置覆盖 PDF 2.X

Overlaying PDF on all Pages at specific location on all Pages using PDFBox 2.X

我正在尝试将 PDF 叠加在 PDF 中所有页面的顶部,在每个页面的左上角。不同大小的 PDF。 PDF overlay 是一个固定大小,小于 PDF 的所有页面。

我似乎只能让 PDFBox 将叠加层放在 PDF 的中间。

我不想将 PDF 叠加层转换为位图 (PDImageXObject) 并将其插入页面。这是我正在玩的一些粗略代码:-

public static void main(String[] args) throws Exception {
    String overlayPath = "C:\OverlayPdf.pdf";
    String overlayOnMePath = "C:\ToBeOverlayedOn.pdf";       
    PDDocument overlayOnMe = PDDocument.load(new File(overlayOnMePath)); //Document to write to.
    overlayPath = overlayPath + "Anno.pdf";

    HashMap<Integer, String> overlayGuide = new HashMap<>();
    for (int i = 0; i < overlayOnMe.getNumberOfPages(); i++) {
        overlayGuide.put(i + 1, overlayPath);
    }
    Overlay overlay = new Overlay();
    overlay.setInputPDF(overlayOnMe);
    overlay.setOverlayPosition(Overlay.Position.FOREGROUND);
    overlay.overlay(overlayGuide);

    overlayOnMe.save(new File(overlayOnMePath + "_OVERLAYED.pdf"));
    overlay.close();
}

我的直觉是它是一个仿射变换,但我也无法让它工作。

我创建了一个新的 issue 并且它允许传递一个转换,这将在 2.0.10 或更高版本中。这将在 calculateAffineTransform 中通过扩展覆盖 class 来完成。要将图章放在左上角,新方法将如下所示:

protected AffineTransform calculateAffineTransform(PDPage page, PDRectangle overlayMediaBox)
{
    AffineTransform at = new AffineTransform();
    PDRectangle pageMediaBox = page.getMediaBox();
    at.translate(0, pageMediaBox.getHeight() - overlayMediaBox.getHeight());
    return at;
}