Add image to PDF from a URL?

大憨熊 提交于 2019-12-22 10:35:35

问题


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?


回答1:


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.




回答2:


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();
            }



回答3:


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].



来源:https://stackoverflow.com/questions/15760111/add-image-to-pdf-from-a-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!