Flutter Printing Package自定义页面尺寸不生效问题求助
解决Flutter Printing Package自定义页面尺寸不生效问题
问题分析
设置的2.3cm×4.7cm页面尺寸在预览中显示异常,核心原因有两点:
- 启用了
pw.PageOrientation.landscape参数,该参数会自动交换页面宽高值,导致实际尺寸被反转调整后偏离预期。 - 部分打印机驱动存在自定义尺寸范围限制,会自动将过小的尺寸调整为设备支持的最小尺寸。
解决方案
1. 移除横向方向设置
无需通过orientation参数控制页面方向,直接通过width和height定义实际页面尺寸即可:
await Printing.layoutPdf( format: PdfPageFormat.standard.copyWith( width: 4.7 * PdfPageFormat.cm, // 直接定义实际宽度 height: 2.3 * PdfPageFormat.cm, // 直接定义实际高度 marginBottom: 0.05 * PdfPageFormat.cm, marginLeft: 0.05 * PdfPageFormat.cm, marginRight: 0.05 * PdfPageFormat.cm, marginTop: 0.05 * PdfPageFormat.cm, ), onLayout: (PdfPageFormat format) { final pdf = pw.Document(); pdf.addPage( pw.Page( pageFormat: format, // 移除orientation: pw.PageOrientation.landscape build: (pw.Context context) { return pw.Align( alignment: pw.Alignment.center, child: pw.Container( color: PdfColors.amber, child: pw.Center(child: pw.Text("Hi I am Miraj")), ), ); }, ), ); return pdf.save(); }, );
2. 直接使用点数(pt)定义尺寸(规避单位转换误差)
如果单位转换存在潜在问题,可以直接用点数(1cm≈28.3465pt)计算后设置尺寸:
await Printing.layoutPdf( format: PdfPageFormat.standard.copyWith( width: 4.7 * 28.3465, // 4.7cm 转换为约133.2pt height: 2.3 * 28.3465, // 2.3cm 转换为约65.2pt marginBottom: 0.05 * 28.3465, marginLeft: 0.05 * 28.3465, marginRight: 0.05 * 28.3465, marginTop: 0.05 * 28.3465, ), onLayout: (PdfPageFormat format) { final pdf = pw.Document(); pdf.addPage( pw.Page( pageFormat: format, build: (pw.Context context) { return pw.Align( alignment: pw.Alignment.center, child: pw.Container( color: PdfColors.amber, child: pw.Center(child: pw.Text("Hi I am Miraj")), ), ); }, ), ); return pdf.save(); }, );
3. 检查打印机支持的自定义尺寸
若上述调整后仍不生效,需确认打印机是否支持2.3cm×4.7cm这种小尺寸。部分打印机存在最小页面尺寸限制,会自动将尺寸调整到设备支持的范围。可在打印机设置中查看支持的自定义尺寸列表,确保目标尺寸在允许范围内。
内容的提问来源于stack exchange,提问作者Miraj Hossain Shawon
相关产品推荐
相关产品推荐

