Search code examples
javaimagepdfbox

How to insert a image created by decode of a string to a pdf in pdfbox


I'm trying to insert an image (which needs to be converted from a string by java.util.Base64.getDecoder().decode(imageInputString)) to a certain position of a pdf file.

The main logic of the code will be:

  //create a PDImageXObject myImage first (or something that could be used in addImage method. 
  //And this is what I could not figure out how to accomplish.

  //open the pdf file and use addImage to insert the image to the specific page at specific position.
  PDDocument document = PDDocument.load(pdfFile);  
  PDPageContentStream contentStream = new PDPageContentStream(document, pageNumber);
  contentStream.addImage(myImage,x,y);
  document.save();

Most of the tutorial I found created the myImage from reading an image file. Could someone help me to see if I could do the same thing but with a byte [], which is the output of java.util.Base64.getDecoder().decode(imageInputString)?

Thanks!


Solution

  • You can use the static method PDImageXObject.createFromByteArray(), which detects the file type based on contents and will decide which PDF image type / image compression is best. (javadoc)