Pdf写入和读取Itext

时间:2018-03-12 15:47:14

标签: android pdf itext

我正在尝试创建一个pdf文件,然后使用Itext库从我的Android设备上读取它。

我的问题 当我尝试打开pdf视图意图时,我的文件不存在,即使我尝试通过Toasts查看路径,这看起来非常好......

这是我的代码:

private void createPdf() throws FileNotFoundException, DocumentException{


        pdfFolder = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), "pdfdemo");
        if (!pdfFolder.exists()) {
            pdfFolder.mkdir();
            Log.i(LOG_TAG, "Pdf Directory created");
        }

        myFile = new File(pdfFolder + "/pdftest.pdf");
        /*String path = myFile.getPath();
        Toast.makeText(this, path, Toast.LENGTH_SHORT).show();*/

        try {
            myFile.createNewFile();
        } catch (Exception io){
            io.printStackTrace();
        }


        OutputStream output = new FileOutputStream(myFile);

        //Step 1
        Document document = new Document();

        //Step 2
        PdfWriter.getInstance(document, output);

        //Step 3
        document.open();

        //Step 4 Add content
        document.add(new Paragraph(edt_email.getText().toString()));
        document.add(new Paragraph(edt_name.getText().toString()));

        //Step 5: Close the document
        document.close();

    }

我的代码来自Val Okafor,来自他的Itext示例:https://www.codeproject.com/Articles/986574/Android-iText-Pdf-Example

这就是我试图打开它的方式:

private void viewPdf(){

        /*String filepath = myFile.getPath();
        Toast.makeText(this, filepath, Toast.LENGTH_SHORT).show();*/

        if (myFile.exists()) {

            Uri path = Uri.fromFile(myFile);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(path, "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            Toast.makeText(this, "File exists", Toast.LENGTH_SHORT).show();

            try {
                startActivity(intent);
            }
            catch (ActivityNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(this, "Error reading", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "file doesnt exist", Toast.LENGTH_SHORT).show();
        }
    }

(我已添加读写外部存储的权限)

我哪里出错了?请帮我解决这个问题, 有一个美好的一天/傍晚/晚上!

0 个答案:

没有答案