2017-02-10 76 views
10

我正在嘗試使用android.graphics.pdf創建一個PDF。我的問題是多個頁面。我可以給android.graphics.pdf html然後打印成PDF。現在,如果文本溢出設置的頁面大小,則不起作用。是否有可能給它所有的html,並根據頁面大小的內容創建多個頁面?正如TCPDF :)使用android.graphics.pdf創建PDF的多個頁面

注意。我試圖避免通過計算內容的高度來創建單獨的多個頁面。

+0

哎嘗試此鏈接可能你會得到你的答案http://stackoverflow.com/a/36349822/2888952 – Arpan24x7

+0

內容溢出時是否有錯誤發生? – Michael

回答

0

爲此,您需要iTextG添加罐子到項目中:

public void createandDisplayPdf(String text) { 

    Document doc = new Document(); 

    try { 
     String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Dir"; 

     File dir = new File(path); 
     if(!dir.exists()) 
      dir.mkdirs(); 

     File file = new File(dir, "newFile.pdf"); 
     FileOutputStream fOut = new FileOutputStream(file); 

     PdfWriter.getInstance(doc, fOut); 

     //open the document 
     doc.open(); 

     Paragraph p1 = new Paragraph(text); 
     Font paraFont= new Font(Font.COURIER); 
     p1.setAlignment(Paragraph.ALIGN_CENTER); 
     p1.setFont(paraFont); 

     //add paragraph to document 
     doc.add(p1);  

    } catch (DocumentException de) { 
     Log.e("PDFCreator", "DocumentException:" + de); 
    } catch (IOException e) { 
     Log.e("PDFCreator", "ioException:" + e); 
    } 
    finally { 
     doc.close(); 
    } 

    viewPdf("newFile.pdf", "Dir"); 
} 

// Method for opening a pdf file 
private void viewPdf(String file, String directory) { 

    File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file); 
    Uri path = Uri.fromFile(pdfFile); 

    // Setting the intent for pdf reader 
    Intent pdfIntent = new Intent(Intent.ACTION_VIEW); 
    pdfIntent.setDataAndType(path, "application/pdf"); 
    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

    try { 
     startActivity(pdfIntent); 
    } catch (ActivityNotFoundException e) { 
     Toast.makeText(TableActivity.this, "Can't read pdf file", Toast.LENGTH_SHORT).show(); 
    } 
}