Android PDFDocument 正在生成一个空白文档

标签 android android-studio pdf-generation

我正在使用 Android Studio 并尝试让我的应用生成 PDF。我已经设置了一个 Activity 来生成我希望我的 PDF 具有的内容。如果我让它显示在屏幕上,这很好用。 Activity 的 onCreate 部分如下:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Connect to database
    connectToDatabase();

    // Set view
    setContentView(R.layout.activity_export_pattern);

    // find various views and set up their contents 
    // (I've left this bit out as it's quite long, but it doesn't contain 
    // anything controversial)

    // Now try to export to PDF.  
    // Return success or failure to calling activity 
    //  (basically just displays a toast indicating success/failure)
    try {
        if(exportToPDF()) {
            Intent returnIntent = new Intent();
            setResult(Activity.RESULT_OK, returnIntent);
            finish();
        }else {
            Intent returnIntent = new Intent();
            setResult(Activity.RESULT_CANCELED, returnIntent);
            finish();
        }
    } catch (IOException e) {
        e.printStackTrace();
        Intent returnIntent = new Intent();
        setResult(Activity.RESULT_CANCELED, returnIntent);
        finish();
    }
}

如果我省略最后一部分(try-catch),让它显示在屏幕上,它就可以正常工作。屏幕显示我期望它显示的内容。

但是,为了让它创建 PDF,我使用 try-catch 调用 exportToPDF,其中包含以下代码(这基本上是 Android 文档中的代码,有一些更改,如下面的评论所示):

   public boolean exportToPDF() {
        // Create PDF document
        PdfDocument document = new PdfDocument();
        // Create page description
        // Line below changed as Android Studio was highlighting an error; 
        //  instead of Rect, I have just put numbers.
        //  I've varied the numbers from 100 up to 1000, to no effect
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(720, 720, 1).create();
        // Start page
        PdfDocument.Page page = document.startPage(pageInfo);
        // Changed the line below from content = getContentView, as that was causing an error
        // pageContent is the id of the overall LinearLayout in the XML file
        // If I break after this in the debugger, content seems to have found the correct view and be populated with the appropriate page elements
        View content =  this.findViewById(R.id.pageContent);
        // Added the line below after finding it suggested on here in another question
        //  Doesn't seem to make any difference
        content.layout(0, 0, 200, 200);
        if (content != null) {
            content.draw(page.getCanvas());
        }
        // Finish page
        document.finishPage(page);

        // Write document content to external storage
        // I'm using a FileOutputStream instead of BufferedOutputStream as given in the documentation, but, since this does at least produce a file, I don't think this is the source of the problem
        String filename = this.item.getName() + ".pdf";
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + filename);
        FileOutputStream fileOut = null;
        try {
            fileOut = new FileOutputStream(file);
            document.writeTo(fileOut);
            fileOut.close();
            document.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            if(fileOut != null) fileOut.close();
            document.close();
            return false;
        }
    }

因此,运行它会在正确的目录中生成一个 PDF,名称正确,但它是空白的。我不知道还能尝试什么。

最佳答案

在 Activity 中将 View 写入 PDF onCreate() 的地方,它不会工作,因为您的 View 返回 0 高度和宽度。您需要等待 Activity 窗口附加,然后将 View 写入 pdf。您可以尝试从 Activity 的 onWindowFocusChanged() 方法调用 exportToPDF。

public void onWindowFocusChanged(boolean hasFocus) {
    // TODO Auto-generated method stub
    super.onWindowFocusChanged(hasFocus);
try {
        if(exportToPDF()) {
            Intent returnIntent = new Intent();
            setResult(Activity.RESULT_OK, returnIntent);
            finish();
        }else {
            Intent returnIntent = new Intent();
            setResult(Activity.RESULT_CANCELED, returnIntent);
            finish();
        }
    } catch (IOException e) {
        e.printStackTrace();
        Intent returnIntent = new Intent();
        setResult(Activity.RESULT_CANCELED, returnIntent);
        finish();
    }

    }

你也可以使用ViewTreeObserver

 View content =  this.findViewById(R.id.pageContent);
    ViewTreeObserver vto = content.getViewTreeObserver(); 
            vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
                @Override 
                public void onGlobalLayout() { 
              try {
            if(exportToPDF()) {
                Intent returnIntent = new Intent();
                setResult(Activity.RESULT_OK, returnIntent);
                finish();
            }else {
                Intent returnIntent = new Intent();
                setResult(Activity.RESULT_CANCELED, returnIntent);
                finish();
            }
        } catch (IOException e) {
            e.printStackTrace();
            Intent returnIntent = new Intent();
            setResult(Activity.RESULT_CANCELED, returnIntent);
            finish();
        }
content.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    } 
            }); 

关于Android PDFDocument 正在生成一个空白文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37763922/

相关文章:

android - 如何在 Kotlin 中滑动 fragment 时选择 BottomNavigationView 中的项目

Android sslpeerunverifiedexception 没有对等证书,JSON SSL

android - 在 Android Studio 1.3.1 中多次导入库项目导致库消失

java.lang.NullPointerException 在 android.support.v4.view.ViewCompatHC.setAlpha(ViewCompatHC.java :101)

android - 将测试文件夹添加到类路径中以获得特定的gradle风格

php - 如何使用 PHP 使用 FPDF 制作这样的表格?

android - 向 View 添加一些文本

android - 在 Firebase 中同时上传到数据库和存储

asp.net - 如何在 ABC 中打断表格pdf

r - 如何降低使用 R 创建的 pdf 的质量