In this article I will show you how you can use our PDF files to HTML API to convert documents to HTML with our library BuildVu. PDF to HTML conversion helps you to optimise your PDF content for display on browsers. We have a separate article explaining the benefits of converting PDF to HTML.
Convert PDF to HTML using Java
- Download the BuildVu trial jar
- Add the BuildVu Jar to your project libraries
- Choose conversion options
- Choose viewer options
- Set PDF file path and output directory
HTMLConversionOptions conversionOptions = new HTMLConversionOptions();
// Set conversion options here e.g. conversionOptions.setCompressImages(true);
IDRViewerOptions viewerOptions = new IDRViewerOptions();
// Set viewer options here e.g. viewerOptions.setViewerUI(IDRViewerOptions.ViewerUI.Clean);
File pdfFile = new File("C:/MyDocument.pdf");
File outputDir = new File("C:/MyOutputDirectory/");
PDFtoHTML5Converter converter = new PDFtoHTML5Converter(pdfFile, outputDir, conversionOptions, viewerOptions);
try {
converter.convert();
} catch (PdfException e) {
e.printStackTrace();
}
Convert PDF to HTML from the command line
You can run the BuildVu API to convert directly from the command line which is useful for using the converter with another language or script.
- Download the BuildVu trial jar
- Set the input directory and output directory
- Choose conversion options
- Increase the XMX value according to need
java -Xmx512M -jar buildvu-html.jar /inputDirectory/ /outputDirectory/
The default mode generates the document inside the IDRViewer. To generate just the raw content to be used inside your own custom solution, you can use:
java -Dorg.jpedal.pdf2html.viewMode=content -jar buildvu-svg.jar /inputDirectory/ /outputDirectory/
You can also convert PDF to HTML in a lot of other languages using a hosted BuildVu Cloud API using:
- The IDRsolutions trial and cloud subscription service
- Your own self-hosted BuildVu microservice
Convert PDF to HTML using Ruby
While you can access these services using standard HTTP requests, this tutorial utilizes our open-source Ruby IDRCloudClient, which offers a straightforward Ruby wrapper for the REST API.
Prerequisites
There are two ways to integrate the IDRCloudClient into your project.
Using the gem: Install the idr_cloud_client gem with the following command:
gem install idr_cloud_client
Alternatively, add the line “gem ‘idr_cloud_client'” to your application’s Gemfile and then run the following command:
bundle install
You can check out documentation for BuildVu to learn more on how to turn PDF into an HTML. If you want to convert PDF to SVG you can check out our other article here.
Code Example
Below is a simple code example to convert PDF files to HTML or SVG. Additional configuration options and advanced features are detailed below:
require ‘idr_cloud_client’
client = IDRCloudClient.new(‘https://cloud.idrsolutions.com/cloud/’ + IDRCloudClient::BUILDVU)
result = client.convert(
# token=’Token’, # Required only when connecting to the IDRsolutions trial and cloud subscription service
input: IDRCloudClient::UPLOAD,
file: ‘path/to/exampleFile.pdf’)
client.download_result(result, ‘path/to/output/dir’)
puts ‘Download URL: ‘ + result[‘downloadUrl’]
Return result to a callback url
The BuildVu Microservice supports a callback URL to notify you of the conversion status upon completion. This eliminates the need to continuously check the service for updates. You can provide the callback URL to the convert method as demonstrated below:
result = client.convert(
# token=’Token’, # Required only when connecting to the IDRsolutions trial and cloud subscription service
input: IDRCloudClient::UPLOAD,
callbackUrl: ‘http://listener.url’,
file: ‘path/to/exampleFile.pdf’)
Configuration Options
The BuildVu API allows customization of your conversion using a stringified JSON object with key-value pair configuration options. Provide these settings to the convert method. A comprehensive list of configuration options for converting PDF files to HTML or SVG is available here.
settings:'{"key":"value","key":"value"}’
Upload by URL
In addition to uploading a local file, you can provide a URL that the BuildVu Microservice will download and convert. To do this, replace the input and file values in the convert method with the following.
input:IDRCloudClient.DOWNLOAD
url:’http://exampleURL/exampleFile.pdf’
Using Authentication
If you’ve set up your own BuildVu Microservice that needs a username and password for converting PDF files to HTML, you must provide these credentials with each conversion. You can do this by passing a variable named auth to the convert method as demonstrated below.
auth:(‘username’, ‘password’))
Convert PDF to HTML using Python
This tutorial uses our Python IDRCloudClient open source which provides a simple Python wrapper around the REST API.
Prerequisites
Using pip, install the IDRCloudClient package with the following command:
pip install IDRCloudClient
Code Examples
Below is a basic code example for converting PDF files to HTML or SVG. Additional configuration options and advanced features are detailed below.
from IDRSolutions import IDRCloudClient
client = IDRCloudClient(‘https://cloud.idrsolutions.com/cloud/’ + IDRCloudClient.BUILDVU)
try:
result = client.convert(
# token=’Token’, # Required only when connecting to the IDRsolutions trial and cloud subscription service
input=IDRCloudClient.UPLOAD,
file=’/path/to/exampleFile.pdf’
)
outputURL = result[‘downloadUrl’]
client.downloadResult(result, ‘path/to/output/dir’)
if outputURL is not None:
print("Download URL: " + outputURL)
except Exception as error:
print(error)
Return result to a callback url
The BuildVu Microservice supports a callback URL to send the status of a conversion on completion. Using a callback URL eliminates the need to continually check the service for updates. You can provide the callback URL to the `convert` method as shown below:
result = client.convert(
# token=’Token’, # Required only when connecting to the IDRsolutions trial and cloud subscription service
input=IDRCloudClient.UPLOAD,
callbackUrl=’http://listener.url’,
file=’/path/to/exampleFile.pdf’
)
Configuration Options
The BuildVu API allows for conversion customization using a stringified JSON object with key-value pair configuration options. Provide these settings to the convert method. A comprehensive list of options for converting PDF files to HTML or SVG is available here.
settings='{"key":"value","key":"value"}’
Upload by URL
In addition to uploading a local file, you can provide a URL for the BuildVu Microservice to download and convert. Simply replace the input and file values in the convert method with the following.
input=IDRCloudClient.DOWNLOAD
url=’http://exampleURL/exampleFile.pdf’
Using Authentication
For deployments of your own BuildVu Microservice that require a username and password for PDF-to-HTML or SVG conversions, provide these credentials with each conversion. Pass a variable named auth to the convert method as demonstrated below.
auth=(‘username’, ‘password’))
Convert PDF to HTML using PHP
Although the services can be accessed with standard HTTP requests, this tutorial uses our open-source PHP IDRCloudClient, which offers a straightforward PHP wrapper for the REST API.
Prerequisites
To install the idrsolutions-php-client package using Composer, execute the following command:
composer require idrsolutions/idrsolutions-php-client
Code Examples
This is a basic code example to convert PDF files to HTML or SVG. Configuration options and advanced features are detailed below:
‘Token’, // Required only when connecting to the IDRsolutions trial and cloud subscription service
‘input’ => IDRCloudClient::INPUT_UPLOAD,
‘file’ => __DIR__ . ‘path/to/file.pdf’
);
$results = IDRCloudClient::convert(array(
‘endpoint’ => $endpoint,
‘parameters’ => $parameters
));
IDRCloudClient::downloadOutput($results, __DIR__ . ‘/’);
echo $results[‘downloadUrl’];
Return result to a callback url
The BuildVu Microservice supports a callback URL to send the status upon conversion completion, eliminating the need to constantly poll the service. You can provide the callback URL to the parameters array as demonstrated below:
$parameters = array(
//’token’ => ‘Token’, // Required only when connecting to the IDRsolutions trial and cloud subscription service
‘input’ => IDRCloudClient::INPUT_UPLOAD,
‘callbackUrl’ => ‘http://listener.url’,
‘file’ => __DIR__ . ‘path/to/file.pdf’
);
Configuration Options
The BuildVu API allows for conversion customization using a stringified JSON object with key-value pair configuration options. Add these settings to the parameters array. A comprehensive list of options for converting PDF files to HTML or SVG can be found here.
‘settings’ => ‘{"key":"value","key":"value"}’
Upload by URL
In addition to uploading a local file, you can provide a URL for the BuildVu Microservice to download and convert. Simply replace the input and file values in the parameters array with the following.
‘input’ => IDRCloudClient.DOWNLOAD
‘url’ => ‘http://exampleURL/exampleFile.pdf’
Using Authentication
If you’ve deployed your own BuildVu Microservice that requires a username and password for converting PDF files to HTML or SVG, you’ll need to provide these credentials for each conversion. Add two variables named username and password to the parameters array, as shown below.
‘username’ => ‘Username_If_Required’,
‘password’ => ‘Password_If_Required’,
In such cases, you’ll also need to provide the authentication values to the downloadOutput method.
IDRCloudClient::downloadOutput($results, __DIR__ . ‘/’,’newFileName’,’username’,’password’);
Convert PDF to HTML using NodeJS
To install the idrcloudclient package using npm, run the following command:
npm install –save @idrsolutions/idrcloudclient
Create an idrcloudclient object with:
var idrcloudclient = require(‘@idrsolutions/idrcloudclient’);
Create endpoint variable
var endpoint = ‘https://cloud.idrsolutions.com/cloud/’ + idrcloudclient.BUILDVU;
Create Parameters map to upload a file
var parameters = {
//token: ‘Token’, //Required only when connecting to the IDRsolutions trial and cloud subscription service
input: idrcloudclient.UPLOAD,
file: ‘path/to/exampleFile.pdf’
}
[Optional] Create listeners to trigger on progress, success, and failure.
function progressListener(e) {
console.log(JSON.stringify(e));
}
function failureListener(e) {
console.log(e);
console.log(‘Failed!’);
}
function successListener(e) {
console.log(JSON.stringify(e));
console.log(‘Download URL: ‘ + e.downloadUrl);
}
Call convert method using variables created previously
idrcloudclient.convert({
endpoint: endpoint,
parameters: parameters,
// The below are the optional listeners, ignore any you haven’t defined
progress: progressListener,
success: successListener,
failure: failureListener
});
Return result to a callback url
The BuildVu Microservice supports a callback URL to notify you upon conversion status completion. Using a callback URL eliminates the need to constantly poll the service.
You can provide the callback URL to the parameters variable as demonstrated below:
var parameters = {
//token: ‘Token’, //Required only when connecting to the IDRsolutions trial and cloud subscription service
input: idrcloudclient.UPLOAD,
callbackUrl: ‘http://listener.url’,
file: ‘path/to/exampleFile.pdf’
}
Complete Code Example
Here is a complete code example for converting PDF files to HTML or SVG, following the steps outlined in the previous sections. Configuration options and advanced features can be found in the sections that follow:
var idrcloudclient = require(‘@idrsolutions/idrcloudclient’);
function progressListener(e) {
console.log(JSON.stringify(e));
}
function failureListener(e) {
console.log(e);
console.log(‘Failed!’);
}
function successListener(e) {
console.log(JSON.stringify(e));
console.log(‘Download URL: ‘ + e.downloadUrl);
}
var endpoint = ‘https://cloud.idrsolutions.com/cloud/’ + idrcloudclient.BUILDVU;
var parameters = {
//token: ‘Token’, //Required only when connecting to the IDRsolutions trial and cloud subscription service
input: idrcloudclient.UPLOAD,
file: ‘path/to/exampleFile.pdf’
}
idrcloudclient.convert({
endpoint: endpoint,
parameters: parameters,
// The below are the available listeners
progress: progressListener,
success: successListener,
failure: failureListener
});
Configuration Options
The BuildVu API allows for conversion customization using a stringified JSON object with key-value pair configuration options. Add these settings to the parameters array. A comprehensive list of options for converting PDF files to HTML or SVG is available here.
settings: ‘{"key":"value","key":"value"}’
Upload by URL
In addition to uploading a local file, you can provide a URL for the BuildVu Microservice to download and convert. Replace the input and file values in the parameters variable with the following.
input: IDRCloudClient.DOWNLOAD
url: ‘http://exampleURL/exampleFile.pdf’
Using Authentication
If you’ve deployed your own BuildVu Microservice that requires a username and password for converting PDF files to HTML or SVG, you will need to provide these credentials for each conversion. Add two variables named username and password to the convert method as shown below.
username: ‘username’,
password: ‘password’,
Convert PDF to HTML using JavaScript
This tutorial uses our open source Javascript IDRCloudClient which provides a simple Javascript wrapper around the REST API.
Prerequisites
To incorporate the client into your project, add the idrcloudclient.js file to your project and include the following line to access it:
<script src="path/to/idrcloudclient.js" type="text/javascript"></script>
Code Examples
Here is a simple code example for converting PDF files to HTML or SVG. Detailed configuration options and advanced features are provided below:
var endpoint = ‘https://cloud.idrsolutions.com/cloud/’ + IDRCloudClient.BUILDVU;
var parameters = {
//token: ‘Token’, //Required only when connecting to the IDRsolutions trial and cloud subscription service
input: IDRCloudClient.UPLOAD,
file: ‘path/to/exampleFile.pdf’
}
function progressListener(e) {
console.log(JSON.stringify(e));
}
function failureListener(e) {
console.log(e);
console.log(‘Failed!’);
}
function successListener(e) {
console.log(JSON.stringify(e));
console.log(‘Download URL: ‘ + e.downloadUrl);
}
IDRCloudClient.convert({
endpoint: endpoint,
parameters: parameters,
// The below are the available listeners
progress: progressListener,
success: successListener,
failure: failureListener
});
You can find an example using the JavaScript client here.
Return result to a callback url
The BuildVu Microservice supports a callback URL to notify you of the status of a conversion upon completion. Using a callback URL eliminates the need to constantly poll the service.
You can provide the callback URL to the parameters variable as demonstrated below:
var parameters = {
//token: ‘Token’, //Required only when connecting to the IDRsolutions trial and cloud subscription service
input: IDRCloudClient.UPLOAD,
callbackUrl: ‘http://listener.url’,
file: ‘path/to/exampleFile.pdf’
}
Configuration Options
The BuildVu API allows for conversion customization using a stringified JSON object with key-value pairs. These settings should be added to the parameters array. A complete list of configuration options for converting PDF files to HTML or SVG can be found here.
settings: ‘{"key":"value","key":"value"}’
Upload by URL
In addition to uploading a local file, you can provide a URL for the BuildVu Microservice to download and convert. Replace the input and file values in the parameters variable with the following:
input: IDRCloudClient.DOWNLOAD
url: ‘http://exampleURL/exampleFile.pdf’
Using Authentication
If you have deployed your own BuildVu Microservice that requires a username and password to convert PDF files to HTML or SVG, you must provide these credentials for each conversion. Pass two variables named username and password to the convert method as shown below.
username: ‘username’,
password: ‘password’,
Convert PDF to HTML using cURL
Although the aforementioned services can be accessed using cURL with the REST API.
Prerequisites
Before you begin, ensure that cURL is installed. Setup instructions vary based on your operating system; more details can be found on the cURL website.
Code Examples
Here is a simple code example for converting PDF files to HTML or SVG. Please note that the file entry must be prefixed with ‘@’, followed by the file path (absolute or relative).
Detailed configuration options and advanced features are provided below:
curl -X POST -F input="upload" -F file="@/path/to/file/myfile.pdf" https://cloud.idrsolutions.com/cloud/buildvu
# Variable token required when connecting to the IDRsolutions trial or cloud subscription servers, example below
curl -X POST -F input="upload" -F file="@/path/to/file/myfile.pdf" -F token=Token https://cloud.idrsolutions.com/cloud/buildvu
The response will contain a uuid and will be in Jason format.
{"uuid" : "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}
You can use this to poll the progress of your conversion and obtain the URL for the output once the conversion is complete.
curl https://cloud.idrsolutions.com/cloud/buildvu?uuid=aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa
The response will be in JSON format and will include the following details:
{
"state" : "processed",
"downloadUrl" : "output/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa/myfile.zip",
"previewUrl" : "output/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa/myfile/index.html"
}
You can use the previewURL to view the output in your browser.
Additionally, you can download the converted output using the download URL with the following cURL request.
# Download the file to the current directory as it is named, in this case "myfile.zip"
curl https://cloud.idrsolutions.com/cloud/buildvu/output/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa/myfile.zip -LO –output "output.zip"
Return result to a callback url
The BuildVu Microservice supports a callback URL to notify of the status of conversion completion. Using a callback URL eliminates the need to poll the service to determine when the conversion is finished.
The callback URL can be provided as shown below:
curl -X POST -F input="upload" -F callbackUrl="http://listener.url" -F file="@/path/to/file/myfile.pdf" https://cloud.idrsolutions.com/cloud/buildvu
# Variable token required when connecting to the IDRsolutions trial or cloud subscription servers, example below
curl -X POST -F input="upload" -F callbackUrl="http://listener.url" -F file="@/path/to/file/myfile.pdf" -F token=Token https://cloud.idrsolutions.com/cloud/buildvu
Configuration Options
The BuildVu API allows you to customize your conversion by accepting a stringified JSON object with key-value pairs for configuration options. These settings should be added before the URL in the cURL command. You can find a complete list of configuration options for converting PDF files to HTML or SVG here.
Note that the syntax for escaping double quotes can vary depending on the environment you use, make sure to check what works for your specific environment:
Note that for PowerShell your command should start with curl.exe –% to avoid parsing errors.
Upload by URL
In addition to uploading a local file, you can provide a URL for the BuildVu Microservice to download and convert. Simply replace the input and file values with the following.
-F input=download -F url="http://exampleURL/exampleFile.pdf"
Using Authentication
If you’ve deployed your own BuildVu Microservice that requires a username and password for converting PDF files to HTML or SVG, you need to provide these credentials for each conversion. Add the user flag with the username and password before the URL.
–user username:password
Convert PDF to HTML using C#
Although the aforementioned services can be accessed using plain HTTP requests, this tutorial utilizes our open-source C# IDRCloudClient, which offers a straightforward C# wrapper around the REST API.
Prerequisites
To install the idrsolutions-csharp-client package using NuGet, run the following command:
nuget install idrsolutions-csharp-client
Code Example
Here is a basic code example for converting PDF files to HTML or SVG. Detailed configuration options and advanced features are provided below.
using System;
using System.Collections.Generic;
using idrsolutions-csharp-client;
class ExampleUsage
{
static void Main(string[] args)
{
var client = new IDRCloudClient("https://cloud.idrsolutions.com/cloud/" + IDRCloudClient.BUILDVU);
try
{
Dictionary parameters = new Dictionary
{
//["token"] = "Token", //Required only when connecting to the IDRsolutions trial and cloud subscription service
["input"] = IDRCloudClient.UPLOAD,
["file"] = "path/to/input.pdf"
};
Dictionary results = client.Convert(parameters);
String outputUrl = results.GetValueOrDefault("downloadUrl", "No download URL provided");
client.DownloadResult(results, "path/to/output/dir");
Console.WriteLine("Converted: " + outputUrl);
}
catch (Exception e)
{
Console.WriteLine("Conversion failed: " + e.Message);
}
}
}
Return result to a callback url
The BuildVu Microservice supports a callback URL to notify you on the status of conversion completion. Using a callback URL eliminates the need to poll the service to check when the conversion is complete.
The callback URL can be provided to the convert method as demonstrated below:
Dictionary parameters = new Dictionary
{
//["token"] = "Token", //Required only when connecting to the IDRsolutions trial and cloud subscription service
["callbackUrl"] = "http://listener.url",
["input"] = IDRCloudClient.UPLOAD,
["file"] = "path/to/input.pdf"
};
Configuration Options
The BuildVu API allows for conversion customization using a stringified JSON object with key-value pairs. These settings should be added to the parameters array. A comprehensive list of configuration options for converting PDF files to HTML or SVG is available here.
["settings"] = "{\"key\":\"value\",\"key\":\"value\"}"
Upload by URL
In addition to uploading a local file, you can provide a URL for the BuildVu Microservice to download and convert. Replace the input and file values in the parameters variable with the following settings.
["input"] = IDRCloudClient.DOWNLOAD
["url"] = "http://exampleURL/exampleFile.pdf"
Using Authentication
If you’ve deployed your own BuildVu Microservice that requires a username and password for converting PDF files to HTML or SVG, you must provide these credentials for each conversion. Pass two variables named username and password to the convert
var client = new IDRCloudClient("http://exampleURL.com/" + IDRCloudClient.BUILDVU, "username", "password");
Convert PDF to HTML using Dart
This tutorial our REST API.
Prerequisites
Before you start, ensure that you have the latest version of the Dart SDK installed. For more information, visit the Dart website. Additionally, you should install the following libraries:
Code Examples
Here is a basic code example for converting PDF files to HTML or SVG. Detailed configuration options and advanced features can be found below:
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 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 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);
}
}
Return result to a callback url
The BuildVu Microservice supports a callback URL to send the conversion status upon completion. Using a callback URL eliminates the need to poll the service to check when the conversion is complete. The callback URL can be provided to the params map as shown below.
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’;
Configuration Options
The BuildVu API allows for conversion customization using a stringified JSON object with key-value pairs. These settings should be added to the parameters array. A comprehensive list of configuration options for converting PDF files to HTML or SVG can be found here.
final settings = {
"key": "value",
"key": "value",
};
final settingsJson = convert.jsonEncode(settings);
final request = http.MultipartRequest(‘POST’, Uri.parse(apiUrl));
request.fields[‘settings’] = settingsJson;
Upload by URL
In addition to uploading a local file, you can provide a URL that the BuildVu Microservice will download and convert. Replace the input and file values in the parameters variable with the following configuration.
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’);
}
}
Using Authentication
If the BuildVu Microservice requires authentication, you need to provide a username and password. Pass these credentials by including two variables named `username` and `password` in the `convert` method as shown below.
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 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’);
}
We have other articles aimed at helping you with all things PDF, you can find them here.
BuildVu allows you to
View PDF files in a Web app |
Convert PDF documents to HTML5 |
Parse PDF documents as HTML |