2011-05-24 133 views
5

嗨在我的應用程序中,我想直接將我的數據從我的Android手機發送到我的網絡打印機以打印出來。我怎樣才能做到這一點?Android直接打印到網絡打印機?

我也想提供規格如佈局,副本,頁面範圍等。我怎樣才能直接從我的Android手機檢測我的打印機,並給予打印命令?

+0

您使用的是藍牙打印機? – Sujit 2011-05-24 07:20:49

+0

我已經寫了一個寫入藍牙打印機的應用程序。在這種情況下,您只需將手機與設備配對,之後您只需打開一個套接字並向其寫入數據即可。 – 2011-05-24 07:32:58

+0

@sujit我正在使用網絡打印機 – Harinder 2011-05-24 08:58:56

回答

1

你只需要提交你的文檔到谷歌雲打印。這是我用來打印的代碼。該文件保存在外部存儲器中,並以pdf格式。唯一的要求是設備和無線打印機必須位於同一網絡中。如果打印機已連線,則Android設備和連接到打印機的系統必須使用相同的Google帳戶登錄。

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

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

     try { 

      input = new FileInputStream(Environment.getExternalStorageDirectory() + "/hello.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; 
     } 

     // int pages = computePageCount(newAttributes); 

     PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("The invoice").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build(); 

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

printManager.print(jobName, pda, null);