简体   繁体   中英

create a one page PDF from two PDFs using PDFBOX

I have a small (quarter inch) one page PDF I created with PDFBOX with text (A). I want to put that small one page PDF (A) on the top of an existing PDF page (B), preserving the existing content of the PDF page (B). In the end, I will have a one page PDF, representing the small PDF on top(A), and the existing PDF intact making up the rest (B). How can I accomplish this with PDFBOX?

To join two pages one atop the other onto one target page, you can make use of the PDFBox LayerUtility for importing pages as form XObjects in a fashion similar to PDFBox SuperimposePage example, eg with this helper method:

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 method join )

You use it like this:

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

( JoinPages test testJoinSmallAndBig )

The result looks like this:

截图

Just as an additional point to @mkl's answer. If anybody is looking to scale the PDFs before placing them on the page use,

    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

This way you can rescale your PDFs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM