我想从位图生成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();
}