liuxiaolong 77ac86b91c ConversionFlutter - 替换秘钥 | vor 1 Jahr | |
---|---|---|
android | vor 1 Jahr | |
doc | vor 1 Jahr | |
ios | vor 1 Jahr | |
lib | vor 1 Jahr | |
linux | vor 1 Jahr | |
macos | vor 1 Jahr | |
web | vor 1 Jahr | |
windows | vor 1 Jahr | |
.gitignore | vor 1 Jahr | |
.metadata | vor 1 Jahr | |
README.md | vor 1 Jahr | |
analysis_options.yaml | vor 1 Jahr | |
pubspec.lock | vor 1 Jahr | |
pubspec.yaml | vor 1 Jahr |
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.
Conversion SDK supports converting PDF files to the following formats
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.
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.
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.
- Import the "ComPDFKit_Conversion_Flutter_Demo” project on Android Studio.
- In the toolbar, select "ComPDFKit_Conversion_Flutter_Demo" from the run configurations drop-down menu.
- From the target device drop-down menu, select the device that you want to run "ComPDFKit_Conversion_Flutter_Demo" on.
- 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
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.
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')
...
}
xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
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" />
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.
3.Click Finish in the popup to complete the addition
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.
5.Apply the License Key
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
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) {});
}
}
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.
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.
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
}
}
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.
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
}
}
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:
Any other related information, such as error screenshot
Home link: https://www.compdf.com
Email: support@pdfreaderpro.com
Thanks,
The ComPDFKit Team