Creating PDFs in android

▼魔方 西西 提交于 2019-12-10 12:25:36

问题


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));
    }



来源:https://stackoverflow.com/questions/18592320/creating-pdfs-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!