No Description

liuxiaolong 77ac86b91c ConversionFlutter - 替换秘钥 1 year ago
android 77ac86b91c ConversionFlutter - 替换秘钥 1 year ago
doc f7d4b0ecd3 ConversionFlutter - README文档优化 1 year ago
ios 77ac86b91c ConversionFlutter - 替换秘钥 1 year ago
lib 83dbf5003e ConversionFlutter - 修复部分iphone设备无法打开转档文件Bug 1 year ago
linux 131c0306b0 ConversionFlutter - 初始化工程 1 year ago
macos 4f169b42ac ConversionFlutter - Android端转档实现 1 year ago
web 131c0306b0 ConversionFlutter - 初始化工程 1 year ago
windows 24f86f77b9 ConversionFlutter - 1.修复Android端文件多选问题 2.UI调整 1 year ago
.gitignore 19aac4a0f6 ConversionFlutter - iOS端代码优化 1 year ago
.metadata 131c0306b0 ConversionFlutter - 初始化工程 1 year ago
README.md f7d4b0ecd3 ConversionFlutter - README文档优化 1 year ago
analysis_options.yaml 131c0306b0 ConversionFlutter - 初始化工程 1 year ago
pubspec.lock 83dbf5003e ConversionFlutter - 修复部分iphone设备无法打开转档文件Bug 1 year ago
pubspec.yaml 83dbf5003e ConversionFlutter - 修复部分iphone设备无法打开转档文件Bug 1 year ago

README.md

ComPDFKitConversion SDK Flutter Platform Usage Guide

ComPDFKitConversion SDK is a powerful file conversion tool that can convert files between various formats on Android,iOS,Mac,Windows,Linux and Web platforms. This article will teach you how to use it on Flutter platform to make your application more flexible and efficient.

Supported Conversion Formats

Conversion SDK supports converting PDF files to the following formats

  • Convert PDF documents to Word documents.
    • Reconstruct content from PDF files into reusable data.
    • Reconstruction (recover page layout, columns, formatting, graphics, and preserve text flow).
    • Support mapping conversion to split-column function.
    • Support the function of combining letters into a string of text.
    • Support floating insertion such as picture rotation cutting.
    • Support converting partial Math or Chemistry function.
    • Support font size, color, bold, italic, and underline recognition.
  • Convert PDF documents to Excel documents.
    • Support data mapping to Excel cells.
    • Support recognition of a small number, currency, and other formats.
    • Support multiple cells merge function.
    • Support different types of content, including text, table, or all content in PDF.
    • Support multiple Worksheet options, including converting one table to one sheet, all tables on one page to one sheet, or all tables in the entire document to one sheet.
  • Convert PDF documents to PPT documents.
    • Convert each page to an editable slide.
    • Support converting text to a PowerPoint text box.
    • Support picture rotation cutting and other floating insertion.
    • Support converting partial Math or Chemistry function.
  • Convert PDF documents to TXT documents.
  • Convert PDF documents to CSV documents.
    • Support extracting only tables from PDF accurately and converting them to CSV, and one table is converted to one CSV file.
  • Convert PDF documents to Image documents.
    • Support converting PDF to high-quality image formats, including PNG and JPEG. All image quality and resolution will remain intact.
  • Convert PDF documents to RTF documents.
    • Support converting PDF to Rich Text Format documents, including text and images.
  • Convert PDF documents to HTML documents.
    • Support converting PDF to HTML, including single-page and multiple-page.

OS Support

Android

ComPDFKit Conversion SDK is supported on Android devices running API level 21 or newer and targeting the latest stable Android version 5.0 (API 30) or higher. Furthermore, ComPDFKit Conversion SDK requires apps to enable Java 11 language features to build.

  • Android Studio Arctic Fox or newer (support AndroidX).
  • Project specifications.
    • A minSdkVersion of 21 (KitKat) or higher.
    • A compileSdkVersion of 30 or higher.
    • A targetSdkVersion of 30 or higher.
    • Android ABI(s): x86, x86_64, armeabi-v7a, arm64-v8a.

iOS

ComPDFKit Conversion SDK requires the latest stable version of Xcode available at the time the release was made. This is a hard requirement, as each version of Xcode is bundled with a specific version of the iOS or macOS Base SDK.

  • iOS 10.0 or higher.
  • macOS 10.10 or higher.
  • Xcode 12.0 or newer for Objective-C.

How to Run a Demo

