文件名含斜杠时无法将HTML转换为PDF的问题求助
解决文件名含斜杠导致HTML转PDF失败的问题
问题根源
斜杠(/)是操作系统的路径分隔符,当你传入test_insp_CURR/011作为文件名时,系统会误将其解析为「test_insp_CURR子目录下的011文件」,但该子目录并不存在,因此抛出FileSystemException错误。
直接解决方案:替换非法字符
在调用转换方法前,将文件名中的斜杠替换为下划线等合法字符,避免被解析为路径结构:
Future savePdf(String htmlContents, String pdfFileName) async { Directory documentDirectory = await getApplicationDocumentsDirectory(); String documentPath = documentDirectory.path; // 把文件名里的斜杠替换为下划线 String safeFileName = pdfFileName.replaceAll('/', '_'); print(documentPath); print(safeFileName); await FlutterHtmlToPdf.convertFromHtmlContent(htmlContents, documentPath, safeFileName); }
进阶方案:按目录结构保存(如果确有需要)
如果希望保留目录层级,需要先手动创建对应的子目录,再执行转换:
import 'package:path/path.dart' as p; Future savePdf(String htmlContents, String pdfFileName) async { Directory documentDirectory = await getApplicationDocumentsDirectory(); // 拼接完整的PDF文件路径 String fullFilePath = p.join(documentDirectory.path, pdfFileName); File pdfFile = File(fullFilePath); // 递归创建所有不存在的父目录 await pdfFile.parent.create(recursive: true); // 提取纯文件名(不含路径部分)用于转换时的临时文件 String fileName = p.basename(pdfFileName); await FlutterHtmlToPdf.convertFromHtmlContent(htmlContents, pdfFile.parent.path, fileName); }
注:此方案需要在pubspec.yaml中添加path依赖(版本可按需调整):
dependencies: path: ^1.8.3
内容的提问来源于stack exchange,提问作者Fash
相关产品推荐
相关产品推荐

