2

I have made an android app in that i have tried to print a sample text file,I want to use wifi connected printers,I tried this linkWifi printing in android But it only goes to searching wifi printer and do nothing,MY code is as below,Please help me and save my life

code

public class MainActivity extends Activity {

    public int pageHeight;
    public int pageWidth;
    public PdfDocument myPdfDocument;
    public int totalpages = 4;
    Button button1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button1 = (Button) findViewById(R.id.button1);

    }

    PrintDocumentAdapter pda = new PrintDocumentAdapter() {

        @Override
        public void onWrite(PageRange[] pages,
                ParcelFileDescriptor destination,
                CancellationSignal cancellationSignal,
                WriteResultCallback callback) {
            InputStream input = null;
            OutputStream output = null;

            try {

                input = getAssets().open("sample.txt");
                output = new FileOutputStream(destination.getFileDescriptor());

                byte[] buf = new byte[1024];
                int bytesRead;

                while ((bytesRead = input.read(buf)) > 0) {
                    output.write(buf, 0, bytesRead);
                }

                callback.onWriteFinished(new PageRange[] { PageRange.ALL_PAGES });

            } catch (FileNotFoundException ee) {
                // Catch exception
            } catch (Exception e) {
                // Catch exception
            } finally {
                try {
                    input.close();
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @SuppressLint("InlinedApi")
        @Override
        public void onLayout(PrintAttributes oldAttributes,
                PrintAttributes newAttributes,
                CancellationSignal cancellationSignal,
                LayoutResultCallback callback, Bundle extras) {

            if (cancellationSignal.isCanceled()) {
                callback.onLayoutCancelled();
                return;
            }

            //int pages = computePageCount(newAttributes);

            PrintDocumentInfo pdi = new PrintDocumentInfo.Builder(
                    "Name of file").setContentType(
                    PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();

            callback.onLayoutFinished(pdi, true);
        }
    };

    @SuppressLint("InlinedApi")
    public void printDocument(View view) {
        PrintManager printManager = (PrintManager) this
                .getSystemService(Context.PRINT_SERVICE);
        String jobName = this.getString(R.string.app_name) + " Document";
        printManager.print(jobName, pda, null);
    }

}

manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.wifiprint"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <uses-feature android:name="android.hardware.wifi" />

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Community
  • 1
  • 1
jigar jims
  • 129
  • 1
  • 12

1 Answers1

0

You should make button listener first for button event.

    Button button1 = (Button) findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            doCustomPrint();
        }
    });

And this print method for custom document print;

    private void doCustomPrint() {

    PrintDocumentAdapter pda = new PrintDocumentAdapter(){

        @Override
        public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){
            InputStream input = null;
            OutputStream output = null;

            AssetManager assetManager = getAssets();

            try {
                // File for print.
                input = assetManager.open("abc.pdf");
                output = new FileOutputStream(destination.getFileDescriptor());

                byte[] buf = new byte[1024];
                int bytesRead;

                while ((bytesRead = input.read(buf)) > 0) {
                     output.write(buf, 0, bytesRead);
                }

                callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});

            } catch (FileNotFoundException ee){
                //Catch exception
            } catch (Exception e) {
                //Catch exception
            } finally {
                try {
                    input.close();
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){

            if (cancellationSignal.isCanceled()) {
                callback.onLayoutCancelled();
                return;
            }

            PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("print_doc.pdf").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();
            callback.onLayoutFinished(pdi, true);
        }
    };

    PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE);
    String jobName = this.getString(R.string.app_name) + " Document";
    printManager.print(jobName, pda, null);
}

And check this documents.

http://developer.android.com/training/printing/index.html

How to Print PDF using Android 4.4 Printing framework

Community
  • 1
  • 1
Charles
  • 139
  • 6
  • wait..for my update on question,My dear friend i already declared it within my xml..like this android:onClick="printDocument",SO it will be directly call tat function,is it?after clicking that button it opens a popup for pagelayouts and find printers,when i select all printers it goes to finding printers and nothing happens afterwards,,,! – jigar jims May 15 '15 at 07:00
  • have you read my question really?i already mentioned that link that you've send me...with no luck ..:( – jigar jims May 15 '15 at 07:01
  • Print function needs API Level 19. Please have a test minSdkVersion to 19 from 8, and don't forget add android-support-v4.jar lib to your libs. – Charles May 15 '15 at 07:06
  • can you please tell me what problems may be possible if no printer discovered? – jigar jims May 15 '15 at 07:10
  • ok dear,Please wait i am change as per suggested,and let you know,Thanks for help – jigar jims May 15 '15 at 07:17
  • Hello i have changed minsdkversion to 19 but still nothing is happening,it just searches the printers. – jigar jims May 15 '15 at 07:59
  • This is my sample project for printing directly from android device. I have tested this with wi-fi printer and wi-fi direct printer. https://dl.dropboxusercontent.com/u/12033943/test.zip 1) API Level 19 in manifest 2) 'android-support-v4.jar' library in your libs folder. 3) printer connection in local network. 4) check your phone setting > wifi > wifi network or wifi direct for printer connection. – Charles May 15 '15 at 08:42
  • 1
    Is there any solution because I am facing same issue – Munir Feb 14 '17 at 12:11