创建 PDF 后打开文件



我正在使用webView.createPrintDocumentAdapter(jobname(使用名为PDFPrint的自定义类打印PDF。以下是该类的摘录:

public PdfPrint(PrintAttributes p_atributos, aperturador_archivos mi_aperturador )
{
atributos = p_atributos;
aperturador = mi_aperturador;
}
public void print(final PrintDocumentAdapter printAdapter, final File path, final String filename)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
printAdapter.onLayout(null, atributos, null, new PrintDocumentAdapter.LayoutResultCallback() {
@Override
public void onLayoutFinished(PrintDocumentInfo info, boolean changed) {
printAdapter.onWrite(new PageRange[]{PageRange.ALL_PAGES},getOutputFile(path,filename),new CancellationSignal(), new PrintDocumentAdapter.WriteResultCallback() {
@Override
public void onWriteFinished(PageRange[] pages) {
super.onWriteFinished(pages);
}
});
}
},null);

}
}
private ParcelFileDescriptor getOutputFile(File path, String fileName) {
if (!path.exists()) {
path.mkdirs();
}
File file = new File(path, fileName);
try {
file.createNewFile();
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE);
} catch (Exception e) {
Log.e(TAG, "Failed to open ParcelFileDescriptor", e);
}
return null;
}

我的活动使用此方法使用此类:

private void createWebPrintJob(WebView webView) {
String jobName = getString(R.string.app_name) + " Document";
PrintAttributes attributes = new PrintAttributes.Builder()
.setMediaSize(PrintAttributes.MediaSize.ISO_A4)
.setResolution(new PrintAttributes.Resolution("pdf", "pdf", 600, 600))
.setMinMargins(PrintAttributes.Margins.NO_MARGINS).build();
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/PDFHYC/");
PdfPrint pdfPrint = new PdfPrint(attributes, this);
String[] titulo_split = mToolbar.getTitle().toString().split(" ");
pdfPrint.print(webView.createPrintDocumentAdapter(jobName) , path, titulo_split[0]+ "_"+  titulo_split[1]+ "_" + Long.toString(System.currentTimeMillis()).substring(1,6)+ ".pdf");
}

生成 PDF 文件时,代码按预期工作。但是我想在生成文件后打开文件,但我找不到正确的方法,我尝试覆盖一些方法,但我得到一个没有内容的空 pdf 文件。

我想知道如何实现该功能,这是我打开文件的代码:

public void abrir_pdf(String ruta) {
File file = new File(ruta);
Uri data = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(data, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
}

我的实现基于这个答案:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
FileProvider.getUriForFile(
MainActivity.this,
getApplicationContext().getPackageName() + ".provider",
pdfFile),
"application/pdf");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent chooserIntent =
Intent.createChooser(intent, getResources().getString(R.string.open_with));
try {
startActivity(chooserIntent);
} catch (ActivityNotFoundException e) {
showError(R.string.error_missed_pdf_reader);
}

相关内容

  • 没有找到相关文章

最新更新