【发布时间】:2019-11-26 21:47:42
【问题描述】:
我正在使用 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;
}
我的Activity通过这个方法使用这个类:
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.addFlag(Intent.FLAG_GRANT_READ_URI_PERMISSION);
标签: android file pdf android-asynctask