你可以看看这个链接:
https://github.com/HendrixString/Android-PdfMyXml
说明
- 创建 XML 布局
首先创建 XML 布局。根据 1:1.41 的比例,给它以像素为单位的尺寸(以及它的所有子视图)和横向或纵向的比例。
page1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="2115px"
android:layout_height="1500px"
android:background="@color/white">
<TextView android:id="@+id/tv_hello"
android:textColor="@color/black"
android:textSize="27px"
android:textStyle="bold"
android:padding="6px"/>
</RelativeLayout>
您可以根据需要创建任意数量的页面/模板。
- 实现视图渲染器
通过扩展 AbstractViewRenderer 或匿名实例化它并注入布局 ID 来实现您的视图渲染器。 initView(View view) 会自动为您提供一个膨胀的视图。还有其他选择,但我现在不会介绍。
AbstractViewRenderer page = new AbstractViewRenderer(context, R.layout.page1) {
private String _text;
public void setText(String text) {
_text = text;
}
@Override
protected void initView(View view) {
TextView tv_hello = (TextView)view.findViewById(R.id.tv_hello);
tv_hello.setText(_text);
}
};
// you can reuse the bitmap if you want
page.setReuseBitmap(true);
- 构建 PDF 文档
使用 PdfDocument 或 PdfDocument.Builder 来添加页面并在后台使用进度条进行渲染和运行。
PdfDocument doc = new PdfDocument(ctx);
// add as many pages as you have
doc.addPage(page);
doc.setRenderWidth(2115);
doc.setRenderHeight(1500);
doc.setOrientation(PdfDocument.A4_MODE.LANDSCAPE);
doc.setProgressTitle(R.string.gen_please_wait);
doc.setProgressMessage(R.string.gen_pdf_file);
doc.setFileName("test");
doc.setInflateOnMainThread(false);
doc.setListener(new PdfDocument.Callback() {
@Override
public void onComplete(File file) {
Log.i(PdfDocument.TAG_PDF_MY_XML, "Complete");
}
@Override
public void onError(Exception e) {
Log.i(PdfDocument.TAG_PDF_MY_XML, "Error");
}
});
doc.createPdf(ctx);
或使用 PdfDocument.Builder
new PdfDocument.Builder(ctx).addPage(page).filename("test").orientation(PdfDocument.A4_MODE.LANDSCAPE)
.progressMessage(R.string.gen_pdf_file).progressTitle(R.string.gen_please_wait).renderWidth(2115).renderHeight(1500)
.listener(new PdfDocument.Callback() {
@Override
public void onComplete(File file) {
Log.i(PdfDocument.TAG_PDF_MY_XML, "Complete");
}
@Override
public void onError(Exception e) {
Log.i(PdfDocument.TAG_PDF_MY_XML, "Error");
}
}).create().createPdf(this);