I am implementing custom document printing using Android’s Print Framework.
Using the Android's documentation link as reference: https://developer.android.com/training/printing/custom-docs
The flow I am using is PrintManager to display the print picker, implementing PrintDocumentAdapter, then creating the PDF inside onWrite() using PrintedPdfDocument by calling startPage(), drawing content on the Canvas, calling finishPage(), and finally writing the document to the ParcelFileDescriptor passed by the framework.
The Android documentation states that if the work inside onWrite() cannot be completed quickly, it may be executed on a worker thread. However, PrintedPdfDocument (and the underlying PdfDocument) is not thread-safe and only allows one page to be open at a time. This becomes problematic in a multithreaded application where page rendering is expensive and consists of layout computation, bitmap generation, text shaping, and other CPU-heavy operations that ideally should be done in parallel.
In my application, multiple background tasks generate data required to draw each page, but every page still requires mandatory calls to startPage() and finishPage(), both of which operate on a non-thread-safe object. This makes it unclear how to correctly integrate parallel rendering logic with the single-threaded requirement of PrintedPdfDocument.
What is the correct threading model for using Android’s Print Framework in this situation? How should background rendering tasks interact with onWrite() safely when PDF generation itself must remain sequential?