【问题标题】:Adding image to PDF, Android Studio将图像添加到 PDF、Android Studio
【发布时间】:2018-11-27 10:45:52
【问题描述】:

我正在使用 iTextGAndroid Studio 中开发应用程序,您可以在其中填写表格,单击按钮,然后您会收到 PDF。我需要在文档末尾添加一张图片。

按下按钮后,应用程序崩溃并显示“MyApp 已停止”。但是它会创建 PDF 文件,但它是空的,我无法打开它。

这是我的代码(在负责创建文档的函数中):

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

所以我检查了用法,添加图片的一种方法是通过 URL,所以我将其上传到 imgur。

document.open();
document.add(data);
document.add(test);
document.close();

我正在将段落添加到文档中。没有它,我的应用程序正在使用我打算包含的所有数据创建正确的文档。唯一的问题是添加图像。

你能帮我解决这个问题吗?

【问题讨论】:

  • 我认为我从未见过有人创建这样的图像:new Jpeg(logoJock)。你为什么不使用Image.getInstance(logoJock)?此外:每次创建 PDF 时都需要从 Web 下载图像的设计是一个糟糕的设计:它使用了太多数据。您应该在设备上缓存图像。当您不涉及 PDF 而是以 byte[] 下载应用程序时,您的应用程序是否会崩溃?
  • 是的,我承认,这是一个糟糕的设计,但这是我必须检查的最后一个想法。通过 image.getInstance() 获取实例;是显而易见的选择,但它不起作用。查看我的评论以查看解决方案。

标签: android android-studio itext pdf-generation itextg


【解决方案1】:

问题解决了,

我尝试了这个,我尝试了 image.getInstance(path),我尝试了其他可能性,最后这个成功了(我必须将我的徽标文件移动到 assets 文件夹):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    相关资源
    最近更新 更多