-
-
Save brettwold/838c092329c486b6112c8ebe94c8007e to your computer and use it in GitHub Desktop.
package android.print; | |
import android.os.CancellationSignal; | |
import android.os.ParcelFileDescriptor; | |
import android.util.Log; | |
import java.io.File; | |
public class PdfPrint { | |
private static final String TAG = PdfPrint.class.getSimpleName(); | |
private final PrintAttributes printAttributes; | |
public PdfPrint(PrintAttributes printAttributes) { | |
this.printAttributes = printAttributes; | |
} | |
public void print(PrintDocumentAdapter printAdapter, final File path, final String fileName) { | |
printAdapter.onLayout(null, printAttributes, 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; | |
} | |
} |
thank you!
The empty file problem is because of the webview rendering time.
The pdfPrint method finishes writing to the file even before the webView finishes rendering.
I decided to render the webview underneath, before clicking the button to call pdfPrint.
So that will allow time for the webview to render.
The empty file problem is because of the webview rendering time. The pdfPrint method finishes writing to the file even before the webView finishes rendering. I decided to render the webview underneath, before clicking the button to call pdfPrint. So that will allow time for the webview to render.
@marlonngalvao do you have sample gist for this?
The empty file problem is because of the webview rendering time. The pdfPrint method finishes writing to the file even before the webView finishes rendering. I decided to render the webview underneath, before clicking the button to call pdfPrint. So that will allow time for the webview to render.
can you elaborate on that, do i have to use setWebviewClient and onPageFinished??, while i have tried that, the webview never reaches the onPageFinished and pdf is never loaded in webview, how am i supposed to send the pdf for printing?
This worked!