Reputation: 51
Tring Bitmap to convert On PDf File and try to save it download directory . Application run successfully but doesnt generate pdf and doesnt save anything. even doesnt showing any error in log. so what is the error on given code. Help me out please. Thanks in advance.
public void CreatePDF(View view) {
File file = getOutputFile();
if (file != null) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
PdfDocument pdfDocument = new PdfDocument();
for (int i = 0; i < imageUris.size(); i++) {
Bitmap bitmap = BitmapFactory.decodeStream(imageUris.get(i).getPath());
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(350, 500, (i + 1)).create();
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvas.drawPaint(paint);
canvas.drawBitmap(bitmap, 0f, 0f, null);
pdfDocument.finishPage(page);
bitmap.recycle();
}
pdfDocument.writeTo(fileOutputStream);
pdfDocument.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private File getOutputFile() {
File root = new File(this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "My PDF Folder");
boolean isFolderCreated = true;
if (!root.exists()) {
isFolderCreated = root.mkdir();
}
if (isFolderCreated) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String imageFileName = "PDF_" + timeStamp;
return new File(root, imageFileName + ".pdf");
} else {
Toast.makeText(this, "Folder is not created", Toast.LENGTH_SHORT).show();
return null;
}
}
}
If you want to look up whole code Link : https://github.com/KayesFahim/ScannerBuddy/
Upvotes: 1
Views: 339
Reputation: 1058
Possibility 1:
If you don't have the permission, add it in AndroidManifest.xml
:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
these permissions are also mentioned, but I you don't need them (as long as you don't use the internet or camera):
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
Possibility 2:
There sometimes is a glitch with the emulator that makes Toast-messages not show. Maybe try to throw an exception while testing.
Possibility 3:
Try
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
directly at first.
Or maybe the emulator somehow doesn't have a download folder, in this case try
root.mkdirs();
Possibility 4:
What is imageUris and where are the bitmaps you want to save? Why do you want to decode a Stream if you already have a bitmap? Why are you looping?
Just directly use your bitmap, without a loop, and replace 350
with bitmap.width()
and bitmap.height()
.
Upvotes: 1