前言,以前生成PDF,是靠盲布的。效率非常不高,再次做类似项目决定将XML Layout View转换成pdf,这个布局就由xml文件来实现,xml再使用上ConstraintLayout,那简直就是「所见即所得」了。非常的方便。这里把这个方案分析给大家。
系统版本: Android 4.4.2 +
平台:不限
public static void createPdfFromView(View content, final String pdfPath) {
if (content == null || pdfPath == null) {
Log.e(TAG, "content and pdfPath can not be null!");
return;
}
// create a new document
PdfDocument document = new PdfDocument();
// crate a page description
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(
PrintAttributes.MediaSize.ISO_A4.getWidthMils() * 72 / 1000,
PrintAttributes.MediaSize.ISO_A4.getHeightMils() * 72 / 1000, 1)
.create();
// start a page
PdfDocument.Page page = document.startPage(pageInfo);
// draw something on the page
// LayoutInflater li = LayoutInflater.from(getApplicationContext());
// View content = li.inflate(R.layout.activity_welcome, null);
Canvas canvas = page.getCanvas();
content.draw(canvas);
// finish the page
document.finishPage(page);
// add more pages
// write the document content
FileOutputStream os = null;
try {
Log.i(TAG, "String:" + pdfPath);
os = new FileOutputStream(pdfPath);
document.writeTo(os);
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// close the document
document.close();
}
}
来源:stackoverflow,具体链接找不到了。:(
注意事项:
1. 使用LayoutInflater反射出来的View不行;
2. 将要转换成pdf的xml view文件include到一个界面中,将其设置成android:visibility=”invisible”就可以实现,不显示,但是能转换成PDF;
3. 设置成gone不行;