I have a code that convert layout to image bitmap, then attached on a PDF then it will save the file on external storage.
But I want to implement, while clicking on the download button file will be download on background and show PDF on this window.
Here is my code:
downloadPDF.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PdfDocument pdfDocument = new PdfDocument();
PdfDocument.PageInfo pi = new PdfDocument.PageInfo.Builder(mBitmap.getWidth(),
mBitmap.getHeight(),1).create();
PdfDocument.Page page = pdfDocument.startPage(pi);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.parseColor("#FFFFFF"));
canvas.drawPaint(paint);
mBitmap = Bitmap.createScaledBitmap(mBitmap, mBitmap.getWidth(),mBitmap.getHeight(), true);
paint.setColor(Color.BLUE);
canvas.drawBitmap(mBitmap,0,0,null);
pdfDocument.finishPage(page);
if (ContextCompat.checkSelfPermission(AllotmentDoc.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(AllotmentDoc.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(AllotmentDoc.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
}
} else {
//Save PDF file
//Create time stamp
Date date = new Date() ;
@SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("_yyyy_MM_dd_HH_mm_ss").format(date);
String filePath = Environment.getExternalStorageDirectory() +"/"+ "Allotment" +timeStamp+ ".pdf";
File myFile = new File(filePath);
try {
OutputStream output = new FileOutputStream(myFile);
pdfDocument.writeTo(output);
output.flush();
output.close();
Toast.makeText(AllotmentDoc.this, "PDF Created Succesfully", Toast.LENGTH_LONG).show();
Toast.makeText(AllotmentDoc.this, "PDF Saved On Memory", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
pdfDocument.close();
}
});
How can I do this?