代码之家  ›  专栏  ›  技术社区  ›  Expiredmind

将位图中的PDF保存到内部存储或按意图发送

  •  0
  • Expiredmind  · 技术社区  · 7 年前

    我想从位图生成PDF,但我不想使用外部存储(在所有示例中,如何使用外部存储,但我不想强制用户在手机中使用SD卡)。我想通过intent共享我的PDF,通过电子邮件发送或存储在GoogleDrive/电话存储中。我正在使用 Itext library .

    目前,我无法将其保存在内部存储器上(我在尝试保存时遇到“打开文件时出错:src”Toast),而且google驱动器和邮件发送也失败(收到消息,文件无法上载/附加)

    代码:

        Bitmap bitmap = loadBitmapFromView(view);
        //Now create the name of your PDF file that you will generate
        File pdfFile = new File(CreatePDFActivity.this.getFilesDir(), "myPdfFile.pdf");
    
        try {
            Document document=new Document();
    
            PdfWriter.getInstance(document,new FileOutputStream(pdfFile.getAbsolutePath())); //  Change pdf's name.
            document.open();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            Image img =Image.getInstance(stream.toByteArray());  // Change image's name and extension.
    
            float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
                             - document.rightMargin() - 0) / img.getWidth()) * 100; // 0 means you have no indentation. If you have any, change it.
    
            img.scalePercent(scaler);
            img.setAlignment(Image.ALIGN_CENTER | Image.ALIGN_TOP);
    
    
            document.add(img);
            document.close();
    
    
            Intent intent = new Intent(Intent.ACTION_SEND);
    
            intent.putExtra(Intent.EXTRA_SUBJECT, "Test ");
            Uri uri = Uri.fromFile(new File( CreatePDFActivity.this.getFilesDir(), "myPdfFile.pdf"));
            intent.putExtra(Intent.EXTRA_STREAM, uri);
            intent.addFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION );
            intent.setType("application/pdf");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   CommonsWare    7 年前

    在所有的例子中,他们都使用外部存储,但我不想强迫用户在手机中安装SD卡

    External storage 不是 removable storage . 在目前使用的大约99%的Android设备上,外部存储不是SD卡。

    我在尝试保存时遇到了一个“打开文件时出错:src”Toast

    没有 Toast 在您问题中的代码中。

    google驱动器和邮件发送也失败(收到无法上载/附加文件的消息)

    第三方应用无法访问您的应用的 internal storage . 此外,一旦您提高 targetSdkVersion 至24或更高。使用 FileProvider 使保存在内部存储上的文件可供第三方应用程序使用。