有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用PDFBOX从两个PDF创建一页PDF

我有一个小的(四分之一英寸)一页的PDF,我用PDFBOX创建,带有文本(a)。我想把小的一页PDF(A)放在现有PDF页面(B)的顶部,保留PDF页面(B)的现有内容。最后,我将有一个一页的PDF,表示顶部(a)的小PDF,其余(B)部分则是完整的现有PDF。如何使用PDFBOX实现这一点


共 (2) 个答案

  1. # 1 楼答案

    要将两个页面一个接一个地连接到一个目标页面上,可以使用PDFBoxLayerUtility以类似于PDFBoxSuperimposePage示例的方式将页面作为表单XObject导入,例如,使用此帮助器方法:

    void join(PDDocument target, PDDocument topSource, PDDocument bottomSource) throws IOException {
        LayerUtility layerUtility = new LayerUtility(target);
        PDFormXObject topForm = layerUtility.importPageAsForm(topSource, 0);
        PDFormXObject bottomForm = layerUtility.importPageAsForm(bottomSource, 0);
    
        float height = topForm.getBBox().getHeight() + bottomForm.getBBox().getHeight();
        float width, topMargin, bottomMargin;
        if (topForm.getBBox().getWidth() > bottomForm.getBBox().getWidth()) {
            width = topForm.getBBox().getWidth();
            topMargin = 0;
            bottomMargin = (topForm.getBBox().getWidth() - bottomForm.getBBox().getWidth()) / 2;
        } else {
            width = bottomForm.getBBox().getWidth();
            topMargin = (bottomForm.getBBox().getWidth() - topForm.getBBox().getWidth()) / 2;
            bottomMargin = 0;
        }
    
        PDPage targetPage = new PDPage(new PDRectangle(width, height));
        target.addPage(targetPage);
    
    
        PDPageContentStream contentStream = new PDPageContentStream(target, targetPage);
        if (bottomMargin != 0)
            contentStream.transform(Matrix.getTranslateInstance(bottomMargin, 0));
        contentStream.drawForm(bottomForm);
        contentStream.transform(Matrix.getTranslateInstance(topMargin - bottomMargin, bottomForm.getBBox().getHeight()));
        contentStream.drawForm(topForm);
        contentStream.close();
    }
    

    JoinPages方法join

    您可以这样使用它:

    try (   PDDocument document = new PDDocument();
            PDDocument top = ...;
            PDDocument bottom = ...) {
        join(document, top, bottom);
        document.save("joinedPage.pdf");
    }
    

    JoinPages测试testJoinSmallAndBig

    结果如下所示:

    screenshot

  2. # 2 楼答案

    作为@mkl答案的补充。 如果有人希望在将PDF放到页面上之前对其进行缩放

        contentStream.transform(Matrix.getScaleInstance(<scaling factor in x axis>, <scaling factor in y axis>));  //where 1 is the scaling factor if you want the page as the original size
    

    这样,您可以重新缩放PDF