我正在尝试创建一个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();
}
}
答案 0 :(得分:0)
我认为这是因为multiline
是EditText
的属性,而不是String
的属性,因此,如果您从ET读取它,它将始终位于单行中。您可以尝试设置最大行长,然后读取要限制的字符,然后将其添加到新的String
中,例如ArrayList<String>
(您不知道文本的长度)。如果行数限制不是以,
或.
或space
结尾,那么请进一步阅读,直到出现,
或.
或space
。将所有ArrayList添加到pdf之后,每行以\n
结尾。
答案 1 :(得分:0)
尝试以一定的预定义长度分割从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);
}
}
我还没有尝试过。这可能有效