【问题标题】:How to send PDF converted from base64 through Intnet?如何通过 Internet 从 base64 发送 PDF 转换?
【发布时间】:2017-09-08 11:35:20
【问题描述】:

我在base64 中有pdf 文件,我对其进行了解码,通过Intent 发送但不幸的是外部应用程序无法读取它(Evernote 例如说它可以'不打开空文件)。另一个奇怪的是,我在转换后的列表中没有像 Adobe ReaderMessanger 这样的应用程序。这是我的代码:

FileOutputStream fos;
fos = context.openFileOutput("doc.pdf", Context.MODE_PRIVATE);
String fileB64 = url.split(",")[1];
byte[] decodedStr = Base64.decode(fileB64, Base64.NO_WRAP);
fos.write(decodedStr);
Intent sendIntent = new Intent();
sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sendIntent.setAction(Intent.ACTION_SEND);
File filePath = new File(String.valueOf(context.getFilesDir()));
File newFile = new File(filePath, "application/pdf");
sendIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".FileProvider", newFile));
sendIntent.setType("application/pdf");
context.startActivity(sendIntent);
fos.flush();
fos.close();

我也尝试使用在线转换器来检查转换是否正常。我有这样的东西:

%PDF-1.3
3 0 obj
<</Type /Page
/Parent 1 0 R
/Resources 2 0 R
/MediaBox [0 0 348.00 256.00]
/Contents 4 0 R
>>
endobj
4 0 obj
<</Length 11287>>
stream
1.000 0.000 0.000 -1.000 0.000 256.000 cm
0.20 w
0 G
q
1.000 0.000 0.000 1.000 0.000 0.000 cm
q
/F9 16 Tf
/F9 12 Tf
q
q
Q
q
Q
Q
q
Q
q
/GS1 gs
1.000 0.000 0.000 1.000 0.000 0.000 cm
0.000 0.000 m 
348.000 0.000 l
348.000 0.000 348.000 0.000 348.000 0.000 c
348.000 256.000 l
348.000 256.000 348.000 256.000 348.000 256.000 c
0.000 256.000 l

为了避免“这是一张图片,你为什么不把它作为图片发送”之类的答案我可以告诉你,这只是我转换的另一种选择。我的转换和作为图像共享它完美无缺。感谢您的时间和任何帮助!

@EDIT

我改变了这一行: File newFile = new File(filePath, "application/pdf"); 对此: File newFile = new File(filePath, "doc.pdf");

但现在我得到了pdf格式的空白页。

【问题讨论】:

  • 确保文件保存正确,如果没有其他可用的外部应用程序,请尝试在 webview 中加载文件。
  • @SARATHV 好吧,正如我所说,有可用的应用程序:Evernote 或 Gmail。他们说:“无法读取空文件”。你读过这篇文章吗?
  • @SARATHV 我为图像导出做了同样的保存,它可以工作,为什么它在这里会出错?

标签: android pdf android-intent base64


【解决方案1】:

错误 #1:您打开一个文件,然后在完成对文件的处理之前尝试将其交给另一个应用程序(flush()、缺少的getFD().sync()close()

错误 #2:您正在主应用程序线程上执行磁盘 I/O。

错误 #3:您正试图将整个解码的 PDF 读入堆空间,这对于许多 PDF 文件来说会失败,因为它们太大了。

错误 #4:newFile 不指向您尝试创建的文件,而是指向路径中带有 application/pdf 的某个文件。因此,其他应用无法访问您的 PDF,即使它已完全写入磁盘。

错误 #5:您在 Intent 上没有 FLAG_GRANT_READ_URI_PERMISSION,因此第三方应用可能没有读取您的内容的权限(请参阅 the docs 中的第三个项目符号)。

【讨论】:

  • 我对图像做了同样的事情,唯一的区别是 application/pdf 这里。那为什么呢?我的意思是 Bug#4 主要是
  • @soommy12:File newFile = new File(filePath, "application/pdf")。我不知道您为什么要在其中放置 MIME 类型。您的openFileOutput() 呼叫正在使用"doc.pdf"。我强烈建议您创建一次File 对象并在两个地方使用它:用于编写文件(在File 上创建FileOutputStream)和获取您的Uri
  • 好吧,我只是利用我另一篇文章中的建议
  • 你能发布一些代码吗?我不明白你要告诉我什么
  • @soommy12:将File newFile = new File(filePath, "application/pdf") 替换为File newFile = new File(filePath, "doc.pdf")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
相关资源
最近更新 更多