
本文介绍如何将用户动态添加的 recyclerview 数据(如商品清单)通过 itext 库生成结构清晰、可扩展的 pdf 文档,核心是遍历原始数据源而非视图本身,并使用 pdfptable 动态构建表格内容。
本文介绍如何将用户动态添加的 recyclerview 数据(如商品清单)通过 itext 库生成结构清晰、可扩展的 pdf 文档,核心是遍历原始数据源而非视图本身,并使用 pdfptable 动态构建表格内容。
在 Android 开发中,RecyclerView 本身是 UI 组件,不可直接导出为 PDF;真正可导出的是其背后的数据源(例如 List<productitem></productitem>)。用户每新增一项,实际是向该 List 添加对象——这正是生成 PDF 的可靠依据。只要确保你的业务逻辑中维护了这份“真实数据列表”,即可完全解耦 UI 与导出逻辑。
以下是一个完整的 PDF 导出示例(基于 iText 5.x):
private void createPdf(Order order) throws FileNotFoundException, DocumentException {
File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Documents");
if (!docsFolder.exists()) docsFolder.mkdir();
String pdfName = order.getOrderId() + "ST.pdf";
File pdfFile = new File(docsFolder.getAbsolutePath(), pdfName);
OutputStream output = new FileOutputStream(pdfFile);
Document document = new Document(PageSize.A4);
// ✅ 关键:从订单中获取原始数据列表(非 RecyclerView!)
List<productitem> items = order.getItemsList();
// 创建四列表格:商品ID、名称、数量、总价
PdfPTable table = new PdfPTable(new float[]{3, 5, 3, 3});
table.setWidthPercentage(100);
table.setTotalWidth(PageSize.A4.getWidth());
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
table.getDefaultCell().setFixedHeight(28);
// 添加表头并设置浅灰背景
table.addCell("Product Id");
table.addCell("Name");
table.addCell("Quantity");
table.addCell("Price");
table.setHeaderRows(1);
for (PdfPCell cell : table.getRow(0).getCells()) {
cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
}
// ✅ 核心循环:逐项写入表格行(自动适配任意长度列表)
for (ProductItem item : items) {
table.addCell(String.valueOf(item.getProductId()));
table.addCell(item.getProductName()); // 建议非空校验
int qty = item.getProductQuantity();
table.addCell(String.valueOf(qty));
table.addCell(String.format("%.2f", item.getProductPrice() * qty)); // 保留两位小数
}
// 构建文档并写入文件
PdfWriter.getInstance(document, output);
document.open();
document.add(table);
document.close();
}</productitem>
? 关键注意事项:
- ✅ 永远操作数据源(List),而非 RecyclerView 或 ViewHolder —— 视图可能被回收、复用或未完全渲染;
- ✅ 在添加文本前建议对
item.getProductName()等字段做非空/安全转换(如Objects.toString(..., "")),避免NullPointerException; - ✅ 若字段含换行符或长文本,可启用
cell.setPhrase(new Phrase(text, font))并设置cell.setPadding(5)提升可读性; - ⚠️ iText 5 需声明
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>(Android 10+ 建议改用应用私有目录或 MediaStore); - ? 如需支持多页长列表,iText 会自动分页——无需手动处理,但建议为
table.setSplitLate(false)确保表头跨页重复(需配合table.setHeaderRows(1))。
总结:PDF 导出的本质是「数据快照」,而非「界面截图」。只要你在添加 RecyclerView 条目时同步更新了底层 List(这是标准 MVVM/MVC 实践),导出逻辑就天然具备可扩展性与健壮性——无论用户输入 1 条还是 1000 条,代码零修改即可稳定运行。










