-1

I am Building an App to Upload Images to my company server I am now working on Taking multiple images and converting them to PDF so images that are part of the same document can stay together

My Problem is I have No Idea How to make It so I can Add multiple images to the PDF creation I am Using a android Library PhotoUtils By Kosal Geek for Image processing and PDFdocument to create the pdf

At the moment a single image works but if I select Multiple images I get A null Pointer exception

Main Code

public class PdfMake extends AppCompatActivity {
    private final int PICK_IMAGE=12345;
    private final int REQUEST_CAMERA=6352;
    CameraPhoto cameraPhoto;
    GalleryPhoto galleryPhoto;
    String selectedPhoto;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        StrictMode.VmPolicy.Builder builder4=new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder4.build());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf_make);
        Button fromCamera=findViewById(R.id.SelectImages2);
        Button PdfMake=findViewById(R.id.button4);

        fromCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPictureDialog();
            }
        });
        PdfMake.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api=Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(View v) {
                try {
                    createPdf();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
        private void showPictureDialog () {
            AlertDialog.Builder pictureDialog=new AlertDialog.Builder(this);
            pictureDialog.setTitle("Select Action");
            String[] pictureDialogItems={
                    "Select photo from gallery",
                    "Capture photo from camera"};
            pictureDialog.setItems(pictureDialogItems,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which) {
                                case 0:
                                    getImageFromGallery();
                                    break;
                                case 1:
                                    try {
                                        getImageFromCamera();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    break;

                            }
                        }
                    });

        }




    @RequiresApi(api=Build.VERSION_CODES.KITKAT)
    private void createPdf() throws IOException {
        // create a new document
        PdfDocument document=new PdfDocument();
        // crate a page description
        PdfDocument.PageInfo pageInfo=new PdfDocument.PageInfo.Builder(3000, 6000, 1).create();
        // start a page
        PdfDocument.Page page=document.startPage(pageInfo);
        Canvas canvas=page.getCanvas();
        Bitmap image=BitmapFactory.decodeFile(selectedPhoto);
        canvas.drawBitmap(image, 10, 10, null);

        document.finishPage(page);
        String directory_path=Environment.getExternalStorageDirectory().getPath() + "/mypdf/";
        File file=new File(directory_path);
        if (!file.exists()) {
            file.mkdirs();
        }
        String targetPdf=directory_path + "test-2.pdf";
        File filePath=new File(targetPdf);
        try {
            document.writeTo(new FileOutputStream(filePath));
            Toast.makeText(this, "Done", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Log.e("main", "error " + e.toString());
            Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
        }
        // close the document
        document.close();
    }



        private void getImageFromCamera () throws IOException {

            cameraPhoto=new CameraPhoto(getApplicationContext());
            Intent in=cameraPhoto.takePhotoIntent();
            startActivityForResult(in, REQUEST_CAMERA);
            Bungee.split(PdfMake.this);

        }

        private void getImageFromGallery () {

        Intent intent=new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            }
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
                Bungee.split(PdfMake.this);

            }
        }


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
        if (requestCode == REQUEST_CAMERA) {


        String photoPath=cameraPhoto.getPhotoPath();
        selectedPhoto=photoPath;
        try {
        Bitmap bitmap=ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
        } catch (FileNotFoundException e) {
        Toasty.error(getApplicationContext(),
        "Something Wrong while loading photos", Toast.LENGTH_SHORT).show();
        }

        } else if (requestCode == PICK_IMAGE) {
        Uri uri=data.getData();

        galleryPhoto.setPhotoUri(uri);
        String photoPath=galleryPhoto.getPath();
        selectedPhoto=photoPath;
        try {
        Bitmap bitmap=ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
        } catch (FileNotFoundException e) {
        Toasty.error(getApplicationContext(),
        "Something Wrong while choosing photos", Toast.LENGTH_SHORT).show();
        }
        }
        }
        }
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        int CAMERA_RESULT=11100;
        if(requestCode == CAMERA_RESULT){
        if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
        try {
        getImageFromCamera();
        } catch (IOException e) {
        e.printStackTrace();
        }
        }
        else{
        Toasty.error(getApplicationContext(), "Permission Needed.", Toast.LENGTH_LONG).show();
        }
        }
        else {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
        if(requestCode == PICK_IMAGE){
        if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
        getImageFromGallery();
        }
        else{
        Toasty.error(getApplicationContext(), "Permission Needed.", Toast.LENGTH_LONG).show();
        }
        }
        else {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
        }
}

