1

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?

Mark Storer
  • 15,672
  • 3
  • 42
  • 80
Marcineroo
  • 51
  • 1
  • 5
  • I don't think I've ever seen someone create an image like this: `new Jpeg(logoJock)`. Why didn't you use `Image.getInstance(logoJock)`? Also: a design that requires to download an image from the web every time a PDF is created is a bad design: it uses too much data. You should cache the image on the device. Does your app crash when you don't involve PDF, but download the app as a `byte[]`? – Bruno Lowagie Jun 19 '18 at 02:22
  • Yup, I admit, it was bad design but it was the last idea I had to check. Getting an instance by image.getInstance(); was obvious choice, but it wasn't working. Check my comment to see the solution. – Marcineroo Jun 20 '18 at 08:06

1 Answers1

4

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()
Marcineroo
  • 51
  • 1
  • 5