You can open this project with Android studio. You can find them in the "ComPDFKit_Conversion_Flutter_Demo" folder. In this guide, it takes the "Flutter" demo as an example to show how to run it in Android and iOS.

  1. Import the "ComPDFKit_Conversion_Flutter_Demo” project on Android Studio.
  2. In the toolbar, select "ComPDFKit_Conversion_Flutter_Demo" from the run configurations drop-down menu.
  3. From the target device drop-down menu, select the device that you want to run "ComPDFKit_Conversion_Flutter_Demo" on.
  4. Click "Run".

If you don't have any devices configured, then you need to either connect a device via USB or create an AVD to use the Android Emulator. If you need to run on the ios simulator, please install Xcode

How to integrate ComPDFKit Conversion SDK in the Flutter?

If you want to run the ComPDFKit Conversion SDK on the Flutter platform and integrate it on Android and iOS, you need to integrate the ComPDFKitConversion.aar on the Android side and reference the ComPDFKitConversion.framework on the iOS side. Use the Flutter EventChannel to communicate and thus implement the use of the ComPDFKit Conversion SDK in Flutter.

Integration on Android platform.

  1. Use Android Studio to create a Phone & Tablet project in Kotlin.
  2. Copy ComPDFkitConversion.aar to the Lib directory of the app.
  3. Add the following code into the app’s build.gradle file.
android{ 
    ...
  defaultConfig {
      ...
      ndk {
          abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64"
        } 
    }
    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        viewBinding true
    }
    repositories {
        flatDir {
            dirs 'libs'
        } 
    }
}

dependencies {
  implementation(name: 'ComPDFKitConversion', ext: 'aar')
  ...
}
  1. Apply for read and write permissions in AndroidManifest.xml. xml <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  2. Add the following code into the app’s build.gradle file. Add this license in the AndroidManifest.xml of the main module. xml <meta-data android:name="CPDFConverter_key" android:value="YOUR_LICENSE_KEY_GOES_HERE" /> <meta-data android:name="CPDFConverter_secret" android:value="YOUR_LICENSE_SECRET_GOES_HERE" />

Integration on iOS platform.

To integrate the ComPDFKit_Conversion.framework into your Flutter iOS project, follow these steps:

1.Open your Flutter iOS project using Xcode or other suitable IDE tool. 2.Drag and drop the ComPDFKit_Conversion.framework file into your project, ensuring that they are placed correctly. 0368093e81dc08219a840fb9214750e8.png
3.Click Finish in the popup to complete the addition 9d0e89ccdbb770d5d729da41c9e1875e.png
4.To embed the required frameworks and libraries into your project, you can open the General tab in the project configuration and locate the Frameworks, Libraries, and Embedded Content option. Within this tab, you can select Embed & Sign to embed and sign the necessary frameworks and libraries, which will ensure that your project compiles and runs smoothly. e45f0d765d6c6aade15d2d08846c49f8.png 5.Apply the License Key

  • Swift
    ```swift import UIKit import Flutter

import ComPDFKit_Conversion

@UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application(

_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?

) -> Bool {

  ComPDFKit_Conversion.CPDFConvertKit.setLicenseKey(
  licenseKey: "YOUR_LICENSE_KEY_GOES_HERE", secret: "YOUR_LICENSE_SECRET_GOES_HERE")
  ...
return super.application(application, didFinishLaunchingWithOptions: launchOptions)

} }


- Objective-C<br>
```objc
#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
#import <ComPDFKit_Conversion/ComPDFKit_Conversion.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [CPDFConvertKit setLicenseKey:@"YOUR_LICENSE_KEY_GOES_HERE" secret:@"YOUR_LICENSE_SECRET_GOES_HERE"];
    
  [GeneratedPluginRegistrant registerWithRegistry:self];
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end

Flutter Platform Usage

To demonstrate how to use it, we will take converting a PDF file to a PPT file as an example.

The specific steps are as follows:

First, you need to select a PDF file from your mobile storage. You can do this in your preferred way, or you can use the file_picker plugin to retrieve the file. Here, we will use the file_picker plugin as an example. 1.Add the file_picker plugin in the pubspec.yaml file, and then click Pub get in the upper right corner to complete the plugin addition.

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  file_picker: ^5.2.5
  ...

2.Get PDF file

    FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom, allowedExtensions: ['pdf'], allowMultiple: true);
    if (result != null) {
        List<String?> pdfFiles = result.paths;
    }

3.Generate file conversion information and configure options to convert PDF to PPT.

