how to add background image to PDF using PDFBox?

落花浮王杯 提交于 2019-12-18 09:32:04

问题


I am using Java PDFBox version 2.0. I want to know how to add a back ground image to the pdf. I can not find any good example in the pdfbox.apache.org


回答1:


Do this with each page, i.e. from 0 to doc.getNumberOfPages():

    PDPage pdPage = doc.getPage(page);
    InputStream oldContentStream = pdPage.getContents();
    byte[] ba = IOUtils.toByteArray(oldContentStream);
    oldContentStream.close();

    // brings a warning because a content stream already exists
    PDPageContentStream newContentStream = new PDPageContentStream(doc, pdPage, false, true);

    // createFromFile is the easiest way with an image file
    // if you already have the image in a BufferedImage, 
    // call LosslessFactory.createFromImage() instead
    PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
    newContentStream.saveGraphicsState();
    newContentStream.drawImage(pdImage, 0, 0);
    newContentStream.restoreGraphicsState();
    newContentStream.close();

    // append the saved existing content stream
    PDPageContentStream newContentStream2 = new PDPageContentStream(doc, pdPage, true, true);
    newContentStream2.appendRawCommands(ba); // deprecated... needs to be rediscussed among devs
    newContentStream2.close();           

There is another way to do it which is more painful IMHO, getting a iterator of PDStream objects from the page with getContentStreams(), build a List, and insert the new stream at the beginning, and reassign this PDStream list to the page with setContents(). I can add this as an alternative solution if needed.




回答2:


Call PDPageContentStream.drawImage:

val document = PDDocument()
val page = PDPage()
document.addPage(page)
val contentStream = PDPageContentStream(document, page)

val imageBytes = this::class.java.getResourceAsStream("/image.jpg").readAllBytes()
val image = PDImageXObject.createFromByteArray(document, imageBytes, "background")
contentStream.drawImage(image, 0f, 0f, page.mediaBox.width, page.mediaBox.height)

contentStream.close()
page.close()


来源:https://stackoverflow.com/questions/33406920/how-to-add-background-image-to-pdf-using-pdfbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!