Recently Added

6/recent/ticker-posts

How to Convert Image to PDF in Android Studio Part 3

In this video, I am going to show you  how you can convert an image to pdf and also show the pdf in recyclerview

so let's start.


1.update your file_view.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp">

<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_weight="0"
android:src="@drawable/ic_file" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:orientation="vertical">

<TextView
android:id="@+id/file_view_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="file name"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="16sp" />

<TextView
android:id="@+id/file_view_size"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="10MB"
android:textAlignment="center" />

</LinearLayout>


<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0"
android:src="@drawable/more" />
</LinearLayout>

2.create a model class and name it like Model.java and add this code

package com.example.convertor;

public class Model {

String id;
String title;
String path;
String size;


public Model(String id, String title, String path, String size) {
this.id = id;
this.title = title;
this.path = path;
this.size = size;
}


public String getId() {
return id;
}

public String getTitle() {
return title;
}

public String getPath() {
return path;
}

public String getSize() {
return size;
}
}

3. create a java file and name it like FileAdapter.java and add this code


public class FileAdapter extends RecyclerView.Adapter<FileAdapter.MyHolder> {

Context context;
ArrayList<Model> pdfAdapterArray = new ArrayList<>();

public FileAdapter(Context context, ArrayList<Model> pdfAdapterArray) {
this.context = context;
this.pdfAdapterArray = pdfAdapterArray;
}

@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.file_view, parent,false);
return new MyHolder(view);
}

@Override
public void onBindViewHolder(@NonNull FileAdapter.MyHolder holder, int position) {
holder.title.setText(pdfAdapterArray.get(position).getTitle());
holder.size.setText(pdfAdapterArray.get(position).getSize());
}

@Override
public int getItemCount() {
return pdfAdapterArray.size();
}


public class MyHolder extends RecyclerView.ViewHolder {
TextView title, size;
public MyHolder(@NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.file_view_title);
size = itemView.findViewById(R.id.file_view_size);
}
}
}

4.update your MainActivity.java code


public class MainActivity extends AppCompatActivity {

private static final int REQUEST_CODE = 100;
String folderPath = Environment.getDataDirectory().getAbsolutePath()
+ "/storage/emulated/0/your_folder_name";
File directory = new File("/sdcard/your_folder_name/");

Button camera, upload, convert;
ImageView img;
TextView title;
ProgressBar progressBar;

ArrayList<Model> pdfList = new ArrayList<>();
RecyclerView recyclerView;
FileAdapter fileAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
askPermission();

camera = findViewById(R.id.convertor_toll_camera);
upload = findViewById(R.id.convertor_toll_upload);
convert = findViewById(R.id.convertor_toll_convert);
img = findViewById(R.id.convertor_toll_imageView);
title = findViewById(R.id.convertor_toll_fileName);
progressBar = findViewById(R.id.progressBar);
recyclerView = findViewById(R.id.pdf_recyclerView);

camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (directory.exists()) {
progressBar.setVisibility(View.VISIBLE);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CODE);
} else {
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "try again",
Toast.LENGTH_SHORT).show();
createFolder();
}
}
});
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (directory.exists()) {
progressBar.setVisibility(View.VISIBLE);
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE);
} else {
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "try again",
Toast.LENGTH_SHORT).show();
createFolder();
}
}
});

loadPDFFiles();
}

@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
progressBar.setVisibility(View.GONE);
if (data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.DISPLAY_NAME};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn,
null, null);
cursor.moveToFirst();
int filePath = cursor.getColumnIndex(filePathColumn[0]);
int fileName = cursor.getColumnIndex(filePathColumn[1]);
String path = cursor.getString(filePath);
String name = cursor.getString(fileName);
cursor.close();
img.setImageURI(Uri.parse(path));
title.setText(name);
convert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
boolean converted = imageToPDF(path, name);
runOnUiThread(new Runnable() {
@Override
public void run() {
progressBar.setVisibility(View.GONE);
if (!converted) {
Toast.makeText(MainActivity.this, "fail",
Toast.LENGTH_SHORT).show();
}
}
});
}
});
thread.start();
}
});
} else {
Toast.makeText(this, "select a image",
Toast.LENGTH_SHORT).show();
}
}

private void askPermission() {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
+ ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA}, REQUEST_CODE);
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE) {
createFolder();
}
}

private void createFolder() {
File folder = new File(folderPath);
if (!folder.exists()) {
folder.mkdir();
}
directory.mkdirs();

}


private boolean imageToPDF(String path, String name) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Bitmap bitmap = BitmapFactory.decodeFile(path);
PdfDocument pdfDocument = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(
1920, 1080, 0).create();
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
page.getCanvas().drawBitmap(bitmap, 0, 0, null);
pdfDocument.finishPage(page);
String changeName = getWithoutExtension(name);
String newPath = directory + "/" + changeName + ".pdf";
File file = new File(newPath);
try {
pdfDocument.writeTo(new FileOutputStream(file));
MediaScannerConnection.scanFile(MainActivity.this,
new String[]{file.toString()}, null, null);
} catch (Exception e) {
e.getStackTrace();
}
pdfDocument.close();
return true;
} else {
return false;
}
}

private String getWithoutExtension(String name) {
return name.substring(0, name.lastIndexOf("."));
}


private void loadPDFFiles() {
pdfList = loadFiles(this);
fileAdapter = new FileAdapter(this, pdfList);
recyclerView.setAdapter(fileAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this,
RecyclerView.VERTICAL, false));
}


public ArrayList<Model> loadFiles(Context context) {
ArrayList<Model> arrayList = new ArrayList<>();
Uri uri = MediaStore.Files.getContentUri("external");
String[] projection = {
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.TITLE,
MediaStore.Files.FileColumns.SIZE,
MediaStore.Files.FileColumns.MIME_TYPE,
};
String mimeType = "application/pdf";
String whereClause = MediaStore.Files.FileColumns.MIME_TYPE + " IN ('" + mimeType + "')";
String sortOrder = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";

Cursor cursor = context.getContentResolver().query(uri, projection, whereClause,
null, sortOrder);

int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID);
int idPath = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA);
int idTitle = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.TITLE);
int idSize = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE);

if (cursor != null) {
while (cursor.moveToNext()) {
String id = cursor.getString(idColumn);
String path = cursor.getString(idPath);
String title = cursor.getString(idTitle);
long size = cursor.getLong(idSize);

Model model = new Model(id, title, path, convertIntoReadableSize(size));
arrayList.add(model);
}
}
return arrayList;
}

private String convertIntoReadableSize(long size) {
String s = "";
long kilo = 1024;
long mega = kilo * kilo;
long giga = mega * kilo;
long tera = giga * kilo;
double kb = (double) size / kilo;
double mb = kb / kilo;
double gb = mb / kilo;
double tb = gb / kilo;
if (size < kilo) {
s = size + " Bytes";
} else if (size >= kilo && size < mega) {
s = String.format("%.2f", kb) + " KB";
} else if (size >= mega && size < giga) {
s = String.format("%.2f", mb) + " MB";
} else if (size >= giga && size < tera) {
s = String.format("%.2f", gb) + " GB";
} else if (size >= tera) {
s = String.format("%.2f", tb) + " TB";
}
return s;
}


}

Watch full Tutorials

Post a Comment

0 Comments