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.   

Wednesday 27 August 2014

print the photos through android camera

Print images: 

In now days taking photos and sharing in social sites and chat application is normal in now days. all these thing we can done by mobile or tablets we don't need desktop or laptop. if your mobile device allow to user taking a photos and sharing them in social sites then it also allow to print the that photos.in all android device having a android support library which provide the function of the enabling the print the photos . these function use the minimal amount of code for print the images.

Here for print the images using the V4 support library and printHelper class.

How to print images:

private void doPhotoPrint() {
    PrintHelper photoPrinter = new PrintHelper(getActivity());
    photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
            R.drawable.droids);
    photoPrinter.printBitmap("droids.jpg - test print", bitmap);
}

as sow in above for print the images it uses a print helper class in simply way. it has a single layout option setScalmode(). these class provide the select the one of the two option:

1) SCALE_MODE_FIT:  This option provide the sizes the images so that whole images show with in a printable area of the page.

2) SCALE_MODE_FILL: This option scales so that fills the printable area of the page.here choose this option means your images will be crop. it means some part of the images like bottom area or some part of edges of images or top area will be not display.

These method can called as action for menu item but some times these menu item not supported so it will be put in to the over flow menu.

Here printHelper class called the printBitmap() method. after calling that method no further action required by your application . User have two option when it uses a print option 1) print images and 2) cancel the process. if user choose first then it job on the print the images and notification appear on to the system bar. 


Print the HTML document:

here this feature provide to you additional content in your printouts beyond just print the images.here android requires composing text and graphics in a print document. the android 4.4 provide the web view class for enable print the HTML document. The class allow to you load a local HTML document resource and download from the web.  

Load the HTML document:

Print the HTML document with the webview involves loading an HTML building or resources of HTML as a string.this portion describe how to load an HTML documents in webview  for printing.
private WebView mWebView;
private void doWebViewPrint() {
    // Create a WebView object specifically for printing
    WebView webView = new WebView(getActivity());
    webView.setWebViewClient(new WebViewClient() {

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i(TAG, "page finished loading " + url);
                createWebPrintJob(view);
                mWebView = null;
            }
    });

    // Generate an HTML document on the fly:
    String htmlDocument = "<html><body><h1>Test Content</h1><p>Testing, " +
            "testing, testing...</p></body></html>";
    webView.loadDataWithBaseURL(null, htmlDocument, "text/HTML", "UTF-8", null);

    // Keep a reference to WebView object until you pass the PrintDocumentAdapter
    // to the PrintManager
    mWebView = webView;
}

Create a print job :

private void createWebPrintJob(WebView webView) {

    // Get a PrintManager instance
    PrintManager printManager = (PrintManager) getActivity()
            .getSystemService(Context.PRINT_SERVICE);

    // Get a print adapter instance
    PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();

    // Create a print job with name and adapter instance
    String jobName = getString(R.string.app_name) + " Document";
    PrintJob printJob = printManager.print(jobName, printAdapter,
            new PrintAttributes.Builder().build());

    // Save the job object for later status checking
    mPrintJobs.add(printJob);
}  
After loading an HTML content in to the webviwe then it's time for the create a job for print that document. Here printManager class uses for print the document.This example saves an instance of the projectjob object for use by the application  which is not required  . your application may uses this object of track the progress of  the print job as it's being .

This approach is useful when you want to promote the status of the print the document in your application for completion, failure or user cancellation.creating application notification is not required because the print framework automatically creates a system notification for the print job.

Sunday 24 August 2014

Develop camera part 3

How to take a picture:

For taking a picture you can use this Camera.takePicture()  method.this method start after once preview start.you can use this method Camera.PictureCallback and Camera.ShutterCallback objects pass in to Camera.takePicture().

If you want to grab images continously, you can create a Camera.PreviewCallback that implements onPreviewFrame(). For something in between, you can capture only selected preview frames, or set up a delayed action to call takePicture().

How to restart preview:

After once start and take the picture . you must restart preview before take the picture in this example . here restart is done by overloading the shutter button 

@Override
public void onClick(View v) {
    switch(mPreviewState) {
    case K_STATE_FROZEN:
        mCamera.startPreview();
        mPreviewState = K_STATE_PREVIEW;
        break;

    default:
        mCamera.takePicture( null, rawCallback, null);
        mPreviewState = K_STATE_BUSY;
    } // switch
    shutterBtnConfig();
}

Stop the preview and release the camera :

After the using the camera you need to stop and release that camera it's called the clean up time.this is the last step of the using camera .here stop means release the camera object. now here if you don't know what is camera object and how it will be create then use this link click here :http://androidbasedapplication.blogspot.in/2014/07/develop-camera-using-eclips.html 

Now you have a question about when you should release the camera ? then i will tell you that having your preview surface destroyed is a pretty good hint that it's time to stop preview and release the camera  tis method from the preview class.

public void surfaceDestroyed(SurfaceHolder holder) {
    // Surface will be destroyed when we return, so stop the preview.
    if (mCamera != null) {
        // Call stopPreview() to stop updating the preview surface.
        mCamera.stopPreview();
    }
}
/**
 * When this function returns, mCamera will be null.
 */
