2016-12-06 93 views
0

在我的android應用程序中,我已經實現了從html內容生成pdf,通過在WebView中顯示html內容,然後使用PdfDocument創建pdf文檔。它工作得很好(下面的代碼示例),但我想知道是否有可能從HTML內容生成PDF文件,這是不可見的屏幕上?當我將mPdfPreviewWebView的可見性設置爲GONE時,則創建的pdf爲空。如何從隱藏的webView創建PDF?

換句話說,我需要從html生成pdf,但我不希望HTML在屏幕上可見(或佔用任何空間)。

備註:我不想使用iText庫,因爲它的許可證。

private void createPDF() { 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 
     PdfDocument pdfDocument = new PdfDocument(); 

     PdfDocument.PageInfo pageInfo = new PdfDocument 
       .PageInfo.Builder(A4_WIDTH, A4_HEIGHT, 1).create(); 

     PdfDocument.Page page = pdfDocument.startPage(pageInfo); 

     Canvas canvas = page.getCanvas(); 
     int webViewWidth = mPdfPreviewWebView.getWidth(); 
     float scale = A4_WIDTH/(float) webViewWidth; 
     canvas.save(); 
     canvas.scale(scale, scale); 

     mPdfPreviewWebView.draw(canvas); 
     canvas.restore(); 
     pdfDocument.finishPage(page); 

     String dir = Environment.getExternalStorageDirectory() 
       + getString(R.string.three_clicks_folder); 

     try { 
      FileOutputStream fileOutputStream = null; 
      try { 
       File file = (new File(dir, "share.pdf")); 
       if (!file.exists()) { 
        file.createNewFile(); 
       } 

       fileOutputStream = new FileOutputStream(file); 

       pdfDocument.writeTo(fileOutputStream); 

       pdfDocument.close(); 
       Log.i(TAG, "PDF created"); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } finally { 
       if (fileOutputStream != null) { 
        fileOutputStream.close(); 
       } 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

回答

0

這是可能的。只需在您的活動之上製作一個片段,然後在您的活動中調用代碼處理您的pdf例程的代碼。轉換完成後,請關閉片段。該片段可以是一個「處理....」消息,完成後,解散它,然後在片段中做任何你喜歡做的事情。或者,您可能希望在您解散片段之前用您的轉換後的pdf做些事情。

+0

但我的問題是從HTML到PDF的轉換。根據我的經驗,我用來生成PDF的方法,只有當'WebView'(或任何其他'View',其上調用'draw'方法)在屏幕上可見時才能正確生成。我正在尋找一種方法來將HTML轉換爲PDF「在後臺」。 –