Flutter使用pdf包生成PDF时如何在文本行之间添加内边距?
可行实现方案
- 方案1:使用
pw.SizedBox组件精准控制间隔
这是最适配你当前需求的替换方案,直接把现在写的pw.Text('.', style: pw.TextStyle(fontSize: 8))全部替换成对应高度的SizedBox即可,想调整间隔大小只要修改height参数值就可以,完全不会产生多余的可见内容。 - 方案2:给组件添加margin/padding属性
如果间隔是跟在某个特定组件下方,可以直接给该组件设置bottom margin,不需要额外新增间隔组件。比如需要在性别文本下方加间隔,直接给性别对应的Text组件外层套pw.Container加margin,或者直接使用pw.Padding组件包裹。 - 方案3:调整TextStyle的height参数控制行高
如果是同一段落内部的多行文本需要调整行间距,不需要加额外间隔组件,直接给Text的style设置height属性即可,该属性值为字体大小的倍数,比如height: 1.5代表行高为字体大小的1.5倍。 - 方案4:用Column组件分组管理内容
可以把同属一个模块的内容放进同一个pw.Column组件里,通过设置Column的mainAxisAlignment统一控制模块内的元素间距,代码结构会更清晰。
优化后代码示例
// 可以先把重复用到的文本样式抽成公共变量简化代码 final commonTextStyle = pw.TextStyle(fontSize: 10); pdf.addPage(pw.MultiPage( pageFormat: PdfPageFormat.a5, margin: pw.EdgeInsets.all(32), build: (pw.Context context) { return <pw.Widget>[ pw.Text("Methsuwa Family Clinic", style: pw.TextStyle(fontSize: 22)), pw.Header( level: 0, child: pw.Text("No: 607, Medamandiya, Panagoda, Homagame.", style: commonTextStyle), ), pw.Text('Name: ' + name, style: commonTextStyle), pw.Text('Age: ' + age, style: commonTextStyle), pw.Text('Gender: ' + mOF, style: commonTextStyle), // 替换原来的点文本,8对应你之前用8号字体点的间隔高度,可自行调整 pw.SizedBox(height: 8), pw.Text('Complains: ' + complain, style: commonTextStyle), pw.SizedBox(height: 8), pw.Text('Blood Pressure: ' + fullPressure, style: commonTextStyle), pw.SizedBox(height: 8), pw.Table.fromTextArray( context: context, headerStyle: commonTextStyle, cellStyle: commonTextStyle, data: <List<String>>[ <String>['Drug', 'Amount', 'Days', 'When'], ..._data.map((msg) => [msg["drug"], msg["amount"], msg["days"], msg["when"]]) ]), pw.SizedBox(height: 8), pw.Table.fromTextArray( context: context, headerStyle: commonTextStyle, cellStyle: commonTextStyle, data: <List<String>>[ <String>['Investigations'], ...selectedInvestigations.map((msg) => [msg["investigation"]]) ]), ]; }));
内容的提问来源于stack exchange,提问作者LovinduLI
相关产品推荐
相关产品推荐

