java - 使用来自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();
}
}
解决方案
尝试使用一些预定义的 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);
}
}
这个我没试过。这可能有效
推荐阅读
- javascript - 由于推送 ID,无法将 Firebase 列表数据附加到 html 表
- php - 奏鸣曲管理员编辑表单而不是实体的 ValueObject
- phpstorm - PhpStorm 2019.1 中缺少创建命令行启动器
- c# - 如何在不使用“文件下载”对话框的情况下使用 WebBrowser 控件下载文件?
- android - 设置工具栏菜单项的样式
- android - 生成 APK 时 QtCreator 发生 ProcessException
- xslt - 通过 XPath 提取元素节点?
- c# - 为什么 .net 显示相同 nuget 包的版本冲突,这是 3rd 方库/包的内部依赖项?
- arrays - 如何从 json 中删除索引 - 使用 laravel
- java - 使用注入的 Spring Boot DI。无法识别的类