6

When User clicks on a button in UI, PrintManager generates Document which is to be printed. Then user click on Print icon to push print command.

Above part is done. But the requirement is : I want to remove user having to click the print icon (print icon shown in pic, which is generated by PrintDocumentAdapter)and generate/print document automatically.

Again : I have implemented the print functionality, I just want to remove user interaction. When below pic is generated, print command gets executed automatically, without user need to click the print icon.

enter image description here

kartic chaudhary
  • 206
  • 3
  • 12

3 Answers3

4

Don't use PrintManager, you can print with class PdfPrint.java from package android.print.

Put this code in java/android/print (outside your package)

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(final 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;
    }
}

And you can use code like this (print from webview)

private fun createWebPrintJob(webView: WebView, date: Long) {
        try {
            val jobName = getString(R.string.app_name) + " Document"
            val attributes = PrintAttributes.Builder()
                .setMediaSize(PrintAttributes.MediaSize.NA_LEGAL)
                .setResolution(PrintAttributes.Resolution("pdf", "pdf", 600, 600))
                .setMinMargins(PrintAttributes.Margins.NO_MARGINS).build()
            val path =
                Environment.getExternalStoragePublicDirectory("/pdf_output")

            val pdfPrint = PdfPrint(attributes)
            pdfPrint.print(
                webView.createPrintDocumentAdapter(jobName),
                path,
                "output_$date.pdf"
            )
            Log.i("pdf", "pdf created")
        } catch (e: Exception) {
            Log.e("pdf", " pdf failed e.localizedMessage")
        }
    }
utsmannn
  • 51
  • 5
  • I get pdf created but nothing prints – Nayef Radwi Feb 02 '22 at 08:22
  • @NayefRadwi it works fine , may be you should do this in onPageFinished call back for web view – Sherif farid Mar 13 '23 at 06:23
  • I am trying to print a PDF document that I have without going through the webview. But `PrintDocumentAdapter`, the first argument of the `print` method, is an abstract class. How do we pass it as a parameter? – Jungwon May 09 '23 at 04:46
1

The library "ipp-client-kotlin" supports silent printing of documents rendered in a format natively supported by the IPP printer (e.g. AirPrint or Mopria): https://github.com/gmuth/ipp-client-kotlin

IPP Nerd
  • 992
  • 9
  • 25
-2

For PrintManager implementation, you can take a look at below lines of code:

Source : https://developer.android.com/training/printing/custom-docs.html

private void doPrint() {
    // Get a PrintManager instance
    PrintManager printManager = (PrintManager) getActivity()
            .getSystemService(Context.PRINT_SERVICE);

    // Set job name, which will be displayed in the print queue
    String jobName = getActivity().getString(R.string.app_name) + " Document";

    // Start a print job, passing in a PrintDocumentAdapter implementation
    // to handle the generation of a print document
    printManager.print(jobName, new MyPrintDocumentAdapter(getActivity()),
            null); //
}
  • I have done all this. Have you read the question where i wrote, above part is done. – kartic chaudhary Feb 02 '18 at 09:34
  • Okay great and yes I didn't see it. So are you trying to implement "Custom Document Printing" in which you can just bypass the clicking of "default print icon" button? – Abhijeet Singh Feb 02 '18 at 09:51
  • @karticchaudhary Please look at the below link for the "Custom document printing" and check if it is useful to your requirements: http://www.techotopia.com/index.php/An_Android_Studio_Custom_Document_Printing_Example – Abhijeet Singh Feb 02 '18 at 10:04