Using the PDFBox library to embed an Image to a PDF document

I tried to embed an image into a PDF using the apache POI and iText libraries but none of them worked to me. So I tried with the pdfbox library and it worked!

The following java function will embed a base64-encoded image into a base64-encoded PDF document.

/*
 * Params:
 *         b64PDF    - String that represents a Base64-encoded PDF document
 *         b64Img    - String that represents a Base64-encoded image
 *         pageNum   - Page number in which the image will be embedded
 *         positionX - From the left side margin
 *         positionY - From the bottom side margin 
 *
 * Imports:
 *         java.io.InputStream
 *         java.io.ByteArrayInputStream
 *         java.io.ByteArrayOutputStream
 *         org.apache.pdfbox.pdmodel.PDDocument
 *         org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject
 *         org.apache.pdfbox.pdmodel.PDPage
 *         org.apache.pdfbox.pdmodel.PDPageContentStream
 *         org.apache.pdfbox.pdmodel.font.PDType1Font
 *
 * Returns:
 *         A string that represents a Base64-encoded PDF document, "-1" if error
 */
String result = "";

try {
  // CREATE THE PDF DOCUMENT OBJECT FROM THE BASE64-ENCODED PDF
  PDDocument doc = PDDocument.load( new ByteArrayInputStream(Base64Util.decodeToByteArray(b64PDF)) );
  
  // GET THE PAGE TO EDIT
  PDPage page = doc.getPage(pageNum);
  PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
  
  // CREATE AND INSERT THE IMAGE TO THE PAGE
  PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, Base64Util.decodeToByteArray(b64Img), null);
  contentStream.drawImage(pdImage, positionX, positionY);
  contentStream.close();
  
  // SAVE TO OUTPUT STREAM
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  doc.save(baos);
  
  // GET THE BASE64-ENCODED PDF
  result = Base64Util.encodeToString(baos.toByteArray());
  doc.close();
} catch (Throwable e) {
  // result = e.getMessage();
  result = "-1";
}

return result;

Download the component and add it to your application to test it! Please read the PDF document included in the component.

Comments

Popular posts from this blog