Creating PDFs in android

2019-06-14 18:42发布

问题:

I am using this code to generate pdf file in android but it gives me "File not found exception"

            try {
    OutputStream file = new FileOutputStream(new File("D:\\Test.pdf"));

    Document document = new Document();
 //   PdfWriter.getInstance(document, new FileOutputStream(FILE));
    PdfWriter.getInstance(document, file);
    document.open();
    addMetaData(document);
    addTitlePage(document);
    addContent(document);
    //createImage();
    document.close();

} catch (Exception e) {
    e.printStackTrace();
}

when I execute this line:

    PdfWriter.getInstance(document, file);

It says "Java.io.FileNotFOundException". I have to create new file then why is it open a file which is not even generated yet? what is wrong with this code?

回答1:

I dont think "D:\" is a valid file location in android

try

OutputStream file = new FileOutputStream(newFile(Environment.getExternalStorageDirectory().toString,"test.pdf"));

As a bit of extra info for in future if you are dealing with file systems in android, becasue android is unix based the path separator is '/' not '\'. The '\' separator is (as far as I know) something unique to windows as is D:



回答2:

This error is because of the location provided by you in your line of code mentioned below.


    OutputStream file = new FileOutputStream(new File("D:\\Test.pdf"));

I don't think D drive exist for your android file system. Below link might help.

How To Create a PDF file in raw in Android

or you can use below code.


    try {
                 File temp = new File(FILE.getAbsolutePath(),"Test.pdf");   
                  PdfWriter.getInstance(document, new FileOutputStream(temp));
    }