简体   繁体   English

从 URL 添加图像到 PDF?

[英]Add image to PDF from a URL?

Im trying to add a image from a URL address to my pdf.我正在尝试将来自 URL 地址的图像添加到我的 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.这是使用 iText 从远程位置加载 .gif 时的一个已知问题。

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.对此的解决方法是使用 Java 下载 .gif(而不是通过 iText 的 Image 类的 getInstance 方法)并在 Image 类的 getInstance 方法中使用下载的字节。

Edit: I went ahead and fixed remote gif loading in iText, it is included from iText 5.4.1 and later.编辑:我继续在 iText 中修复了远程 gif 加载,它包含在 iText 5.4.1 及更高版本中。

Adding Image into Itext PDF is not possible through URL .无法通过 URL 将图像添加到 Itext PDF 中。 Only way to add image in PDF is download all images in to local directory and apply below code在PDF中添加图像的唯一方法是将所有图像下载到本地目录并应用以下代码

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.您用于向 IText PDF 添加图像的方式是用于添加本地文件的方式,而不是 URL。

For URLs, this way will solve the problem.对于 URL,这种方式可以解决问题。

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) .然后,您可以继续使用document.add(image)将此image添加到某个先前打开的document

For further reference, please visit the [ Java IText: Image docs ].如需进一步参考,请访问 [ Java IText: Image docs ]。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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