【问题标题】:Add image to PDF from a URL?从 URL 将图像添加到 PDF?
【发布时间】:2013-04-02 09:05:51
【问题描述】:

我正在尝试将 URL 地址中的图像添加到我的 pdf 中。代码是:

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

但它不起作用。有什么问题?

【问题讨论】:

  • 您是否尝试先将其下载到 temp 文件夹然后添加到 pdf 中?

标签: java image itext


【解决方案1】:

这是使用 iText 从远程位置加载 .gif 时的一个已知问题。

对此的解决方法是使用 Java 下载 .gif(而不是通过 iText 的 Image 类的 getInstance 方法)并在 Image 类的 getInstance 方法中使用下载的字节。

编辑: 我继续修复了 iText 中的远程 gif 加载,它包含在 iText 5.4.1 及更高版本中。

【讨论】:

  • 不,似乎也不起作用:URL url = new URL("http://blog.phonehouse.es/wp-content/uploads/2013/01/Google.jpg"); InputStream in = new BufferedInputStream(url.openStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int n = 0; while (-1!=(n=in.read(buf))) { out.write(buf, 0, n); } out.close(); in.close(); byte[] response = out.toByteArray(); Image image=Image.getInstance(response);
  • 我实际上在 iText 中修复了这个问题:sourceforge.net/p/itext/code/5741
  • 我已经为 iText 5.4.1(今天发布)修复了这个问题,你能用你的代码确认一下吗?
【解决方案2】:

无法通过 URL 将图像添加到 Itext PDF 中。 在 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();
            }

【讨论】:

    【解决方案3】:

    您用于向 IText PDF 添加图像的方式是用于添加本地文件的方式,而不是 URL。

    对于网址,这种方式可以解决问题。

    String imageUrl = "http://www.google.com/intl/en_ALL/" 
                      + "images/logos/images_logo_lg.gif";
    
    Image image = Image.getInstance(new URL(imageUrl));
    

    然后您可以继续将此image 添加到以前打开的document,使用document.add(image)

    如需进一步参考,请访问 [Java IText: Image docs]。

    【讨论】:

    • 一个解释将使这个成为一个答案。
    • 这并没有提供问题的答案。一旦你有足够的reputation,你就可以comment on any post;相反,provide answers that don't require clarification from the asker。 - From Review
    • 即使一个答案只有代码,它仍然被认为是一个答案。不要说它不是一个答案,然后尝试删除它@DebosmitRay
    • @Zizouz212 我明白你在说什么。根据可用的“桶”,这似乎是最合适的桶。 这是一个非常低质量的答案。问题说... But it does not work. What can be wrong?。这能回答问题吗? 没有。因此,它没有提供问题的答案。
    • @DebosmitRay 这是一个低质量的答案,但不足以删除。见:meta.stackoverflow.com/questions/287563/…
    猜你喜欢
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    相关资源
    最近更新 更多