2011-05-24 135 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);