Search This Blog

Saturday 30 August 2014

Print the custom document

In android mobile we can print the simple ,HTML and custom document with using android camera system.for know how to print simple images and the HTML document then click here http://androidbasedapplication.blogspot.in/2014/08/print-photos-through-android-camera.html  .Here i will tell you how to print the custom document.

Printing the custom document:

In android system some application is focus on the graphics layouts. many application available today like a drawing application , page layout applications etc. today you can creating a beautiful page layout easily. you can printed your page layouts as per your document.page layout include the margin also like header ,footer body alignment and graphics element. 

How to connect print manager :

For print out the custom document first of all you need to connect the your android camera with the print device. for connect the print device you need some android print framework and also need the print manager class. This class allow to you initialize print manager and beaning the print life cycle. Here use this code and see the how print manger connect to the android camera.

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); //
}

Create a print adapter :

After call the print manger() method now it's time to initialize adapter method which instance provide handling of the printing life cycle.here i will call printDocumentAdapter() method . it is abstract class. it having a 4 main call back methods.the four method is that on start(),on layout(),on write() and on finish() . The printDocumentAdapter() implement in to on layout step of life cycle. The execution of the on layout() method can have 3 out comes completion , cancellation and failure. see below.

@Override
public void onLayout(PrintAttributes oldAttributes,
                     PrintAttributes newAttributes,
                     CancellationSignal cancellationSignal,
                     LayoutResultCallback callback,
                     Bundle metadata) {
    // Create a new PdfDocument with the requested page attributes
    mPdfDocument = new PrintedPdfDocument(getActivity(), newAttributes);

    // Respond to cancellation request
    if (cancellationSignal.isCancelled() ) {
        callback.onLayoutCancelled();
        return;
    }

    // Compute the expected number of printed pages
    int pages = computePageCount(newAttributes);

    if (pages > 0) {
        // Return print information to print framework
        PrintDocumentInfo info = new PrintDocumentInfo
                .Builder("print_output.pdf")
                .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
                .setPageCount(pages);
                .build();
        // Content layout reflow is complete
        callback.onLayoutFinished(info, true);
    } else {
        // Otherwise report an error to the print framework
        callback.onLayoutFailed("Page count calculation failed.");
    }
}

NOTE: The Boolean parameter of the on layout finish() method indicts whether or not the layout content has actually changed since the last request.setting this parameter properly allows the print framework to avoid unnecessary calling the on write() method  ,essentially catching the previously written print document and improving performance. 

Print the document file:

Now its time to print out document file from the print device here we already set the layouts as per our documents.Android print framework call the on write() method.of your applications PrintDocumnetAdapter() class.This method specify which pages should be written and the output file to be used.some times document in to the PDF file so you just need a printDocumentFile() class to print the PDF file. you can easily add the elements on the page layouts.which are given below. 

@Override
public void onWrite(final PageRange[] pageRanges,
                    final ParcelFileDescriptor destination,
                    final CancellationSignal cancellationSignal,
                    final WriteResultCallback callback) {
    // Iterate over each page of the document,
    // check if it's in the output range.
    for (int i = 0; i < totalPages; i++) {
        // Check to see if this page is in the output range.
        if (containsPage(pageRanges, i)) {
            // If so, add it to writtenPagesArray. writtenPagesArray.size()
            // is used to compute the next output page index.
            writtenPagesArray.append(writtenPagesArray.size(), i);
            PdfDocument.Page page = mPdfDocument.startPage(i);

            // check for cancellation
            if (cancellationSignal.isCancelled()) {
                callback.onWriteCancelled();
                mPdfDocument.close();
                mPdfDocument = null;
                return;
            }

            // Draw page content for printing
            drawPage(page);

            // Rendering is complete, so page can be finalized.
            mPdfDocument.finishPage(page);
        }
    }

    // Write PDF document to file
    try {
        mPdfDocument.writeTo(new FileOutputStream(
                destination.getFileDescriptor()));
    } catch (IOException e) {
        callback.onWriteFailed(e.toString());
        return;
    } finally {
        mPdfDocument.close();
        mPdfDocument = null;
    }
    PageRange[] writtenPages = computeWrittenPages();
    // Signal the print framework the document is complete
    callback.onWriteFinished(writtenPages);

    ...
}

Drawing a PDF page content:

Wen you print the document in a android frame work you must need the PDF generate document so you need to convert documents in to PDF . Here you can use the PDF generation library for generation purpose here printPdfdocument () class used. this class used the canvas object to draw the elements on a PDF page.
private void drawPage(PdfDocument.Page page) {
    Canvas canvas = page.getCanvas();

    // units are in points (1/72 of an inch)
    int titleBaseLine = 72;
    int leftMargin = 54;

    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setTextSize(36);
    canvas.drawText("Test Title", leftMargin, titleBaseLine, paint);

    paint.setTextSize(11);
    canvas.drawText("Test paragraph", leftMargin, titleBaseLine + 25, paint);

    paint.setColor(Color.BLUE);
    canvas.drawRect(100, 100, 172, 172, paint);
}

When using the canvas to draw on a PDF page elements are specified in points , which is 1/72 of an inch. Make sure the which units are using in the draw elements is correct. for positioning of drawing elements ,the coordinate system starts at 0,0 for the corner of the page.   

6 comments:

  1. Thanks for writing such useful blog...

    ReplyDelete
  2. Thankyou for printing document

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. how we are getting total no of pages here?

    ReplyDelete
  5. Where is MyPrintDocumentAdapter function??

    ReplyDelete
  6. I stil confuse how to cunstruct the all code, and how to put in activity?

    ReplyDelete