我正在使用webView.createPrintDocumentAdapter(jobname)使用名为PDFPrint的自定义类来打印PDF。这里是以下类的摘录:
function onMessage(event) {
var name = "";
if (event.message.text == "Im Bored") {
name = "You";
} else {
name = event.user.displayName;
}
var message = name + ": You could scrub accounts or make some calls. Have you logged into statflo today? ";
return { "text": message };
}
我的Activity通过以下方法使用此类:
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;
}
代码在生成PDF文件时按预期工作。但是我想在生成文件后打开它,但是我找不到正确的方法,我尝试覆盖某些方法,但是得到了一个没有内容的空pdf文件。
我想知道如何实现该功能,这里是打开文件的代码:
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");
}
答案 0 :(得分:0)
我的实现基于this answer:
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);
}