
本文介绍如何将用户动态添加的 recyclerview 列表(如订单商品)通过 itext 库生成结构清晰、自适应行数的 pdf 文档,核心是复用数据源列表而非操作视图本身。
本文介绍如何将用户动态添加的 recyclerview 列表(如订单商品)通过 itext 库生成结构清晰、自适应行数的 pdf 文档,核心是复用数据源列表而非操作视图本身。
在 Android 开发中,RecyclerView 本身是 UI 组件,不能直接写入 PDF;但其背后必然由一个数据集合(如 List<productitem></productitem>)驱动。因此,生成 PDF 的关键在于:跳过视图层,直接遍历原始数据列表,逐项将内容写入 iText 的表格(PdfPTable)中。这种方式天然支持任意长度的数据——无论用户添加了 1 条还是 100 条记录,PDF 都能自动适配。
以下是一个完整、可落地的实现示例:
private void createPdf(Order order) throws FileNotFoundException, DocumentException {
// 1. 创建存储目录
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);
// 2. 初始化 PDF 文档(A4 尺寸)
Document document = new Document(PageSize.A4);
PdfWriter.getInstance(document, output);
// 3. 构建表格:4 列(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);
// 4. 添加表头(带浅灰背景)
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);
}
// 5. ✅ 核心逻辑:遍历真实数据源(非 RecyclerView!)
List<productitem> items = order.getItemsList();
for (ProductItem item : items) {
table.addCell(String.valueOf(item.getProductId()));
table.addCell(item.getProductName()); // 注意:避免 null 导致崩溃,建议加空值判断
table.addCell(String.valueOf(item.getProductQuantity()));
table.addCell(String.format("%.2f", item.getProductPrice() * item.getProductQuantity()));
}
// 6. 写入文档并关闭
document.open();
document.add(table);
document.close();
}</productitem>
✅ 关键要点说明:
- 永远不要尝试“截图”或“渲染 RecyclerView 到 PDF”——效率低、易失真、无法搜索文本;
-
确保
Order.getItemsList()返回的是最新、完整的业务数据列表(通常来自 ViewModel 或本地数据库); -
务必对可能为
null的字段做安全处理(如item.getProductName()建议判空后替换为"N/A"); - 若需支持中文,请在创建
Font时指定支持 UTF-8 的字体(如 NotoSansCJK),并为PdfPCell设置setFont(); - 表格行高、列宽、颜色等样式可根据实际需求灵活调整,iText 提供丰富的排版控制能力。
最终生成的 PDF 具备专业表格结构、固定列头、自动分页(长列表会自动跨页),且全文可选、可搜索——真正满足业务级导出需求。