Map<String, String> options = {
      'dataTag' : tag,
      'convertType' : "PPT",
      'filePath' : pdfFilePath, //Selected pdf file path
      'fileName' : fileName,
      'containImages': true,
      'containAnnotations': true,
    };

2.Using EventChannel to enable communication between Flutter and the Native platform, thereby achieving file conversion functionality.

You can refer to the convert_flutter.dart class in Demo

ElevatedButton(onPressed: () {
     ConvertFlutter().convert(context, pdfFilePath);
},child: Text("convert"))



class ConvertFlutter {
  static const EventChannel _channel =
      EventChannel('com.compdfkit.conversion.flutter.convert');

  void convert(BuildContext context, String pdfFilePath) {
    Map<String, String> options = {
      'dataTag' : "tag",
      'convertType' : "PPT",
      'filePath' : pdfFilePath,
      'fileName' : "fileName",
      'containImages': "true",
      'containAnnotations': "true",
    };
    _channel.receiveBroadcastStream(options).listen((event) {
      Map<dynamic, dynamic> result = event;
      String dataTag = result['dataTag'];
      
      //get convert file progress
      int progress = result['progress'];
      
      //converting : 1
      //convert_success : 2
      //convert_fail : 3
      int convertStatus = result['status'];
      //If the file conversion is successful, you can obtain the saved file path of the converted file through the outputpath field.
      String convertOutputPath = result['outputPath']
      
    }, onDone: () {}, onError: (object) {});
  }
}

The native platform realizes the conversion function

Android platform

1.On the Android platform, you need to use EventChannel to communicate with Flutter and retrieve the serialized data transmitted by Flutter in the onListen method.

class ConvertFlutterPlugin(var activity: MainActivity, flutterPlugin: FlutterEngine) : EventChannel.StreamHandler {
    
    private val channelName = "com.compdfkit.conversion.flutter.convert"
    
    private var channel : EventChannel
    
    init {
        channel = EventChannel(flutterPlugin.dartExecutor.binaryMessenger, channelName)
        channel.setStreamHandler(this)
    }
    
    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {   
        val convertInfoMap = arguments as Map<String, String>
        
    }

    override fun onCancel(arguments: Any?) {

    }
    
}

2.You can use the ComPDFKit Conversion SDK API to perform file conversion operations within the onListen() method. The following demonstration shows you how to convert a PDF file to PPT format.

    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {   
        val convertInfoMap = arguments as Map<String, String>
        val pdfFilePath = convertInfoMap["filePath"]
        val convertType = convertInfoMap["convertType"]
        val isContainImages = convertInfoMap["containImages"].toBoolean()
        val isContainAnnotations = convertInfoMap["containAnnotations"].toBoolean()
        
        activity.lifecycleScope.launch(Dispatchers.IO){
            val pptOptions = CPDFConvertPPTOptions().also {
             it.isContainImages = isContainImages
             it.isContainAnnotations = isContainAnnotation
            }
            //Please convert string type filePath to Uri type 
            //If the pdf file is encrypted, please fill in the file password
            var cPDFConvert = CPDFConverterPPT(context, fileUri, pdfPassword)
            cPDFConvert.convert(outputDir = "outPutDir",
                outputFilenameNoSuffix = "",
                options = pptOptions,
                pageArrays = null,
                onHandle = {
                    //convert start
                }, onProgress = { current, total ->
                    val progress = ((current / total.toFloat()) * 1000).toInt() / 10
                    val resultData = mapOf(
                        "progress" to progress,
                        "dataTag" to dataTag,
                        "status" to 1
                    )
                    
                    activity.lifecycleScope.launch(Dispatchers.Main) {
                        //Return the current conversion progress
                        events?.success(resultData)
                    }
                
                }, onPost = { code, outFilePath ->
                
                    when(code){
                        ConvertError.ERR_SUCCESS->{
                            //convert success
                            val process = mapOf(
                                "progress" to 100, 
                                "dataTag" to dataTag, 
                                "status" to CONVERT_SUCCESS, 
                                "outputPath" to outFilePath
                            )
                            activity.lifecycleScope.launch(Dispatchers.Main) {
                                //Return conversion completion information 
                                events?.success(process)
                            }
                        }
                        ConvertError.ERR_CONVERTING->{
                            ...
                        }
                        else ->{
                            ...
                        }
                }
            })          
        }  
}

3.You need to call ConvertFlutterPlugin.kt in the configureFlutterEngine method of MainActivity.kt.


