【问题标题】:image from gallery is not displaying on pdf file in android来自画廊的图像未显示在 android 的 pdf 文件中
【发布时间】:2021-07-14 10:25:45
【问题描述】:

我正在尝试从我的 Android 应用程序中的图像创建 pdf。 我成功获取图像并成功创建了pdf文件。但是当我打开我的 pdf 文件时,没有显示图像。我在 Internet 上尝试了许多解决方案,但都是徒劳的。 我正在粘贴我的代码。请指导我。

首先我粘贴从图库中获取图像的代码

       Intent myIntent = new Intent(Intent.ACTION_PICK, 
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
             
              startActivityForResult(myIntent,120);

现在我正在粘贴 OnActivityResult 方法的代码,我在其中获取图像并创建一个 pdf 文件。

 try {
    Document doc = new Document();
    if (resultCode == RESULT_OK) {
        if (requestCode == 120) {
            if (data.getData() != null) {
               Uri uri   = data.getData();


               Image image = Image.getInstance(uri.toString());
               FileOutputStream fileOutputStream =openFileOutput("mypdf.pdf", Context.MODE_PRIVATE);
                   PdfWriter.getInstance(doc, fileOutputStream);
                   doc.open();
                   doc.add(image);

                   doc.close();


            }
        }
    }
    } catch (IOException | DocumentException e) {
        e.printStackTrace();
    }

【问题讨论】:

  • Image.getInstance(String) 需要一个文件系统路径,而您没有文件系统路径。
  • 我使用的路径也如下所示。图像图像 = Image.getInstance(uri.getPath());但什么也没有发生。图像未显示在 Pdf 上

标签: android itext


【解决方案1】:

在使用 iText 时,您需要创建 BitMap 格式的图像,然后需要添加到 pdf 中。

ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(contentResolver, <pass the uri of image>);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAbsolutePosition(470f,755f);
myImg.scaleToFit(100f,100f);
document.add(myImg);

【讨论】:

    【解决方案2】:

    我已经解决了,解决方法是使用输入流如下:

     Uri uri = data.getData();
            InputStream ims = getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(ims);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            Image image = Image.getInstance(byteArray);
            doc.add(image);
            doc.close();
    

    【讨论】:

      猜你喜欢
      • 2015-05-25
      • 1970-01-01
      • 2014-08-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多