首页 > 解决方案 > 我想在 Android Studio 中将文件类型转换为 PdfDocument 类型

问题描述

我试过代码

@Override
protected void onActivityResult(int requestCode, int resultCode, 
                                @Nullable Intent data) 
{
    switch (requestCode)
    {
        case 10:
            if (resultCode==RESULT_OK) 
            {
                String path = data.getData().getPath();
                path_disp.setText(path);
                File file = new File(path);
                PdfDocument pdf = new PdfDocument(file.getAbsolutePath(), null);
            }
            break;
    }
}

但这给了我一个错误“PdfDocument()中的 PdfDocument()不能应用于(java.lang.String,null)”

标签: javaandroid

解决方案


https://developer.android.com/reference/android/graphics/pdf/PdfDocument

看起来类 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();

您必须先创建一个页面,然后才能在画布上绘制一些东西。在你的情况下,它会是

yourCanvas.drawText("Your string.")

推荐阅读