private void stopPreviewAndFreeCamera() {

    if (mCamera != null) {
        // Call stopPreview() to stop updating the preview surface.
        mCamera.stopPreview();
    
        // Important: Call release() to release the camera for use by other
        // applications. Applications should release the camera immediately
        // during onPause() and re-open() it during onResume()).
        mCamera.release();
    
        mCamera = null;
    }
}
Earlier in the lesson, this procedure was also part of the setCamera() method, so initializing a camera always begins with stopping the preview.

if you wants to print the contain then follow here 

Print contain :

After the using the camera if you wants to print that contain and you wants to send your friend then refer this domain print contain. 

in android 4.4 and higher frame work provide the printing images and document directly from the your android application here you can print the 3 types contain given below:
1)print the image 

2)print the HTML document

3)print the custom document 
Being able to print information from your android application gives users a way to see a larger version of the content from the application or share it with another person who is not using your application . Printing also allows then to create a shanp shot  of the content  that does not depend on having a device, sufficient battery power or a wireless network connection

Friday 22 August 2014

develop camera part 2

How to create the camera view:

        Here i will show you how to create the camera view go to this link you will see that how to open the camera object   
http://androidbasedapplication.blogspot.in/2014/07/develop-camera-using-eclips.html

         Normally when we use the camera we need to see the preview of that subject before we clicking on shutter. you can see the  SurfaceView to draw of preview of what the camera sensor is picking up. here i will develop the camera view.

Preview class:  
         
          To get start with with displaying a preview, you need a preview class.it requires the implement of android.view.SurfaceHolder.Callback  the interface, which used to pass image data from the camera hardware to application.the preview class must be pass to the camera object before the live image preview can be started .

class Preview extends ViewGroup implements SurfaceHolder.Callback {

    SurfaceView mSurfaceView;
    SurfaceHolder mHolder;

    Preview(Context context) {
        super(context);

        mSurfaceView = new SurfaceView(context);
        addView(mSurfaceView);

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = mSurfaceView.getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
...
}

set and start preview:

A camera is instance and its related preview must be created in specific Oder with the camera object being the first.in the below snippet, the process of initializing the camera is encapsulated    so that Camera.startPreview()is called by the setCamera()  method.whenever user does something to change in the camera. The preview must also be restarted in the preview class surfaceChanged() call back method.

public void setCamera(Camera camera) {
    if (mCamera == camera) { return; }
    
    stopPreviewAndFreeCamera();
    
    mCamera = camera;
    
    if (mCamera != null) {
        List<Size> localSizes = mCamera.getParameters().getSupportedPreviewSizes();
        mSupportedPreviewSizes = localSizes;
        requestLayout();
      
        try {
            mCamera.setPreviewDisplay(mHolder);
        } catch (IOException e) {
            e.printStackTrace();
        }
      
        // Important: Call startPreview() to start updating the preview
        // surface. Preview must be started before you can take a picture.
        mCamera.startPreview();
    }
}

Modify camera setting :

camera setting changes the way that the camera takes picture, from the zoom level to exposure compensation. this example changes only preview size , see the source code of the camera application for many more.
 
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    // Now that the size is known, set up the camera parameters and begin
    // the preview.
    Camera.Parameters parameters = mCamera.getParameters();
    parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
    requestLayout();
    mCamera.setParameters(parameters);

    // Important: Call startPreview() to start updating the preview surface.
    // Preview must be started before you can take a picture.
    mCamera.startPreview();
}
      

set the preview orientation : 

most of camera application lock the display into landscape mode becuse that is natural orientation of the camera sensor. this setting does not prevent you from taking portrait-mode photos,   because the orientation the device is recorded in the EXIF header. the method lets you change how the preview is displayed with out affecting how the images is recorded . However in android prior level to API level .you must stop your preview before changing the orientation and then restart it. 


Monday 18 August 2014

promote your products online

If you run a large e commerce website or just sell products online in your spare time at home, there have never been a greater number of places to promote or even sell your products online.using the social media network you can easily promote your products and get the review about your products. Some of these platforms work well alongside your main website, some have replaced the need for an e commerce site entirely and work as a standalone solution for Internet-based sales and promotion.
 there are many types of the marketing online
  • Using the social sites 
  • Own web sites 
  • Email
  • Paid marketing 
Using the social sites: today people using lots of social sites like facebook twitter,netlog etc. using that social sites we make a advertise of our  products and also we can get the easily publicity and also we can get the opinion from the users. by this opinion we can made the corrections in our products. social sites effort the maximum selling rate with a minimum selling price.social sites publish a products world level. you can find out the user from all over world.if you have a video audio or attractive images of your products you can promote the your products easily. you can add the that all videos easily. you must have add the video or steps for how to use the your products.

Own web sites : if you ave your own domain like your sites or webpage then you can promote your products easily.  if you have many types of products to sell all these products are from the same platform then best way of your products is that you have to make the one site of your products. this domain is your's own you don't need to pay for the promote your products.

Email: email useful for the promote the products.by using the email you can stay touch with your customers and your product's user. email provides the community features. these community provides the free of charge publicity of your products. community is the best option for promoting your products.


Paid marketing : paid marketing is one of the best option promote the products to find out the real users and the get the maximum positive appearance of user number.In now days online paid marketing is the available at 1$ to 10 $ .blog, twitter and facebook social sites are top online paid marketing currently. lots of people connect with social sites and number of user increment more and more. 


if you wants to promote your products in blog then refer this link http://www.fiverr.com/dishasudani/do-promote-your-product-in-my-daily-blog. i will help to you for promote your products in my daily blog  i wiil also post about your products in my dailly blog.