2012-05-15 64 views
1

我試圖使用iText(here)在Android中將文本轉換爲PDF,但它給出了「文件未找到」異常。 這裏是代碼:使用iText在Android中將文本轉換爲PDF

try 
     { 

      PdfWriter.getInstance(document, new FileOutputStream("hello.pdf")); 
      document.open(); 
      document.add(new Paragraph("Hello World")); 
      document.close(); 
      Log.d("OK", "done"); 
     } 
     catch (FileNotFoundException e) 
     { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     catch (DocumentException e) 
     { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

你能幫我嗎?由於

+0

其中是你的文件(文件位置)?是在項目文件夾中還是在系統驅動器上? –

+0

其實我使用了上面的代碼。所以,我認爲操作系統應該在程序文件夾中創建一個新文件。 –

+0

我建議您使用https://code.google.com/p/droidtext/。這對Android來說更好。 – Rusfearuth

回答

6

這工作在我的情況下完美,

try 
    { 
     Document document = new Document(); 
     PdfWriter.getInstance(document, new FileOutputStream(Environment.getExternalStorageDirectory() + "/hello.pdf")); 
     document.open(); 
     document.add(new Paragraph("Hello World")); 
     document.close(); 
     Log.d("OK", "done"); 
    } 
    catch (FileNotFoundException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    catch (DocumentException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

而且清單文件,

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
+0

hello.pdf的位置是「/mnt/sdcard/hello.pdf」。 – user370305

+0

謝謝,但是如果沒有SD卡,情況如何? –

+0

在創建文件之前,只需檢查Environment.getExternalStorageState(),它將返回路徑到內部SD掛載點,如「/ mnt/sdcard」 – user370305

1

這對我的代碼工作...試試這個

嘗試 {

 String path = Environment.getExternalStorageDirectory()+"/hello/"; 
     File file = new File(path+"hello.pdf"); 
     if(!file.exists()){ 
      file.getParentFile().mkdirs(); 
      try { 
       file.createNewFile(); 

      } 
      catch (IOException e) 
      { 
       // TODO Auto-generated catch block e.printStackTrace(); } 
      } 
     } 

     Document document = new Document(); 
     PdfWriter.getInstance(document, new FileOutputStream(Environment.getExternalStorageDirectory() 
       +File.separator 
       +"hello" //folder name 
       +File.separator 
       +"hello.pdf")); 
     document.open(); 
     document.add(new Paragraph("Hello World "+txt.getText())); 
     document.add(new Paragraph("Hello World" +txt.getText())); 
     document.add(new Paragraph("Hello World" +txt.getText())); 
     document.add(new Paragraph("Hello World "+txt.getText())); 
     document.close(); 
     Log.d("OK", "done");