Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I/flutter ( 3281): Exception: Exception: Unable to guess the image type 1311710 bytes #1642

Open
565537905qqcom opened this issue Apr 6, 2024 · 0 comments
Labels
bug Something isn't working needs triage

Comments

@565537905qqcom
Copy link

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:docx_template/docx_template.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:flutter_pdfview/flutter_pdfview.dart';

import 'dart:typed_data';

class PdfViewer extends StatefulWidget {
final Map<String, dynamic> template;
final List<Map<String, dynamic>> bankDetailsList;

const PdfViewer({Key? key, required this.template, required this.bankDetailsList})
: super(key: key);

@OverRide
_PdfViewerState createState() => _PdfViewerState();
}

class _PdfViewerState extends State {
String? docxFilePath;
String? pdfFilePath;

@OverRide
void initState() {
super.initState();
final contractNumber = widget.bankDetailsList.isNotEmpty ? widget.bankDetailsList.first['contract_number'] : '';
_generatePdfFromTemplate();
}

@OverRide
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Word Viewer'),
),
body: pdfFilePath == null
? Center(child: CircularProgressIndicator())
: PDFView(
filePath: pdfFilePath!,
enableSwipe: true,
swipeHorizontal: true,
autoSpacing: false,
pageFling: false,
onRender: (_pages) {
setState(() {});
},
onError: (error) {
print(error.toString());
},
onPageError: (page, error) {
print('$page: ${error.toString()}');
},
onViewCreated: (PDFViewController pdfViewController) {
// _controller.complete(pdfViewController);
},
onPageChanged: (int? page, int? total) {
print('page change: $page/$total');
},
),
);
}
Future _generatePdfFromTemplate() async {
try {

  // 从模板文件中创建 DocxTemplate 实例
  final docx = await DocxTemplate.fromBytes(await File(widget.template['pdfFilePath']).readAsBytes());
  
  // 准备图像数据
  final imageBytes = await File(widget.template['sealImagePath']).readAsBytes();



  final listNormal = ['Foo', 'Bar', 'Baz'];
  final listBold = ['ooF', 'raB', 'zaB'];
  final contentList = <Content>[];
  final bold = listBold.iterator;
  for (var n in listNormal) {
    bold.moveNext();
    final plainContent = PlainContent('value')
      ..add(TextContent('normal', n))
      ..add(TextContent('bold', bold.current));
    contentList.add(plainContent);
  }

  Content content = Content();
  content
    ..add(TextContent('docname', 'Simple docname'))
    ..add(TextContent('passport', 'Passport NE0323 4456673'))
    ..add(TableContent('table', [
      RowContent()
        ..add(TextContent('key1', 'Paul'))
        ..add(TextContent('key2', 'Viberg'))
        ..add(TextContent('key3', 'Engineer'))
        ..add(ImageContent('img', imageBytes)),
      RowContent()
        ..add(TextContent('key1', 'Alex'))
        ..add(TextContent('key2', 'Houser'))
        ..add(TextContent('key3', 'CEO & Founder'))
        ..add(ListContent('tablelist', [
          TextContent('value', 'Mercedes-Benz C-Class S205'),
          TextContent('value', 'Lexus LX 570')
        ]))
        ..add(ImageContent('img', imageBytes))
    ]))
    ..add(ListContent('list', [
      TextContent('value', 'Engine')
        ..add(ListContent('listnested', contentList)),
      TextContent('value', 'Gearbox'),
      TextContent('value', 'Chassis')
    ]))
    ..add(ListContent('plainlist', [
      PlainContent('plainview')
        ..add(TableContent('table', [
          RowContent()
            ..add(TextContent('key1', 'Paul'))
            ..add(TextContent('key2', 'Viberg'))
            ..add(TextContent('key3', 'Engineer')),
          RowContent()
            ..add(TextContent('key1', 'Alex'))
            ..add(TextContent('key2', 'Houser'))
            ..add(TextContent('key3', 'CEO & Founder'))
            ..add(ListContent('tablelist', [
              TextContent('value', 'Mercedes-Benz C-Class S205'),
              TextContent('value', 'Lexus LX 570')
            ]))
        ])),
      PlainContent('plainview')
        ..add(TableContent('table', [
          RowContent()
            ..add(TextContent('key1', 'Nathan'))
            ..add(TextContent('key2', 'Anceaux'))
            ..add(TextContent('key3', 'Music artist'))
            ..add(ListContent(
                'tablelist', [TextContent('value', 'Peugeot 508')])),
          RowContent()
            ..add(TextContent('key1', 'Louis'))
            ..add(TextContent('key2', 'Houplain'))
            ..add(TextContent('key3', 'Music artist'))
            ..add(ListContent('tablelist', [
              TextContent('value', 'Range Rover Velar'),
              TextContent('value', 'Lada Vesta SW Sport')
            ]))
        ])),
    ]))
    ..add(ListContent('multilineList', [
      PlainContent('multilinePlain')
        ..add(TextContent('multilineText', 'line 1')),
      PlainContent('multilinePlain')
        ..add(TextContent('multilineText', 'line 2')),
      PlainContent('multilinePlain')
        ..add(TextContent('multilineText', 'line 3'))
    ]))
    ..add(TextContent('multilineText2', 'line 1\nline 2\n line 3'))
    ..add(ImageContent('img', imageBytes));
  // 生成 Word 文档,根据传入的 Content 对象进行替换占位符
  final docGenerated = await docx.generate(content);

  // print('docGenerated的类型是:${docGenerated.runtimeType}');


  // 获取存储目录
  final directory = await getApplicationDocumentsDirectory();
  // 生成路径
  final outputFile = File('${directory.path}/generated_docx_with_replaced_content.docx');
    
  if (docGenerated != null) {
    // 写入文件
    await outputFile.writeAsBytes(docGenerated);

  // 创建 PDF 文档
  final pdf = pw.Document();

  // 从 Word 文件中读取内容,并添加到 PDF 文档中
  final wordFile = File(outputFile.path);
  
  print('Word 文件路径: ${wordFile.path}');

  // 将 Word 文件内容转换为 Uint8List
  final wordBytes = await wordFile.readAsBytes();

  print('Word 文件内容: $wordBytes');
  
  // 使用临时文件创建 pw.Image
    final tempImage = pw.MemoryImage(
      Uint8List.fromList(wordBytes),
    );

    // 添加图像到 PDF 文档中
    pdf.addPage(
      pw.Page(
        build: (pw.Context context) {
          return pw.Center(
            child: pw.Image(tempImage),
          );
        },
      ),
    );

    // 保存 PDF 文件路径以便稍后使用
    setState(() {
      pdfFilePath = outputFile.path;
    });
  }

} catch (e, stackTrace) {
print('Exception: $e');
print('StackTrace: $stackTrace'); // 调用方法获取堆栈跟踪
}
}
} 此代码在把生成的带有图片的word转换为pdf时一直报错I/flutter ( 3281): Exception: Exception: Unable to guess the image type 1311710 bytes!请问哪位大神帮解决一下!万分感谢!

@565537905qqcom 565537905qqcom added bug Something isn't working needs triage labels Apr 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working needs triage
Projects
None yet
Development

No branches or pull requests

1 participant