Home > Mobile >  I want to use API for convert word file to pdf file in my flutter app using convertapi.com ,what is
I want to use API for convert word file to pdf file in my flutter app using convertapi.com ,what is

Time:03-09

import 'dart:io';
import 'package:aconvert/pages/view.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:convert';
import 'dart:typed_data';
import 'package:aconvert/services/api.dart';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;
import 'package:pdf_viewer_plugin/pdf_viewer_plugin.dart';

//final clientId = '2720faeb-aa0f-46ee-aa0a-8bf7559268fc';
//final secret = '65cc9d8e63d2a01be5dd5abde8cbc970';
//var configuration = Configuration(secret, clientId);
class Docx extends StatefulWidget {
  const Docx({Key? key}) : super(key: key);

  @override
  _DocxState createState() => _DocxState();
}

class _DocxState extends State<Docx> {
//view pdf
  String? docFilePath;
  String? docFilename;
  String? docFiledata;
  File? _file;
  late final pathController = TextEditingController();


  pick_file() async{
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['doc','txt','TXT','png','jpg','pdf','PDF','rtf'],
    );

    if (result != null) {
      // List<File> files = result.paths.map((path) => File(path!)).toList();
      File file = File(result.files.single.path!);
      _file =  File(result.files.single.path!);
      setState(() {
        docFilePath =result.files.single.path!;
        docFilename = _file?.path.split('/').last;
        Uint8List? fileInByte = _file?.readAsBytesSync();
         docFiledata = base64Encode(fileInByte!);
         print("******** $docFilename **********");

      });

    } else {
      // User canceled the picker
    }
  }
  // convert to pdf api

  Future postfile() async{
    String url = 'https://v2.convertapi.com/convert/doc/to/pdf?Secret=5Wq3HMYGVzqViAXJ&Token=636106935&StoreFile=true';
    final Uri uri  = Uri.parse(url);
   http.Response response = await http.post(uri,body: {

       "Parameters": [
         {
           "Name": "File",
           "FileValue": {
             "Name": docFilename,
             "Data": docFiledata
           }
         },
         {
           "Name": "StoreFile",
           "Value": true
         }
       ]

    } , headers: {
      "Content-Type": "application/json"
    });
    var responsebody = json.decode(response.body) ;
   print('Response status: ${response.statusCode}');
    print('------------------------------------');
    print('Response body: ${response.body}');
    print('------------------------------------');
    print('Response body: ${responsebody}');

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text('from docx to pdf'),
        titleTextStyle: TextStyle(color: Colors.white70 , fontSize: 25 , fontWeight: FontWeight.bold),
        backgroundColor: Colors.deepOrangeAccent,
        elevation: 0,
        centerTitle: true,
      ),
      body: SingleChildScrollView(

        child:Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(height: 20,),
            InkWell(
              onTap: pick_file,
              child: Container(
                  height: 60,
                  padding: EdgeInsets.all(10),
                  margin: EdgeInsets.all(10),

                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20),
                    color: Colors.redAccent,
                  ),

                  child: Center(child: Text('select file ' ,style: TextStyle(fontSize: 30,color: Colors.white), ))),
            ),
            SizedBox(height: 20,),
            InkWell(
              onTap: (){
                Get.to(()=>View(docFilePath!));
              },
              child: Container(
                  height: 60,
                  padding: EdgeInsets.all(10),
                  margin: EdgeInsets.all(10),

                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20),
                    color: Colors.redAccent,
                  ),

                  child: Center(child: Text('show selected file' ,style: TextStyle(fontSize: 30,color: Colors.white), ))),
            ),
            SizedBox(height: 20,),
                //convert
            InkWell(
              onTap: postfile,
              child: Container(
                  height: 60,
                  padding: EdgeInsets.all(10),
                  margin: EdgeInsets.all(10),

                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20),
                    color: Colors.redAccent,
                  ),

                  child: Center(child: Text('convert' ,style: TextStyle(fontSize: 30,color: Colors.white), ))),
            ),
            SizedBox(height: 20,),
            InkWell(
              onTap: (){},
              child: Container(
                  height: 60,
                  padding: EdgeInsets.all(10),
                  margin: EdgeInsets.all(10),

                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20),
                    color: Colors.redAccent,
                  ),

                  child: Center(child: Text('upload to cloud' ,style: TextStyle(fontSize: 30,color: Colors.white), ))),
            ),


          ],
        ),
      ),
    );
  }
}

E/flutter (11254): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Bad state: Cannot set the body fields of a Request with content-type "application/json". E/flutter (11254): #0 Request.bodyFields= (package:http/src/request.dart:133:7) E/flutter (11254): #1 BaseClient._sendUnstreamed (package:http/src/base_client.dart:87:17) E/flutter (11254): #2 BaseClient.post (package:http/src/base_client.dart:32:7) E/flutter (11254): #3 post. (package:http/http.dart:69:16) E/flutter (11254): #4 _withClient (package:http/http.dart:164:20) E/flutter (11254): #5 post (package:http/http.dart:68:5) E/flutter (11254): #6 _DocxState.postfile (package:aconvert/pages/fromdocxtopdf.dart:61:40) E/flutter (11254): #7 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21) E/flutter (11254): #8 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:198:24) E/flutter (11254): #9 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11) E/flutter (11254): #10 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5) E/flutter (11254): #11 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:230:7) E/flutter (11254): #12 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:563:9) E/flutter (11254): #13 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:94:12) E/flutter (11254): #14 PointerRouter._dispatchEventToRoutes. (package:flutter/src/gestures/pointer_router.dart:139:9) E/flutter (11254): #15 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8) E/flutter (11254): #16 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:137:18) E/flutter (11254): #17 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:123:7) E/flutter (11254): #18 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:439:19) E/flutter (11254): #19 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22) E/flutter (11254): #20 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:322:11) E/flutter (11254): #21 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7) E/flutter (11254): #22 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5) E/flutter (11254): #23 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7) E/flutter (11254): #24 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7) E/flutter (11254): #25 _rootRunUnary (dart:async/zone.dart:1442:13) E/flutter (11254): #26 _CustomZone.runUnary (dart:async/zone.dart:1335:19) E/flutter (11254): #27 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7) E/flutter (11254): #28 _invoke1 (dart:ui/hooks.dart:170:10) E/flutter (11254): #29 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7) E/flutter (11254): #30 _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31) E/flutter (11254):

CodePudding user response:

You need to wrap the body with jsonEncode()

final body = {

       "Parameters": [
         {
           "Name": "File",
           "FileValue": {
             "Name": docFilename,
             "Data": docFiledata
           }
         },
         {
           "Name": "StoreFile",
           "Value": true
         }
       ]

    };

http.Response response = await http.post(
 uri, 
 body: jsonEncode(body), 
 headers: {"Content-Type": "application/json"}
);
  • Related