1

我尝试使用 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();
        }

你能帮帮我吗?谢谢

4

2 回答 2

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"/>
于 2012-05-15T06:38:03.750 回答
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");
于 2013-05-31T04:25:51.993 回答