利用PdfDocument生成PDF文件,当内容有变化时,就会产生空文件,无论是page.getCanvas().drawText("12345", 20, 50, paint);
还是
view1.draw(canvas);
代码如下:
public void actionGenPdf(View view)
{
// 创建一个PDF文本对象
PdfDocument document=new PdfDocument();
//创建当前页的信息,Builder中的参数表示页面的宽高,以及第几页
PdfDocument.PageInfo pageInfo=new PdfDocument.PageInfo.Builder(595,
843,1).create();
// 生成当前页
PdfDocument.Page
page=document.startPage(pageInfo);
// 在当前页上画画,即把所需要的view的视图画到page的画布上
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(20);
Canvas canvas = page.getCanvas();
/*for(int i = 0; i < 10; i++) {
String sTmp = "12345";
page.getCanvas().drawText("12345", 20, 50, paint);
canvas.translate(0, 30);
}*/
TextView view1 = new TextView(this);//getContentView();
view1.layout(0, 0, 200, 200);
view1.setText("Hello");
TextView view2 = new TextView(this);//getContentView();
view2.layout(0, 0, 200, 200);
String sTmp = "Good"+Integer.toString(10);
final String ss = sTmp;
view2.setText(ss);
view1.draw(canvas);
canvas.translate(0, 200);
view2.draw(canvas);
canvas.save();
/*for(int i = 0; i < 10; i++) {
TextView view1 = new
TextView(this);//getContentView();
view1.layout(0, 0, 200, 200);
view1.setText("Hello"+Integer.toString(i));
Toast.makeText(this,"Hello"+Integer.toString(i),
Toast.LENGTH_SHORT).show();
view1.draw(canvas);
// Move the canvas for the next
view.
canvas.save();
canvas.translate(0, 50);
}*/
document.finishPage(page);
// 输出到文件
try {
String filePath = "/sdcard/";
//String filePath =
Environment.getExternalStoragePublicDirectory("").getAbsolutePath();
//String filePath =
Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "easy.pdf";
File file = new File(filePath, fileName);
FileOutputStream outputStream = new
FileOutputStream(file);
document.writeTo(outputStream);
PubUtils.notifySystemToScan(this,
filePath + fileName);
Toast.makeText(this, "导出完成",
Toast.LENGTH_SHORT).show();
SoundUtils.getInstance().playSuccess();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this,
e.getMessage(), Toast.LENGTH_LONG).show();
}
}