如何在Flutter pdf库中实现从下到上的垂直文本显示?
Flutter PDF库实现文本从下到上垂直显示
可行方案:使用pw.Transform.rotate实现旋转
由于该PDF库的Widget系统不支持RotatedBox,但内置的pw.Transform.rotate可以实现文本旋转,关键是设置正确的旋转角度和原点位置,适配容器尺寸。
修改后的完整代码
import 'dart:math' as math; import 'package:pdf/pdf.dart'; import 'package:pdf/widgets.dart' as pw; Future _writeIntoPdf(String? logo) async { final pdf = pw.Document(); pdf.addPage( pw.Page( pageFormat: PdfPageFormat(160, 105), build: (pw.Context context) { return pw.Container( height: 105, width: 160, decoration: pw.BoxDecoration(border: pw.Border.all(width: 1.0)), child: pw.Row(children: [ pw.Container( height: 105, width: 20, color: PdfColor.fromHex('#f72858'), child: pw.Transform.rotate( // 顺时针旋转90度,实现文本从下到上的垂直效果 angle: -math.pi / 2, // 旋转原点设为文本块的中心,适配容器宽度(20) origin: const Offset(10, 10), child: pw.Align( alignment: Alignment.center, child: pw.Text( 'Visitor', style: pw.TextStyle(fontSize: 6), ), ), ), ), // 其他子Widget... ]), ); }, ), ); // 后续保存/导出PDF的逻辑... }
参数说明
- angle: 设置为
-math.pi / 2(等效于顺时针旋转90度),让原本水平的文本变为垂直方向,且呈现从下到上的顺序。 - origin: 旋转原点设置为
Offset(10,10),对应容器宽度的中心(容器宽20),确保旋转后的文本在容器内居中显示。 - pw.Align: 配合旋转后的文本对齐,保证文本在容器内的位置正确。
替代方案:自定义绘制文本
如果Transform方式仍有问题,可以使用pw.CustomPainter直接绘制旋转后的文本:
pw.Container( height: 105, width: 20, color: PdfColor.fromHex('#f72858'), child: pw.CustomPaint( painter: pw.CustomPainterFn((canvas, size) { canvas.save(); // 移动坐标系到容器中心,再旋转 canvas.translate(size.width / 2, size.height / 2); canvas.rotate(-math.pi / 2); // 绘制文本 canvas.drawText( pw.TextStyle(fontSize: 6).getText('Visitor'), Offset(-size.height / 2, -size.width / 2), ); canvas.restore(); }), ), )
内容的提问来源于stack exchange,提问作者Shiju Shaji
相关产品推荐
相关产品推荐

