这就是我很容易将图像转换为pdf的方法,您需要先在清单中声明用户权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
然后在你的主要活动中,如果你不知道怎么做,你必须检查是否获得了许可,只需在 youtube 上搜索,你会发现很多关于该主题的视频,之后,我使用这种方法来拍照我想从图库中转换成 pdf。
public void pickImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,120);
}
之后,我重写 onActivityResult() 方法以检索所选图像。
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 120 && resultCode == RESULT_OK && data != null) {
Uri selectedImageUri = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor =getContentResolver().query(selectedImageUri,filePath,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String myPath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(myPath);
imageView.setImageBitmap(bitmap);
PdfDocument pdfDocument = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(),
bitmap.getHeight(),1).create();
PdfDocument.Page page = pdfDocument.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);
paint.setColor(Color.BLUE);
canvas.drawBitmap(bitmap,0,0,null);
pdfDocument.finishPage(page);
//save the bitmap image
File root = new File(Environment.getExternalStorageDirectory(),"PDF folder 12");
if (!root.exists()){
root.mkdir();
}
File file = new File(root,"picture.pdf");
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
pdfDocument.writeTo(fileOutputStream);
}catch (Exception e){
e.getStackTrace();
}
pdfDocument.close();
}
}
不要忘记权限并要求用户授予权限
如果要在给出正确的文件夹路径和 pdf 文件名后自动打开 pdf 文件,请使用此方法
String path ="/sdcard/PDF folder 12/picture.pdf";
public void openPDF (){
File pdfFile = new File(path);//File path
if (pdfFile.exists()) //Checking if the file exists or not
{
Uri path = Uri.fromFile(pdfFile);
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(path, "application/pdf");
objIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
startActivity(objIntent);//Starting the pdf viewer
} else {
Toast.makeText(GenerateQRActivity.this, "The file not exists! ", Toast.LENGTH_SHORT).show();
}
}