Code For Gallery images

public class GalleryPhoto {
    final String TAG = this.getClass().getSimpleName();
    private Context context;
    private Uri photoUri;

    public void setPhotoUri(Uri photoUri) {
        this.photoUri = photoUri;
    }

    public GalleryPhoto(Context context) {
        this.context = context;
    }

    public Intent openGalleryIntent() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction("android.intent.action.GET_CONTENT");
        return Intent.createChooser(intent, this.getChooserTitle());
    }

    public String getChooserTitle() {
        return "Select Pictures";
    }

    public String getPath() {
        String path;
        if (VERSION.SDK_INT < 11) {
            path = RealPathUtil.getRealPathFromURI_BelowAPI11(this.context, this.photoUri);
        } else if (VERSION.SDK_INT < 19) {
            path = RealPathUtil.getRealPathFromURI_API11to18(this.context, this.photoUri);
        } else {
            path = RealPathUtil.getRealPathFromURI_API19(this.context, this.photoUri);
        }

        return path;
    }
}

Code For Camera Images

public class CameraPhoto {
    final String TAG = this.getClass().getSimpleName();
    private String photoPath;
    private Context context;

    public String getPhotoPath() {
        return this.photoPath;
    }

    public CameraPhoto(Context context) {
        this.context = context;
    }

    public Intent takePhotoIntent() throws IOException {
        Intent in = new Intent("android.media.action.IMAGE_CAPTURE");
        if (in.resolveActivity(this.context.getPackageManager()) != null) {
            File photoFile = this.createImageFile();
            if (photoFile != null) {
                in.putExtra("output", Uri.fromFile(photoFile));
            }
        }

        return in;
    }

    private File createImageFile() throws IOException {
        String timeStamp = (new SimpleDateFormat("yyyyMMdd_HHmmss")).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, ".jpg", storageDir);
        this.photoPath = image.getAbsolutePath();
        return image;
    }

    public void addToGallery() {
        Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
        File f = new File(this.photoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.context.sendBroadcast(mediaScanIntent);
    }
}
Ruben Meiring
  • 333
  • 2
  • 21
  • Related: https://stackoverflow.com/questions/5290269/how-to-create-a-pdf-with-multiple-pages-from-a-graphics-object-with-java-and-ite – Rahul Khurana Sep 09 '19 at 08:16

1 Answers1

1

There is a nice library called "Android PDF Writer".

What you do is create a PDF object and a page in it.

PDFWriter mPDFWriter = new PDFWriter(PaperSize.FOLIO_WIDTH, PaperSize.FOLIO_HEIGHT);

Then you can add images to it via addImage and pages via newPage()

You can see a demo in the project demo page here.

Itamar Kerbel
  • 2,508
  • 1
  • 22
  • 29
  • How can integrate this library with my app, I can't find a .JAR file of the library.. I Actualy don;t know how to add a library thats not in a JAR file any advice? – Ruben Meiring Sep 09 '19 at 09:09
  • I didn't notice that this lib is old. You can download it and compile it locally but you'll probably get into grade mess. Another option is just to copy the files into your project and compile them with your project. This means that you won't have a library. Last I found a JAR file of it here: https://search.maven.org/artifact/cn.jetclouds/aclibrary/1.0.0/jar – Itamar Kerbel Sep 09 '19 at 09:28
  • Thanks anyway the library is ancient and Like you said i am getting into a gradle mess and deprecated dependecies etc. I am going to try and follow PDFdocuments official android DEV tutorial maybe I can wokr something out from there – Ruben Meiring Sep 09 '19 at 10:00