I'm using webView.createPrintDocumentAdapter(jobname) to print a PDF using a custom class called PDFPrint. Here an extract of the class Below:
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;
}
This class is used by my Activity with this method:
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");
}
The code works as intended when generating the PDF file. But I want to open the file after has been generated, but I can't find the correct way to do so, I've tried overriding some methods but I get an empty pdf file with no content.
I want to know how can I implement that functionality, here my code for opening the file:
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);
}