class MainActivity: FlutterActivity() {

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        ConvertFlutterPlugin(this, flutterEngine)
    }
}

Congratulations, you have successfully integrated the ComPDFKit Conversion SDK into your Flutter application on Android, enabling PDF to PPT conversion.

iOS platform

1.On the iOS platform, you need to use FlutterEventChannel to communicate with Flutter and retrieve the serialized data transmitted by Flutter in the onListen method.

Swift

class ConverFilePlugin{
    
        init(messenger : FlutterBinaryMessenger){
            let channel = FlutterEventChannel(name: "com.compdfkit.conversion.flutter.convert", binaryMessenger: messenger)
            channel.setStreamHandler(SwiftStreamHandler())
        }
        
}


class SwiftStreamHandler: NSObject, FlutterStreamHandler {
    

    
    public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        
        var convertData = arguments as! [String: String];
        var filePath = convertData["filePath"] ?? "";
        let convertType = convertData["convertType"]!;
        let dataTag = String(convertData["dataTag"]!);
        let queue = DispatchQueue(label: "com.compdfkit.conversion.flutter")
        queue.async {
            
            let util = ConvertUtil()
            let options = util.getConvertOptions(withArguments: arguments)
            util.convert(options: options, filePath: filePath, convertType: convertType)
            
        }
            return nil
        }

        public func onCancel(withArguments arguments: Any?) -> FlutterError? {
            return nil
        }
    
}

Objective-C



2.You can use the ComPDFKit Conversion SDK API to perform file conversion operations within the onListen() method. The following demonstration shows you how to convert a PDF file to PPT format.

Swift

import Foundation
import ComPDFKit_Conversion

 class ConvertUtil : NSObject, CPDFConverterDelegate{
    
    let params_convert_type = "convertType";
    let params_file_path = "filePath";
    let params_file_name = "file_name";
    let params_data_tag = "dataTag";
    let params_contain_images = "containImages";
    let params_contain_annotations = "containAnnotations";
    
     var result: ((Int, Int, String?) -> Void)?
    
    func getConvertOptions(withArguments arguments: Any?) -> CPDFConvertOptions {
        let convertData = arguments as! [String: String];
        let isContainImages = Bool(convertData[params_contain_images] ?? "true") ?? true
        let isContainAnnotation = Bool(convertData[params_contain_annotations] ?? "true") ?? true;
        let filePath = convertData[params_file_path];
        let fileName = convertData[params_file_name];

        let pptOptions = CPDFConvertPPTOptions()
            pptOptions.isContainImages = isContainImages
            pptOptions.isContainAnnotations = isContainAnnotation
        return pptOptions
    
    }
    
    
     func convert(options :CPDFConvertOptions, filePath:String, convertType : String, onProgress : @escaping (_ progress : Int, _ status : Int, _ outputPath : String?) -> Void) {
        
        result = onProgress
        
        let outPutPath = NSHomeDirectory() + "/Documents/ConversionDemo"
        
        let fileURL = URL(string: filePath)
        //If the pdf file is encrypted, please fill in the file password
        let pdfConvert : CPDFConverter = CPDFConverterPPT(url: fileURL, password: "")
        //Start converting pdf to ppt
        pdfConvert.convert(toFilePath: outPutPath, pageIndexs: [Int](), options: options)
        pdfConvert?.delegate = self
    }

    

    func converter(_ converter: CPDFConverter!, didStartConvert error: Error!) {
       //conversion started

    }
    
    func converter(_ converter: CPDFConverter!, pageIndex index: UInt, pageCount count: UInt) {
        //conversion in progress
        let progress = Double(index) / Double(count)
        result?(Int(progress*100), 1, nil)
    }
    
    func converter(_ converter: CPDFConverter!, didEndConvert error: Error!) {
        //end of conversion
    }
}


Objective-C


Support

Reporting Problems

Thanks for your interest in ComPDFKit Conversion SDK, the only easy-to-use but powerful development solution. If you encounter any technical questions or bug issues when using ComPDFKit Conversion SDK for Android, please submit the problem report to the ComPDFKit team. More information as follows would help us to solve your problem:

  • ComPDFKit Conversion SDK product and version
  • Your Operating System and IDE version
  • Detailed description of the problem
  • Any other related information, such as error screenshot

    Contact Information

  • Home link: https://www.compdf.com

  • Email: support@pdfreaderpro.com


    Thanks,
    The ComPDFKit Team