Adding image to PDF, Android Studio

5.8k views Asked by At

I'm developing app in Android Studio using iTextG, where you can fill in a form, click the button and in return You receive a PDF. At the end of the document I need to add an image.

After pressing the button the app is crashing with note "MyApp has stopped". Yet it creates PDF file, but it is empty and I cannot open it.

Here is my code (in function responsible for creating the document):

Paragraph test = new Paragraph();
test.setAlignment(Element.ALIGN_LEFT);
try {
    URL logoJock = new URL("https", "www.imgur.com", "/a/AsunJH7");
    test.add(new Jpeg(logoJock));
} catch (Exception e) {
    e.notify();
}

So I checked the usage and one way of adding image is by URL so I uploaded it on imgur.

document.open();
document.add(data);
document.add(test);
document.close();

I'm adding the paragraph to the document. Without it, my app is creating proper document with all the data I meant to include. The only problem is adding the image.

Can You please help me with this issue?

1

There are 1 answers

0
Marcineroo On

Problem solved,

I tried this, I tried image.getInstance(path), I tried other posiibilities, and finally this one worked (I have to move my logo file to assets folder):

document.open();
try {
        InputStream ims = getAssets().open("logo.PNG");
        Bitmap bmp = BitmapFactory.decodeStream(ims);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
        Image image = Image.getInstance(stream.toByteArray());
        image.scalePercent(30);
        image.setAlignment(Element.ALIGN_LEFT);
        document.add(image);
    } catch (IOException e) {
        e.printStackTrace();
    }
document.close()