Skip to content

Instantly share code, notes, and snippets.

@vunguyen-it
Forked from Wicowyn/addImage.java
Created April 11, 2017 08:39
Show Gist options
  • Save vunguyen-it/54c3f2360d95abe8a7d82ed49f951729 to your computer and use it in GitHub Desktop.
Save vunguyen-it/54c3f2360d95abe8a7d82ed49f951729 to your computer and use it in GitHub Desktop.
Add image to PDF with PDFBox-Android
try {
final File realDocument = new File(adapter.get(currentPage).getUriLocal().getPath());
final File copyDocument = File.createTempFile("pdf", "pdf");
IOUtils.copy(new FileInputStream(realDocument), new FileOutputStream(copyDocument));
PDDocument document = PDDocument.load(copyDocument);
PDPage page=document.getPage(document.getNumberOfPages() - 1);
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
Bitmap bitmap=BitmapFactory.decodeFile(file.getPath());
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
PDImageXObject pdImage = new PDImageXObject(document, new ByteArrayInputStream(outputStream.toByteArray()),
COSName.DCT_DECODE, bitmap.getWidth(), bitmap.getHeight(),
8, //awtImage.getColorModel().getComponentSize(0), TODO
PDDeviceRGB.INSTANCE);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(pdImage, 100, 100);
contentStream.close();
document.save(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "immo-facile.pdf"));
document.close();
} catch (IOException e) {
e.printStackTrace();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment