Android利用PdfDocument生成pdf文件及踩过的坑


写在前面:最近编写Android项目生成pdf文件,遇到了一些困难,记录一下自己踩过的坑。
采用PdfDocument这个类
官方文档:

// create a new document
 * PdfDocument document = new PdfDocument();
 *
 * // crate a page description
 * PageInfo pageInfo = new PageInfo.Builder(new Rect(0, 0, 100, 100), 1).create();
 *
 * // start a page
 * Page page = document.startPage(pageInfo);
 *
 * // draw something on the page
 * View content = getContentView();
 * content.draw(page.getCanvas());
 *
 * // finish the page
 * document.finishPage(page);
 * . . .
 * // add more pages
 * . . .
 * // write the document content
 * document.writeTo(getOutputStream());
 *
 * // close the document
 * document.close();

1.在布局文件为当前前页面设置id属性

android:id="@+id/linearlayout"

2.声明 定义并找到布局文件对应的组件

LinearLayout linearLayout;
linearLayout = findViewById(R.id.linearlayout);

3.根据官方文档PdfDocument类的使用,编写生成pdf的方法

private void generatePdf() {
        PdfDocument document = new PdfDocument();//1.建立PdfDocument
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(linearLayout.getWidth(),linearLayout.getHeight(),1).create();
        PdfDocument.Page page = document.startPage(pageInfo);//2.建立新的page

        //View content = this.findViewById(R.id.linearlayout);
        //content.draw(page.getCanvas());
        linearLayout.draw(page.getCanvas());//3.canvas把当前画面画出来
        document.finishPage(page);


        String path = getApplicationContext().getFilesDir().getAbsolutePath() + "/table1.pdf";
        System.out.println(path);
        File file = new File(path);
        if(!file.exists()){
            if(file.mkdirs()){
                System.out.println(1);
            }else
                System.out.println(0);
        }
        if(file.exists()){
            file.delete();
        }
        try {
            document.writeTo(new FileOutputStream(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        document.close();
    }

4.别忘记在manifest 添加读取权限

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

5.接下来就成功生成了pdf文件了,但是生成的pdf文件在模拟器没找到,一直以为是代码错了没生成成功(文件目录没有的话要先创建,不然找不到路径会报IO错误),Debug了好久(好吧-。-,是自己太菜了),后面发现android studio里面可以查看模拟器文件夹,终于在里面找到了我输出的pdf文件,大功告成~

在这里插入图片描述
在这里插入图片描述

发布了121 篇原创文章 · 获赞 33 · 访问量 7322

猜你喜欢

转载自blog.csdn.net/qq_42549254/article/details/103119716