DartでBuildVuマイクロサービスにアクセスする
以下のチュートリアルでは、ホストされたBuildVuクラウドAPIを使用してPDFファイルをHTMLまたはSVGに変換する方法を説明します。対象となるAPIは以下の通りです:
- IDRsolutionsのトライアルおよびクラウドサブスクリプションサービス
- 独自のセルフホストBuildVuマイクロサービス
このチュートリアルでは、REST API を使用します。
開始する前に、最新バージョンのDart SDKがインストールされていることを確認する必要があります。詳細はDartのウェブサイト
で確認できます。
また、以下のライブラリをインストールする必要があります:
http
http_parser
path
以下は、PDFファイルをHTMLまたはSVGに変換するための基本的なコード例です。設定オプションと高度な機能については以下を参照してください。
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:path/path.dart';
import 'dart:convert' as convert;
void main() async {
final apiUrl = 'https://cloud.idrsolutions.com/cloud/buildvu';
final filePath = 'path/to/exampleFile.pdf';
final file = File(filePath);
// Prepare the request headers and form data
final request = http.MultipartRequest('POST', Uri.parse(apiUrl));
request.fields['token'] = 'your_token'; //Required only when connecting to the IDRsolutions trial and cloud subscription service
request.fields['input'] = 'upload';
// Add the file to the form data
final fileBytes = await file.readAsBytes();
final fileStream = http.ByteStream.fromBytes(fileBytes);
final fileLength = file.lengthSync();
final fileName = basename(filePath);
request.files.add(http.MultipartFile(
'file',
fileStream,
fileLength,
filename: fileName,
contentType: MediaType('application', 'pdf'),
));
late String uuid;
// Send the request to upload the file
try {
final response = await request.send();
if (response.statusCode != 200) {
print('Error uploading file: ${response.statusCode}');
exit(1);
}
final responseBody = await response.stream.bytesToString();
final Map<String, dynamic> responseData = convert.jsonDecode(responseBody);
uuid = responseData['uuid'];
print('File uploaded successfully!');
} catch (e) {
print('Error uploading file: $e');
exit(1);
}
// Poll until done
try {
while (true) {
final pollResponse = await http.Request('GET', Uri.parse('$apiUrl?uuid=$uuid')).send();
if (pollResponse.statusCode != 200) {
print('Error Polling: ${pollResponse.statusCode}');
exit(1);
}
final Map<String, dynamic> pollData = convert.jsonDecode(await pollResponse.stream.bytesToString());
if (pollData['state'] == "processed") {
print("Preview URL: ${pollData['previewUrl']}");
print("Download URL: ${pollData['downloadUrl']}");
break;
} else {
print("Polling: ${pollData['state']}");
}
// Wait for next poll
await Future.delayed(Duration(seconds: 1));
}
} catch (e) {
print('Error polling file: $e');
exit(1);
}
}
BuildVuマイクロサービスは、変換完了時に変換のステータス
を送信するコールバックURLを受け付けます。コールバックURLを使用することで、変換が完了したかどうかを判断するためにサービスをポーリングする必要がなくなります。
コールバックURLは、以下のようにparamsマップに指定できます。
final request = http.MultipartRequest('POST', Uri.parse(apiUrl));
request.fields['token'] = 'your_token'; //Required only when connecting to the IDRsolutions trial and cloud subscription service
request.fields['input'] = 'upload';
request.fields['callbackUrl'] = 'http://listener.url';
BuildVu APIは、変換をカスタマイズするためのキーと値のペアの設定オプションを含む文字列化されたJSONオブジェクトを受け付けます。設定はparameters配列に追加する必要があります。PDFファイルをHTMLまたはSVGに変換するための設定オプションの完全なリストはこちら で確認できます。
final settings = {
"key": "value",
"key": "value",
};
final settingsJson = convert.jsonEncode(settings);
final request = http.MultipartRequest('POST', Uri.parse(apiUrl));
request.fields['settings'] = settingsJson;
ローカルファイルをアップロードするだけでなく、BuildVuマイクロサービスがダウンロードして変換を実行するURLを提供することもできます。これを行うには、parameters変数のinputとfileの値を以下のように置き換える必要があります。
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
void main() async {
final apiUrl = 'https://cloud.idrsolutions.com/cloud/buildvu';
final fileUrl = 'hosted_file_url';
final fileName = 'hosted_file_name';
try {
// Get the file from the URL
final response = await http.get(Uri.parse(fileUrl));
if (response.statusCode == 200) {
// Convert the file content to bytes
final fileBytes = response.bodyBytes;
// Prepare the request headers and form data
final request = http.MultipartRequest('POST', Uri.parse(apiUrl));
request.fields['token'] = 'your_token'; //Required only when connecting to the IDRsolutions trial and cloud subscription service
request.fields['input'] = 'upload';
// Add the downloaded file to the form data
final fileStream = http.ByteStream.fromBytes(fileBytes);
final fileLength = fileBytes.length;
request.files.add(http.MultipartFile(
'file',
fileStream,
fileLength,
filename: fileName,
contentType: MediaType('application', 'pdf'),
));
// Send the request to upload the file (same as above code example)
// Poll until done (same as above code example)
} else {
print('Error downloading file: ${response.statusCode}');
}
} catch (e) {
print('Error: $e');
}
}
BuildVuマイクロサービスが認証を必要とする場合は、ユーザー名とパスワードを提供する必要があります。これらは、以下のようにusernameとpasswordという名前の2つの変数をconvertメソッドに渡すことで提供されます。
String apiUrl = 'https://your-api-url.com/endpoint';
String username = 'your-username';
String password = 'your-password';
String credentials = '$username:$password';
String base64Credentials = base64Encode(utf8.encode(credentials));
Map<String, String> headers = {'Authorization': 'Basic $base64Credentials',};
try {
final response = await http.get(Uri.parse(apiUrl), headers: headers);
if (response.statusCode == 200) {
print('Response body: ${response.body}');
} else {
print('Failed to load data. Status code: ${response.statusCode}');
}
} catch (e) {
print('Error: $e');
}
