You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中将docx_template生成的docx文件转换为PDF?

解决docx_template生成的DOCX转PDF问题(基于SyncFusion)

原代码核心问题

  • 错误使用PdfDocument直接加载DOCX字节流:PdfDocument仅用于PDF文档的创建与编辑,不支持解析DOCX格式,必须借助SyncFusion的DocIO库处理Word文档后再转PDF。
  • 存在冗余代码:重复获取应用文档目录,无实际意义。
  • 未做异常处理:无法排查转换过程中的文件读写、格式解析等错误。

修正后的实现方案

1. 配置依赖

在pubspec.yaml中添加SyncFusion相关依赖(请选择适配你项目的版本):

dependencies:
  syncfusion_flutter_docio: ^25.1.39
  syncfusion_flutter_pdf: ^25.1.39
  path_provider: ^2.0.15
  open_file: ^3.2.1

2. 转换代码实现

import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:syncfusion_flutter_docio/document.dart';
import 'package:syncfusion_flutter_pdf/pdf.dart';
import 'package:open_file/open_file.dart';

Future<void> convertDocxToPdf(List<int> docxBytes) async {
  try {
    // 获取应用文档目录
    final directory = await getApplicationDocumentsDirectory();
    final docxPath = '${directory.path}/Engranes Rectos Sistema Ingles.docx';
    final pdfPath = '${directory.path}/Engranes Rectos Sistema Ingles.pdf';

    // 写入docx_template生成的字节到本地文件
    final docxFile = File(docxPath);
    await docxFile.writeAsBytes(docxBytes);

    // 用DocIO加载DOCX文档
    final WordDocument wordDoc = WordDocument(inputBytes: docxFile.readAsBytesSync());

    // 转换为PDF
    final PdfDocument pdfDoc = PdfDocument();
    PdfConverter.convertToPdf(wordDoc, pdfDoc);

    // 保存PDF文件
    final pdfFile = File(pdfPath);
    await pdfFile.writeAsBytes(await pdfDoc.save(), flush: true);

    // 释放资源
    wordDoc.dispose();
    pdfDoc.dispose();

    // 打开生成的PDF
    await OpenFile.open(pdfPath);
  } catch (e) {
    print('转换失败:$e');
  }
}

关键说明

  • 用WordDocument读取DOCX内容:这是SyncFusion专门用于处理Word文档的类,支持从字节流或本地文件加载内容。
  • 通过PdfConverter.convertToPdf完成格式转换:这是SyncFusion官方提供的DOCX转PDF标准方式,能保证格式兼容性。
  • 异常捕获:通过try-catch块捕获转换过程中的各类错误,便于定位问题(比如DOCX格式损坏、存储权限不足等)。

内容的提问来源于stack exchange,提问作者Carlos Aguas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:06:29