Android-使用android.graphics.pdf.PdfDocument生成PDF文件

时间:2017-08-01 09:36:55

标签: android pdf

我正在尝试从xml布局生成pdf。我正在使用android 仅限SDK API。生成pdf但它始终为空。我正在使用android.graphics.pdf.PdfDocument。我尝试寻找解决方案,但无法解决这个问题。下面是我正在使用的代码。请帮忙。

private void generateInvoice() {
        document = new PdfDocument();
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(597, 820, 1).create();
        PdfDocument.Page page = document.startPage(pageInfo);
        getLayoutInflater().inflate(R.layout.invoice_layout, null).draw(page.getCanvas());
        document.finishPage(page);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_WRITE_EXTERNAL_STORAGE_PDF);
        } else {
            try {
                saveDocument();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private void saveDocument() throws IOException {
        File direct = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/YoScholarData");
        if (!direct.exists()) {
            if (direct.mkdir()) // if directory is created
                Log.d(TAG, "YoScholarData Folder Created.");
        }
        String timeStamp = new SimpleDateFormat("dd-MM-yyyy'T'-HH-mm-ss", Locale.getDefault()).format(new Date());
        String fileName = timeStamp + "_Invoice.pdf";
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/YoScholarData" + File.separator + fileName);
        if (file.createNewFile()) {
            if (file.exists()) {
                OutputStream fo = new FileOutputStream(file);
                document.writeTo(fo);
                document.close();
                fo.close();
                Log.d(TAG, "File Created in YoScholarData Folder.");
                Toast.makeText(this, "Invoice created successfully.", Toast.LENGTH_SHORT).show();
            }

        }

        MediaScannerConnection.scanFile(this, new String[]{file.getAbsolutePath()}, null, null);

    }

`

请帮忙。

0 个答案:

没有答案