2016-10-28 52 views
0

我需要在我的android应用程序中实现文档打印功能。 我可以用下述android的印刷框架代码打印图像文件:如何将PDF,图像和HTML文档从android设备打印到wifi上的打印机?

private void doPhotoPrint(Bitmap bigbitmap) 
{ 
    PrintHelper photoPrinter = new PrintHelper(MainActivity.this); 
    photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT); 
    photoPrinter.printBitmap("droids.jpg - test print", bigbitmap); 
} 

我通过现有的线程去讨论同样的问题,但他们没有太大的帮助。

我面临的问题是其他文档类型,如PDF和HLML。 如果有人能够对此进行一些了解,这将有所帮助。

回答

1

您可以检查此代码

if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 
     PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE); 
     String jobName = this.getString(R.string.app_name) + " Document"; 



     PrintDocumentAdapter pda = new PrintDocumentAdapter() { 

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

       try { 
        AssetManager assetManager = getAssets(); 
        File file = new File(getFilesDir(), "fact_sheet.pdf");     
        input = assetManager.open("fact_sheet.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("Name of file").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build(); 

       callback.onLayoutFinished(pdi, true); 
      } 
     }; 
     printManager.print(jobName, pda, null); 
    } 
+0

这为我工作。 –