首页 > 解决方案 > 使用来自editText android的数据创建Pdf

问题描述

我正在尝试创建一个pdf. 数据直接取自编辑文本,但问题是,如果我在编辑文本中写入任何段落,最终输出将pdf在 1 行而不是多行中显示所有数据。虽然pdf正在创建,但我只能在 1 行中看到输出。图片链接:

陈述活动: 在此处输入图像描述

创建的文件: 在此处输入图像描述

查看的文件: 在此处输入图像描述

public class Main2Activity extends AppCompatActivity {
    Button btnCreate;
    EditText editText,editText2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        btnCreate = (Button)findViewById(R.id.create);
        editText =(EditText) findViewById(R.id.edittext);
        editText2 =(EditText) findViewById(R.id.edittext2);
        btnCreate.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(View view) {
                createPdf(editText.getText().toString(),editText2.getText().toString());
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void createPdf(String title,String description){
        // create a new document
        PdfDocument document = new PdfDocument();
        // crate a page description

        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(300, 600, 1).create();
        // start a page
        PdfDocument.Page page = document.startPage(pageInfo);

        Canvas canvas = page.getCanvas();
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        canvas.drawText(title, 20, 40, paint);
        canvas.drawText(description, 20, 60, paint);
       // canvas.drawText(description,1,20,20.0f,30.0f,paint);
        //canvas.drawt
        // finish the page
        document.finishPage(page);
// draw text on the graphics object of the page

        // write the document content
        String directory_path = Environment.getExternalStorageDirectory().getPath() + "/mypdf/";
        File file = new File(directory_path);
        if (!file.exists()) {
            file.mkdirs();
        }
        String targetPdf = directory_path+title+".pdf";
        File filePath = new File(targetPdf);
        try {
            document.writeTo(new FileOutputStream(filePath));
            Toast.makeText(this, "Done", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Log.e("main", "error "+e.toString());
            Toast.makeText(this, "Something wrong: " + e.toString(),  
Toast.LENGTH_LONG).show();
        }
        // close the document
        document.close();
    }
}

标签: javaandroidandroid-layout

解决方案


尝试使用一些预定义的 Length 拆分从 editText 获得的字符串,然后在 canvas.drawText() 中使用它

while(description.length()>15){
    if(description.length()>15){
        String first = description.substring(0,15);
        canvas.drawText(description, 20, 60, paint);
    }
    else{
        String second =description.substring(0,description.length());
        canvas.drawText(description, 20, 60, paint);
    }

}

这个我没试过。这可能有效


推荐阅读