Skip to content

Instantly share code, notes, and snippets.

@omkar-tenkale
Last active July 23, 2021 21:22
Show Gist options
  • Save omkar-tenkale/07e5f08023b04ef424e19be8f757683b to your computer and use it in GitHub Desktop.
Save omkar-tenkale/07e5f08023b04ef424e19be8f757683b to your computer and use it in GitHub Desktop.
Images to pdf android java
// Just pass context and list of file
// It will create a PDF file in cache dir
// Add your own logic to share/open PDF
// Works fast and reliable method
// > - No library needed (Uses android internal android.graphics.pdf.PdfDocument classes)
// > - Works in background, Doesn''t freeze UI
// > - No need to declare and grant storage permission :)
@SuppressLint("StaticFieldLeak")
public static void createPdf(Context context,ArrayList<File> data){
File pdfFile = new File(context.getExternalCacheDir().getAbsolutePath() + File.separator + "TemperoryPDF_"+System.currentTimeMillis()+".pdf");
Toast.makeText(context, "Creating PDF,Please wait..", Toast.LENGTH_SHORT).show();
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
PdfDocument document = new PdfDocument();
try {
for(File item:data) {
Bitmap bitmap = BitmapFactory.decodeFile(item.getAbsolutePath());
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.parseColor("#ffffff"));
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
canvas.drawBitmap(bitmap, 0, 0, null);
document.finishPage(page);
}
document.writeTo(new FileOutputStream(pdfFile));
} catch (IOException e) {
e.printStackTrace();
}finally {
document.close();
}
return null;
}
@Override
protected void onPostExecute(Void unused) {
super.onPostExecute(unused);
if(pdfFile.exists() && pdfFile.length()>0) {
FileUtil.openFile(context, pdfFile.getAbsolutePath()); // See: https://gist.github.com/omkar-tenkale/34d3aa1966653e6949d1ddaee1ba3355
}else {
Toast.makeText(context, "Something went wrong creating the PDF :(", Toast.LENGTH_SHORT).show();
}
}
}.execute();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment