java - 尝试在 Android 中生成 PDF 时出现 FileNotFoundException

标签 java android pdf pdf-generation android-logcat

在这里我尝试在android中生成一个pdf文件,但在运行时我得到这个执行

       ioException:java.io.FileNotFoundException: /storage/sdcard/PDF/Demo.pdf: openfailed: ENOENT (No such file or directory)

这是我的代码

    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.app.Activity;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
     import java.io.IOException;
    import com.lowagie.text.Document;
    import com.lowagie.text.DocumentException; 
    import com.lowagie.text.Font;
    import com.lowagie.text.HeaderFooter;
    import com.lowagie.text.Image;
    import com.lowagie.text.Paragraph;
    import com.lowagie.text.Phrase;
      import com.lowagie.text.pdf.PdfWriter;

      public class MainActivity extends Activity {
    private Button createPDF , openPDF;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        createPDF = (Button)findViewById(R.id.button1);
        createPDF.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                createPDF();
            }
        });
        openPDF = (Button)findViewById(R.id.button2);
        openPDF.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                openPdf();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void createPDF(){
        Document doc  =new Document();
        try {
            String parth = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
            File dir = new File(parth);
            if(!dir.exists())
                dir.mkdir();
            Log.d("PDFCreater", "PDF PARTH "+parth);
            File file = new File(dir,"demo.pdf");
            Log.d("PDFCreater", "Create");
            FileOutputStream fOut = new FileOutputStream(file);
            Log.d("PDFCreater", "1");
            PdfWriter.getInstance(doc, fOut);
            Log.d("PDFCreater", "2");
            doc.open();
            Log.d("PDFCreater", "open");
            Paragraph p1= new Paragraph("Customer History");
            Font paraFont = new Font(Font.HELVETICA);
            paraFont.setSize(16);
            p1.setAlignment(Paragraph.ALIGN_CENTER);
            p1.setFont(paraFont);
            doc.add(p1);
            Log.d("PDFCreater", "add");
            /* Inserting Image in PDF */
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.apple);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
            Image myImg = Image.getInstance(stream.toByteArray());
            myImg.setAlignment(Image.MIDDLE);

            //add image to document
            doc.add(myImg);
            Phrase footerText = new Phrase("This is an example of a footer");
            HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
            doc.setFooter(pdfFooter);

            Toast.makeText(getApplicationContext(), "Created...", Toast.LENGTH_LONG).show();
        } catch (DocumentException de) {
            Log.e("PDFCreator", "DocumentException:" + de);
        } catch (IOException e) {
            Log.e("PDFCreator", "ioException:" + e);
        } 
        finally
        {
            doc.close();
        }



    }
    void openPdf()
    {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";

    File file = new File(path, "demo.pdf");
    intent.setDataAndType( Uri.fromFile( file ), "application/pdf" );
       startActivity(intent);
    }

}

这是我的 xml 文件

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context=".MainActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:layout_marginLeft="56dp"
    android:layout_marginTop="50dp"
    android:text="Create" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button1"
    android:layout_below="@+id/button1"
    android:layout_marginTop="38dp"
    android:text="Open" />

</RelativeLayout>

list 文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.isuru.mypdf"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

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

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.isuru.mypdf.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

我认为异常在这一行抛出

FileOutputStream fOut = new FileOutputStream(file);

请帮帮我,谢谢!

最佳答案

您是否在 Android list 文件中声明了此权限:

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

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

关于java - 尝试在 Android 中生成 PDF 时出现 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22704186/

相关文章:

java - 如何将 Netbeans Java 项目和 MySql 中的数据库导出到一起以在不同机器上工作?

java - 参数 [variable] 的非法修饰符;只允许 final

java - MediaRecorder 停止时出错 : stop called in invalid state 4

iphone - 如何在 iPhone 应用程序中为 pdf 文件添加背景颜色

pdf - 用光栅图像替换 PDF 中的矢量图像

java - gradle 5中的sourcesJar任务

java - 停止长时间等待的线程

Android (API 10) fragment 错误

java - 您可以生成使用 Java 注释覆盖方法的代码吗?

php - 如何以原始格式从 PDF 中提取图像