简体   繁体   中英

Add image to PDF from a URL?

Im trying to add a image from a URL address to my pdf. The code is:

Image image=Image.getInstance("http://www.google.com/intl/en_ALL/images/logos/images_logo_lg.gif");
image.scaleToFit((float)200.0, (float)49.0);
paragraph.add(image);

But it does not work. What can be wrong?

This is a known issue when loading .gif from a remote location with iText.

A fix for this would be to download the .gif with Java (not via the getInstance method of iText's Image class) and to use the downloaded bytes in the getInstance method of the Image class.

Edit: I went ahead and fixed remote gif loading in iText, it is included from iText 5.4.1 and later.

Adding Image into Itext PDF is not possible through URL . Only way to add image in PDF is download all images in to local directory and apply below code

String photoPath = Environment.getExternalStorageDirectory() + "/abc.png";
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 8;
            final Bitmap b = BitmapFactory.decodeFile(photoPath, options);

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            Bitmap.createScaledBitmap(b, 10, 10, false);
            b.compress(Bitmap.CompressFormat.PNG, 30, stream);
            Image img = null;
            byte[] byteArray = stream.toByteArray();
            try {
                img = Image.getInstance(byteArray);
            } catch (BadElementException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

The way you have used to add images to IText PDF is the way that is used for adding local files, not URLs.

For URLs, this way will solve the problem.

String imageUrl = "http://www.google.com/intl/en_ALL/" 
                  + "images/logos/images_logo_lg.gif";

Image image = Image.getInstance(new URL(imageUrl));

You may then proceed to add this image to some previously open document , using document.add(image) .

For further reference, please visit the [ Java IText: Image docs ].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM