javaandroidpdfprintingprintdocument

When passing PDF to printer app, grey letters are surrounded with black dots


My app creates printable worksheets with PDF format. I found a little problem when printing worksheets. The worksheets look perfect on my phone.

enter image description here

However, when sending the PDF to the printer driver app using PrintDocumentAdapter(), the letters of the resulting images waiting for printing become surrounded with random black dots, as shown in the picture: enter image description here

How can I fix this? Or is this an inherited limitation of the printing function that cannot be avoided?


Solution

  • Apparently the problem was that I used PrintedPdfDocument.writeTo(FileOutputStream()) to do the printing job, which was probably defective and resulted in the above artifact.

    I tried another approach to do the printing as described in here: https://stackoverflow.com/a/49298355/13869422 No more problem with this approach!

    Here is my final code that works:

        @Override
        public void onWrite(PageRange[] pageRanges, ParcelFileDescriptor ParcelFileDescriptor, CancellationSignal cancellationSignal, WriteResultCallback writeResultCallback) {
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                inputStream = getContentResolver().openInputStream(pdfUri);
                outputStream = new FileOutputStream(ParcelFileDescriptor.getFileDescriptor());
                byte[] buff = new byte[16384];
                int size;
                while ((size = inputStream.read(buff)) >= 0
                        && !cancellationSignal.isCanceled()) {
                    outputStream.write(buff, 0, size);
                }
                if (cancellationSignal.isCanceled()) {
                    writeResultCallback.onWriteCancelled();
                } else {
                    writeResultCallback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
                }
            } catch (Exception e) {
                writeResultCallback.onWriteFailed(e.getMessage());
            } finally {
                try {
                    inputStream.close();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }