Flutter文本或图片生成PDF文件

Flutter PDF框架:
pub:https://pub.dev/packages/pdf
导入: pdf: ^3.7.1
写文本
static Future<String?> writeTxtToPdf(String text, String saveFile) async {

File file = new File(saveFile);
if(file.existsSync()) {
  return saveFile;
}

// 中文字库设置,否则中文解析会报错
final ttf = pw.Font.ttf(await rootBundle.load('local_files/fonts/Alibaba-PuHuiTi-Regular.ttf'));
final pdf = pw.Document( );
//分页
pdf.addPage(pw.MultiPage(
    footer: (pw.Context context) {
      return pw.Container(
          alignment: pw.Alignment.centerRight,
          margin: const pw.EdgeInsets.only(top: 1.0 * PdfPageFormat.cm),
          child: pw.Text(
              '${context.pageNumber} / ${context.pagesCount}',
              style: pw.TextStyle(fontSize: 12, color: PdfColors.grey))
      );
    },
    build: (pw.Context context) {
      return [
        pw.Column(
            crossAxisAlignment: pw.CrossAxisAlignment.start,
            children: _splitText(text, ttf)
        )
      ];
    }
));

await file.writeAsBytes(await pdf.save());
return saveFile;

}
static List<pw.Widget> _splitText(String text, pw.Font ttf) {
pw.TextStyle style = pw.TextStyle(font: ttf, fontSize: 18);
List list = text.split(’\n’);
List<pw.Widget> widgets = [];
list.forEach((element) {
widgets.add(pw.Text(element, style: style));
});
return widgets;
}

//写入图片

static Future<String?> writeImagesToPdf(List imgPathList, String saveFile) async {

File file = new File(saveFile);
if(file.existsSync()) {
  return saveFile;
}
final pdf = pw.Document();
pdf.addPage(pw.MultiPage(
    footer: (pw.Context context) {
      return pw.Container(
          alignment: pw.Alignment.centerRight,
          margin: const pw.EdgeInsets.only(top: 1.0 * PdfPageFormat.cm),
          child: pw.Text(
              '${context.pageNumber} / ${context.pagesCount}',
              style: pw.TextStyle(fontSize: 12, color: PdfColors.grey))
      );
    },
    build: (pw.Context context) {
      return _splitImages(imgPathList);
    }
));

await file.writeAsBytes(await pdf.save());
return saveFile;

}
static List<pw.Widget> _splitImages(List imgPathList) {
List<pw.Widget> widgets = [];
imgPathList.forEach((element) {
// widgets.add(pw.Image(pw.ImageImage(im.decodeImage(File(element).readAsBytesSync())!)));
widgets.add(pw.Column(
children: [
//本地图片,另外api还有保存网络图netImage,资源图等
pw.Image(pw.MemoryImage(File(element).readAsBytesSync()),width: 500,height: 300),
pw.SizedBox(height: 30)
]
));
});
return widgets;
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值