Convert HTML to PDF - Cloud SDKs Summary Aspose.HTML Cloud v4.0 provides the simplest API to convert HTML documents to PDF format with high quality, easy and fast. HTML files are frequently used to create, edit, or communicate a lot of information. HTML to PDF conversion is often required to establish limited access to documents editing or copying, to produce official documentation, or send some information, for example, by email.
The article explains in a set of Aspose.HTML Cloud SDKs and REST API examples how to convert HTML to PDF. We will consider various scenarios of HTML to PDF conversion: from storage to storage, local file to the local file system and from the Web to a local file system.
Examples of HTML to PDF Conversion A widespread use case for Aspose.HTML Cloud functions is file processing and converting. Aspose.HTML Cloud allows you to fetch an HTML document from a storage location by its name, from a URL or a local file on your drive, convert it to a specified format and save it to the storage or a local drive. The following code examples demonstrate how to convert HTML to PDF for different cases using available SDKs and REST API. A family of SDKs is available to help developers speed up their development, including C#, Java, C++, Python, PHP, Ruby, Swift, Java/Android, Node.js, etc.
Example 1. Convert a local HTML file to PDF and save the result to local path
C# The following example demonstrates the simplest way to convert HTML to PDF C# language applying. Local HTML converted to PDF and saved to the local path. You can download the C# SDK from the GitHub repository
.
// Initialize SDK API
var api = new HtmlApi ( "CLIENT_ID" , "CLIENT_SECRET" ). ConvertApi ;
// Convert HTML to PDF
var result = await api . ConvertAsync ( "test.html" , "test.pdf" );
Java The following example demonstrates how to convert HTML to PDF java language applying. Local HTML converted to PDF and saved to the local path. You can download the java SDK from the GitHub repository
.
Configuration . setBasePath ( "https://api.aspose.cloud" );
Configuration . setAuthPath ( "https://api.aspose.cloud/connect/token" );
HtmlApi api = new HtmlApi ( "CLIENT_ID" , "CLIENT_SECRET" );
JobBuilder builder = new ConverterBuilder ()
. fromLocalFile ( "input.html" )
. saveToLocal ( "output.pdf" );
OperationResult result = api . convert ( builder );
C++ The following example demonstrates how to convert HTML to PDF C++ language applying. Local HTML converted to PDF and saved to the local path.
// Get current directory
std :: string cur_dir ( argv [ 0 ]);
int pos = cur_dir . find_last_of ( "/ \\ " );
cur_dir = cur_dir . substr ( 0 , pos + 1 ); // Include the last slash
std :: wstring w_cur_dir ( cur_dir . begin (), cur_dir . end ());
const utility :: string_t clientId = L "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ;
const utility :: string_t clientSecret = L "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ;
const utility :: string_t basePath = L "https://api.aspose.cloud/v4.0" ;
const utility :: string_t authPath = L "https://api.aspose.cloud/connect/token" ;
// Create configuration for authorization
std :: shared_ptr < ApiConfiguration > apiConfig ( new ApiConfiguration ( clientId , clientSecret , basePath , authPath ));
// Create client from configuration
std :: shared_ptr < ApiClient > apiClient ( new ApiClient ( apiConfig ));
// Create ConversionApi
std :: shared_ptr < ConversionApi > api = std :: make_shared < ConversionApi > ( apiClient );
// File name for conversion
utility :: string_t src = w_cur_dir + L "test.html" ;
utility :: string_t dst = w_cur_dir + L "result.pdf" ;
//Conversion
auto result = api -> convertLocalToLocal ( src , dst );
// Check the result file
auto re = result -> getFile ();
std :: ifstream f ( re . c_str ());
if ( ! f . good ())
{
throw std :: runtime_error ( "Conversion failed" );
}
Python The following example demonstrates how to convert HTML to PDF Python language applying. Local HTML converted to PDF and saved to the local path. You can download the Python SDK from the GitHub repository
.
from asposehtmlcloud.configuration import Configuration
from asposehtmlcloud.api.html_api import HtmlApi
from asposehtmlcloud.api_client import ApiClient as Client
from asposehtmlcloud.rest import ApiException
configuration = Configuration ( apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
appSid = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
basePath = "https://api.aspose.cloud/v4.0" ,
authPath = "https://api.aspose.cloud/connect/token" ,
debug = True )
client = Client ( configuration )
html_api = HtmlApi ( client )
try :
res = html_api . convertApi . convert_local_to_local ( input_file = "test.html" , output_file = "test.pdf" )
except ApiException as ex :
print ( "Exception" )
print ( "Info: " + str ( ex ))
raise ex
PHP The following example demonstrates how to convert HTML to PDF PHP language applying. Local HTML converted to PDF and saved to the local path. You can download the PHP SDK from the GitHub repository
<? php
require_once ( __DIR__ . '/vendor/autoload.php' );
$conf = array (
"basePath" => "https://api.aspose.cloud/v4.0" ,
"authPath" => "https://api.aspose.cloud/connect/token" ,
"apiKey" => "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
"appSID" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
"defaultUserAgent" => "Webkit"
);
$api_html = new Client\Invoker\Api\HtmlApi ( $conf );
$src = 'input.html' ;
$dst = 'output.pdf' ;
try {
//Request to server Api
$result = $api_html -> convertLocalToLocal ( $src , $dst );
print_r ( $result );
} catch ( Exception $e ) {
echo 'Exception when calling HtmlApi->convertLocalToLocal: ' , $e -> getMessage (), PHP_EOL ;
}
?>
Ruby The following example demonstrates how to convert HTML to PDF Ruby language applying. Local HTML converted to PDF and saved to the local path. You can download the Ruby SDK from the GitHub repository
.
# load the gem
require 'aspose_html_cloud'
# Get keys from aspose site.
# There is free quota available.
# For more details, see https://purchase.aspose.cloud/pricing
CONFIG = {
"basePath" :"https://api.aspose.cloud/v4.0" ,
"authPath" :"https://api.aspose.cloud/connect/token" ,
"apiKey" :"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
"appSID" :"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
"debug" :true
}
api_instance = AsposeHtml :: HtmlApi . new CONFIG
src = "test.html" # String | Full path to the input file.
dst = "test.pdf" # String | Full path to the result.
begin
#Convert the document from the local file and save result to the local file.
result = api_instance . convert_local_to_local ( src , dst )
p result
rescue AsposeHtml :: ApiError => e
puts "Exception when calling api_instance.convert_local_to_local: #{ e } "
end
Node.js The following example demonstrates how to convert HTML to PDF Node.js language applying. Local HTML converted to PDF and saved to the local path.
// Get keys from aspose site.
// There is free quota available.
// For more details, see https://purchase.aspose.cloud/pricing
var conf = {
"basePath" : "https://api.aspose.cloud/v4.0" ,
"authPath" : "https://api.aspose.cloud/connect/token" ,
"apiKey" : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
"appSID" : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
"defaultUserAgent" : "NodeJsWebkit"
};
var api = require ( '@asposecloud/aspose-html-cloud' );
// Create Conversion Api object
var conversionApi = new api . ConversionApi ( conf );
var src = "/path/to/src/test.html" ; // {String} Source document.
var dst = "/path/to/dst/test.pdf" ; // {String} Result document.
var opts = null ;
var callback = function ( error , data , response ) {
if ( error ) {
console . error ( error );
} else {
console . log ( data );
}
};
conversionApi . convertLocalToLocal ( src , dst , opts , callback );
Swift The following example demonstrates how to convert HTML to PDF Swift language applying. Local HTML converted to PDF and saved to the local path. You can download the Swift SDK from the GitHub repository
.
import Alamofire
import Foundation
import XCTest
import AsposeHtmlCloud
static let fm = FileManager . default
let resourceDir = fm . homeDirectoryForCurrentUser . appendingPathComponent ( "Documents/Aspose.HTML.Cloud.SDK.Swift/Tests/AsposeHtmlCloudTests/Resources" )
let resultDir = fm . homeDirectoryForCurrentUser . appendingPathComponent ( "Documents/Aspose.HTML.Cloud.SDK.Swift/Tests/AsposeHtmlCloudTests/TestResult" )
func url ( forResource fileName : String ) -> URL {
return resourceDir . appendingPathComponent ( fileName )
}
func fileExist ( name : String ) -> Bool {
return FileManager . default . fileExists ( atPath : name )
}
ClientAPI . setConfig (
basePath : "https://api.aspose.cloud/v4.0" ,
authPath : "https://api.aspose.cloud/connect/token" ,
apiKey : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
appSID : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
debugging : true
)
let fileName = "test.html"
let format = "pdf"
let src = url ( forResource : fileName ). absoluteString
let expectation = self . expectation ( description : "testConvert to \( format ) " )
let dst = resultDir . appendingPathComponent ( "Output. \( format ) " ). absoluteString
HtmlAPI . convertLocalToLocal ( src : src , dst : dst , options : nil ) { ( data , error ) in
guard error == nil else {
XCTFail ( "Error convert html to \( format ) ). Error= \( error !. localizedDescription ) " )
return
}
let resultPath = data !. file !
XCTAssertTrue ( fileExist ( name : resultPath ))
expectation . fulfill ()
}
self . waitForExpectations ( timeout : 100.0 , handler : nil )
Java/Android The following example demonstrates how to convert HTML to PDF Java/Android applying. Local HTML converted to PDF and saved to the local path. You can download the Java/Android SDK from the GitHub repository
.
Configuration . setBasePath ( "https://api.aspose.cloud" );
Configuration . setAuthPath ( "https://api.aspose.cloud/connect/token" );
HtmlApi api = new HtmlApi ( "CLIENT_ID" , "CLIENT_SECRET" );
JobBuilder builder = new ConverterBuilder ()
. fromLocalFile ( "input.html" )
. saveToLocal ( "output.pdf" );
OperationResult result = api . convert ( builder );
CURL The following example demonstrates how to convert HTML to PDF REST API applying. Local HTML converted to PDF and saved to the local path. Follow a few required steps:
Upload a local file to storage using Storage API
. Call REST API to execute conversion (in the example below). Download conversion result back from storage using Storage API
. curl -X POST -v \
"https://api.aspose.cloud/v4.0/html/conversion/html-pdf" \
-d "{'InputPath': '/testpage.html', 'OutputFile': 'test.pdf'}" \
-H "Content-Type: application/json" \
-H "Authorization:Bearer <JWT_token>"
HTML to PDF conversion occurs with the default conversion options : the resulting PDF document’s width and height correspond to A4, all margins have zero value.
Example 2. Convert HTML from the local file system to PDF with explicitly specified options and save it to the local pathThe example below demonstrates how to convert an HTML file from the local file system to PDF with explicitly specified options and save the result back to the local path.
C# The following SDK example demonstrates how to convert HTML to PDF C# language applying. HTML is taken from the local file system, converted to PDF and saved to the local path. You can download the C# SDK from the GitHub repository
.
// Initialize SDK API
var api = new HtmlApi ( "CLIENT_ID" , "CLIENT_SECRET" ). ConvertApi ;
// Create an options object and specify options for HTML to PDF conversion
var options = new PDFConversionOptions ()
. SetHeight ( 11.7 ) // A4 format in inches
. SetWidth ( 8.3 ) // A4 format in inches
. SetLeftMargin ( 0.5 )
. SetRightMargin ( 0.5 )
. SetBottomMargin ( 0.5 )
. SetTopMargin ( 0.5 );
// Convert HTML to PDF file
var result = await api . ConvertAsync ( "test.html" , "test.pdf" , options );
Java The following example demonstrates how to convert HTML to PDF java language applying. HTML is taken from the local file system, converted to PDF and saved to the local path. You can download the java SDK from the GitHub repository
.
Configuration . setBasePath ( "https://api.aspose.cloud" );
Configuration . setAuthPath ( "https://api.aspose.cloud/connect/token" );
HtmlApi api = new HtmlApi ( "CLIENT_ID" , "CLIENT_SECRET" );
PDFConversionOptions opt_A5 = new PDFConversionOptions ()
. setWidth ( 5.8 ) // A5 format in inches
. setHeight ( 8.3 )
. setTopMargin ( 0.5 )
. setBottomMargin ( 0.5 )
. setLeftMargin ( 0.5 )
. setRightMargin ( 0.5 )
. setQuality ( 95 );
JobBuilder builder = new ConverterBuilder ()
. fromLocalFile ( "input.html" )
. useOptions ( opt_A5 )
. saveToLocal ( "output.pdf" );
OperationResult result = api . convert ( builder );
C++ The following example demonstrates how to convert HTML to PDF C++ language applying. HTML is taken from the local file system, converted to PDF and saved to the local path.
// Get current directory
std :: string cur_dir ( argv [ 0 ]);
int pos = cur_dir . find_last_of ( "/ \\ " );
cur_dir = cur_dir . substr ( 0 , pos + 1 ); // Include the last slash
std :: wstring w_cur_dir ( cur_dir . begin (), cur_dir . end ());
const utility :: string_t clientId = L "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ;
const utility :: string_t clientSecret = L "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ;
const utility :: string_t basePath = L "https://api.aspose.cloud/v4.0" ;
const utility :: string_t authPath = L "https://api.aspose.cloud/connect/token" ;
// Create configuration for authorization
std :: shared_ptr < ApiConfiguration > apiConfig ( new ApiConfiguration ( clientId , clientSecret , basePath , authPath ));
// Create client from configuration
std :: shared_ptr < ApiClient > apiClient ( new ApiClient ( apiConfig ));
// Create ConversionApi
std :: shared_ptr < ConversionApi > api = std :: make_shared < ConversionApi > ( apiClient );
// File name for conversion
utility :: string_t src = w_cur_dir + L "test.html" ;
utility :: string_t dst = w_cur_dir + L "result.pdf" ;
std :: shared_ptr < ConversionOptions > opts = std :: make_shared < ConversionOptions > ();
opts -> setWidth ( 8.3 )
-> setHeight ( 11.7 )
-> setLeftMargin ( 0.2 )
-> setRightMargin ( 0.2 )
-> setTopMargin ( 0.2 )
-> setBottomMargin ( 0.2 );
//Conversion
auto result = api -> convertLocalToLocal ( src , dst , opts );
// Check the result file
auto re = result -> getFile ();
std :: ifstream f ( re . c_str ());
if ( ! f . good ())
{
throw std :: runtime_error ( "Conversion failed" );
}
Python The following example demonstrates how to convert HTML to PDF Python language applying. HTML is taken from the local file system, converted to PDF and saved to the local path. You can download the Python SDK from the GitHub repository
.
from asposehtmlcloud.configuration import Configuration
from asposehtmlcloud.api.html_api import HtmlApi
from asposehtmlcloud.api_client import ApiClient as Client
from asposehtmlcloud.rest import ApiException
configuration = Configuration ( apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
appSid = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
basePath = "https://api.aspose.cloud/v4.0" ,
authPath = "https://api.aspose.cloud/connect/token" ,
debug = True )
client = Client ( configuration )
html_api = HtmlApi ( client )
options = {
'width' : 8.3 ,
'height' : 11.7 ,
'topmargin' : 0.2 ,
'bottommargin' : 0.2 ,
'leftmargin' : 0.2 ,
'rightmargin' : 0.2 ,
'jpegquality' : 95
}
try :
res = html_api . convertApi . convert_local_to_local ( input_file = "test.html" , output_file = "test.pdf" , options = options )
except ApiException as ex :
print ( "Exception" )
print ( "Info: " + str ( ex ))
raise ex
PHP The following example demonstrates how to convert HTML to PDF PHP language applying. HTML is taken from the local file system, converted to PDF and saved to the local path. You can download the PHP SDK from the GitHub repository
<? php
require_once ( __DIR__ . '/vendor/autoload.php' );
$conf = array (
"basePath" => "https://api.aspose.cloud/v4.0" ,
"authPath" => "https://api.aspose.cloud/connect/token" ,
"apiKey" => "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
"appSID" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
"defaultUserAgent" => "Webkit"
);
$api_html = new Client\Invoker\Api\HtmlApi ( $conf );
$src = 'input.html' ;
$dst = 'output.pdf' ;
$options_a4 = [
'width' => 8.3 ,
'height' => 11.7 ,
'left_margin' => 0.2 ,
'right_margin' => 0.2 ,
'top_margin' => 0.2 ,
'bottom_margin' => 0.2
];
try {
//Request to server Api
$result = $api_html -> convertLocalToLocal ( $src , $dst , $options_a4 );
print_r ( $result );
} catch ( Exception $e ) {
echo 'Exception when calling HtmlApi->convertLocalToLocal: ' , $e -> getMessage (), PHP_EOL ;
}
?>
Ruby The following example demonstrates how to convert HTML to PDF Ruby language applying. HTML is taken from the local file system, converted to PDF and saved to the local path. You can download the Ruby SDK from the GitHub repository
.
# load the gem
require 'aspose_html_cloud'
# Get keys from aspose site.
# There is free quota available.
# For more details, see https://purchase.aspose.cloud/pricing
CONFIG = {
"basePath" :"https://api.aspose.cloud/v4.0" ,
"authPath" :"https://api.aspose.cloud/connect/token" ,
"apiKey" :"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
"appSID" :"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
"debug" :true
}
api_instance = AsposeHtml :: HtmlApi . new CONFIG
src = "test.html" # String | Full path to the input file.
dst = "test.pdf" # String | Full path to the result.
opts = {
width : 8 . 3 , # Float | Resulting document width in inches.
height : 11 . 7 , # Float | Resulting document height in inches.
left_margin : 0 . 2 , # Float | Left resulting document margin in inches.
right_margin : 0 . 2 , # Float | Right resulting document margin in inches.
top_margin : 0 . 2 , # Float | Top resulting document margin in inches.
bottom_margin : 0 . 2 # Float | Bottom resulting document margin in inches.
}
begin
#Convert the document from the local file and save result to the local file.
result = api_instance . convert_local_to_local ( src , dst , opts )
p result
rescue AsposeHtml :: ApiError => e
puts "Exception when calling api_instance.convert_local_to_local: #{ e } "
end
Node.js The following example demonstrates how to convert HTML to PDF Node.js language applying. HTML is taken from the local file system, converted to PDF and saved to the local path.
// Get keys from aspose site.
// There is free quota available.
// For more details, see https://purchase.aspose.cloud/pricing
var conf = {
"basePath" : "https://api.aspose.cloud/v4.0" ,
"authPath" : "https://api.aspose.cloud/connect/token" ,
"apiKey" : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
"appSID" : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
"defaultUserAgent" : "NodeJsWebkit"
};
var api = require ( '@asposecloud/aspose-html-cloud' );
// Create Conversion Api object
var conversionApi = new api . ConversionApi ( conf );
var src = "/path/to/src/test.html" ; // {String} Source document.
var dst = "/path/to/dst/test.pdf" ; // {String} Result document.
var opts = {
'width' : 8.3 ,
'height' : 11.7 ,
'leftMargin' : 0.2 ,
'rightMargin' : 0.2 ,
'topMargin' : 0.2 ,
'bottomMargin' : 0.2
};
var callback = function ( error , data , response ) {
if ( error ) {
console . error ( error );
} else {
console . log ( data );
}
};
conversionApi . convertLocalToLocal ( src , dst , opts , callback );
Swift The following example demonstrates how to convert HTML to PDF Swift language applying. HTML is taken from the local file system, converted to PDF and saved to the local path. You can download the Swift SDK from the GitHub repository
.
import Alamofire
import Foundation
import XCTest
import AsposeHtmlCloud
static let fm = FileManager . default
let resourceDir = fm . homeDirectoryForCurrentUser . appendingPathComponent ( "Documents/Aspose.HTML.Cloud.SDK.Swift/Tests/AsposeHtmlCloudTests/Resources" )
let resultDir = fm . homeDirectoryForCurrentUser . appendingPathComponent ( "Documents/Aspose.HTML.Cloud.SDK.Swift/Tests/AsposeHtmlCloudTests/TestResult" )
func url ( forResource fileName : String ) -> URL {
return resourceDir . appendingPathComponent ( fileName )
}
func fileExist ( name : String ) -> Bool {
return FileManager . default . fileExists ( atPath : name )
}
ClientAPI . setConfig (
basePath : "https://api.aspose.cloud/v4.0" ,
authPath : "https://api.aspose.cloud/connect/token" ,
apiKey : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
appSID : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
debugging : true
)
let fileName = "test.html"
let format = "pdf"
let src = url ( forResource : fileName ). absoluteString
let options = Options ( width : 8.3 , height : 11.7 , leftMargin : 0.2 ,
rightMargin : 0.2 , topMargin : 0.2 , bottomMargin : 0.2 )
let expectation = self . expectation ( description : "testConvert to \( format ) " )
let dst = resultDir . appendingPathComponent ( "Output. \( format ) " ). absoluteString
HtmlAPI . convertLocalToLocal ( src : src , dst : dst , options : options ) { ( data , error ) in
guard error == nil else {
XCTFail ( "Error convert html to \( format ) ). Error= \( error !. localizedDescription ) " )
return
}
let resultPath = data !. file !
XCTAssertTrue ( fileExist ( name : resultPath ))
expectation . fulfill ()
}
self . waitForExpectations ( timeout : 100.0 , handler : nil )
Java/Android The following example demonstrates how to convert HTML to PDF Java/Android applying. HTML is taken from the local file system, converted to PDF and saved to the local path. You can download the Java/Android SDK from the GitHub repository
.
Configuration . setBasePath ( "https://api.aspose.cloud" );
Configuration . setAuthPath ( "https://api.aspose.cloud/connect/token" );
HtmlApi api = new HtmlApi ( "CLIENT_ID" , "CLIENT_SECRET" );
PDFConversionOptions opt_A5 = new PDFConversionOptions ()
. setWidth ( 5.8 )
. setHeight ( 8.3 )
. setTopMargin ( 0.5 )
. setBottomMargin ( 0.5 )
. setLeftMargin ( 0.5 )
. setRightMargin ( 0.5 )
. setQuality ( 95 );
JobBuilder builder = new ConverterBuilder ()
. fromLocalFile ( "input.html" )
. useOptions ( opt_A5 )
. saveToLocal ( "output.pdf" );
OperationResult result = api . convert ( builder );
CURL The following example demonstrates how to convert HTML to PDF using REST API. Local HTML converted to PDF and saved to the local file system. Follow a few required steps:
Upload a local file to storage using Storage API
. Call REST API to execute conversion (in the example below). Download conversion result back from storage using Storage API
. curl -X POST -v \
"https://api.aspose.cloud/v4.0/html/conversion/html-pdf" \
-d "{'InputPath': '/testpage.html', 'OutputFile': 'test.pdf', 'Options': {'Width':1000, 'Height': 800, 'LeftMargin': 10, 'RightMargin': 10, 'TopMargin': 10, 'BottomMargin': 10}}" \
-H "Content-Type: application/json" \
-H "Authorization: bearer <token>"
Example 3. Convert a Web page to PDF and save the result to the local file systemAspose.HTML Cloud allows you to get an HTML page from the web by its URL, convert it to another format and save into the local file system. The example below demonstrates how to convert HTML to PDF with the default conversion parameters.
C# The following example shows how to convert HTML to PDF C# language applying. HTML is taken from the Web, converted to PDF and saved to the local file system. You can download the C# SDK from the GitHub repository
.
// Initialize SDK API
var api = new HtmlApi ( "CLIENT_ID" , "CLIENT_SECRET" ). ConvertApi ;
// Convert HTML to PDF using ConvertUrlAsync() method
var result = await api . ConvertUrlAsync ( "https://example.com" , "test.pdf" );
Java The following example shows how to convert HTML to PDF java language applying. HTML is taken from the Web, converted to PDF and saved to the local file system. You can download the java SDK from the GitHub repository
.
Configuration . setBasePath ( "https://api.aspose.cloud" );
Configuration . setAuthPath ( "https://api.aspose.cloud/connect/token" );
HtmlApi api = new HtmlApi ( "CLIENT_ID" , "CLIENT_SECRET" );
JobBuilder builder = new ConverterBuilder ()
. fromUrl ( "https://example.com" )
. saveToLocal ( "output.pdf" );
OperationResult result = api . convert ( builder );
C++ The following example demonstrates how to convert HTML to PDF C++ language applying. HTML is taken from the Web, converted to PDF and saved to the local file system.
// Get current directory
std :: string cur_dir ( argv [ 0 ]);
int pos = cur_dir . find_last_of ( "/ \\ " );
cur_dir = cur_dir . substr ( 0 , pos + 1 ); // Include the last slash
std :: wstring w_cur_dir ( cur_dir . begin (), cur_dir . end ());
const utility :: string_t clientId = L "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ;
const utility :: string_t clientSecret = L "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ;
const utility :: string_t basePath = L "https://api.aspose.cloud/v4.0" ;
const utility :: string_t authPath = L "https://api.aspose.cloud/connect/token" ;
// Create configuration for authorization
std :: shared_ptr < ApiConfiguration > apiConfig ( new ApiConfiguration ( clientId , clientSecret , basePath , authPath ));
// Create client from configuration
std :: shared_ptr < ApiClient > apiClient ( new ApiClient ( apiConfig ));
// Create ConversionApi
std :: shared_ptr < ConversionApi > api = std :: make_shared < ConversionApi > ( apiClient );
// File name for conversion
utility :: string_t src = L "https://example.com" ;
utility :: string_t dst = w_cur_dir + L "result.pdf" ;
//Conversion
auto result = api -> convertUrlToLocal ( src , dst );
// Check the result file
auto re = result -> getFile ();
std :: ifstream f ( re . c_str ());
if ( ! f . good ())
{
throw std :: runtime_error ( "Conversion failed" );
}
Python The following example shows how to convert HTML to PDF Python language applying. HTML is taken from the Web, converted to PDF and saved to the local file system. You can download the Python SDK from the GitHub repository
.
import os
from asposehtmlcloud.configuration import Configuration
from asposehtmlcloud.api.html_api import HtmlApi
from asposehtmlcloud.api_client import ApiClient as Client
from asposehtmlcloud.rest import ApiException
# Get keys from aspose site.
# There is free quota available.
# For more details, see https://purchase.aspose.cloud/pricing
configuration = Configuration ( apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
appSid = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
basePath = "https://api.aspose.cloud/v4.0" ,
authPath = "https://api.aspose.cloud/connect/token" ,
debug = True )
client = Client ( configuration )
html_api = HtmlApi ( client )
try :
res = html_api . convert_url_to_local ( input_file = "https://example.com" , output_file = "result.pdf" )
if not os . path . exists ( res . file ):
print ( 'conversion failed' )
except ApiException as ex :
print ( "Exception" )
print ( "Info: " + str ( ex ))
raise ex
PHP The following example demonstrates how to convert HTML to PDF PHP language applying. HTML is taken from the Web, converted to PDF and saved to the local file system. You can download the PHP SDK from the GitHub repository
.
<? php
require_once ( __DIR__ . '/vendor/autoload.php' );
$conf = array (
"basePath" => "https://api.aspose.cloud/v4.0" ,
"authPath" => "https://api.aspose.cloud/connect/token" ,
"apiKey" => "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
"appSID" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
"defaultUserAgent" => "Webkit"
);
$api_html = new Client\Invoker\Api\HtmlApi ( $conf );
$src = 'https://example.com' ;
$dst = 'output.pdf' ;
try {
//Request to server Api
$result = $api_html -> convertUrlToLocal ( $src , $dst );
print_r ( $result );
} catch ( Exception $e ) {
echo 'Exception when calling HtmlApi->convertUrlToLocal: ' , $e -> getMessage (), PHP_EOL ;
}
?>
Ruby The following example shows how to convert HTML to PDF Ruby language applying. HTML is taken from the Web, converted to PDF and saved to the local file system. You can download the Ruby SDK from the GitHub repository
.
# load the gem
require 'aspose_html_cloud'
# Get keys from aspose site.
# There is free quota available.
# For more details, see https://purchase.aspose.cloud/pricing
CONFIG = {
"basePath" :"https://api.aspose.cloud/v4.0" ,
"authPath" :"https://api.aspose.cloud/connect/token" ,
"apiKey" :"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
"appSID" :"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
"debug" :true
}
api_instance = AsposeHtml :: HtmlApi . new CONFIG
src = "https://example.com" # String | Input url.
dst = "test.pdf" # String | Result file.
begin
#Convert the HTML file from the web and save result to the local file.
result = api_instance . convert_url_to_local ( src , dst )
p result
rescue AsposeHtml :: ApiError => e
puts "Exception when calling api_instance.convert_url_to_local: #{ e } "
end
Node.js The following example shows how to convert HTML to PDF Node.js language applying. HTML is taken from the Web, converted to PDF and saved to the local file system.
// Get keys from aspose site.
// There is free quota available.
// For more details, see https://purchase.aspose.cloud/pricing
var conf = {
"basePath" : "https://api.aspose.cloud/v4.0" ,
"authPath" : "https://api.aspose.cloud/connect/token" ,
"apiKey" : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
"appSID" : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
"defaultUserAgent" : "NodeJsWebkit"
};
var api = require ( '@asposecloud/aspose-html-cloud' );
// Create Conversion Api object
var conversionApi = new api . ConversionApi ( conf );
var src = "https://example.com" ; // {String} Url for conversion.
var dst = "/path/to/dst/test.pdf" ; // {String} Result document.
var opts = null ;
var callback = function ( error , data , response ) {
if ( error ) {
console . error ( error );
} else {
console . log ( data );
}
};
conversionApi . convertUrlToLocal ( src , dst , opts , callback );
Swift The following example shows how to convert HTML to PDF Swift language applying. HTML is taken from the Web, converted to PDF and saved to the local file system. You can download the Swift SDK from the GitHub repository
.
import Alamofire
import Foundation
import XCTest
import AsposeHtmlCloud
static let fm = FileManager . default
let resultDir = fm . homeDirectoryForCurrentUser . appendingPathComponent ( "Documents/Aspose.HTML.Cloud.SDK.Swift/Tests/AsposeHtmlCloudTests/TestResult" )
func fileExist ( name : String ) -> Bool {
return FileManager . default . fileExists ( atPath : name )
}
ClientAPI . setConfig (
basePath : "https://api.aspose.cloud/v4.0" ,
authPath : "https://api.aspose.cloud/connect/token" ,
apiKey : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
appSID : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
debugging : true
)
let format = "pdf"
let src = "https://example.com"
let dst = resultDir . appendingPathComponent ( "Output. \( format ) " ). absoluteString
let expectation = self . expectation ( description : "testConvert to \( format ) " )
HtmlAPI . convertUrlToLocal ( src : src , dst : dst , options : nil ) { ( data , error ) in
guard error == nil else {
XCTFail ( "Error convert web site to \( format ) ). Error= \( error !. localizedDescription ) " )
return
}
let resultPath = data !. file !
XCTAssertTrue ( fileExist ( name : resultPath ))
expectation . fulfill ()
}
self . waitForExpectations ( timeout : 100.0 , handler : nil )
Java/Android The following example shows how to convert HTML to PDF Java/Android applying. HTML is taken from the Web, converted to PDF and saved to the local file system. You can download the Java/Android SDK from the GitHub repository
.
Configuration . setBasePath ( "https://api.aspose.cloud" );
Configuration . setAuthPath ( "https://api.aspose.cloud/connect/token" );
HtmlApi api = new HtmlApi ( "CLIENT_ID" , "CLIENT_SECRET" );
JobBuilder builder = new ConverterBuilder ()
. fromUrl ( "https://example.com" )
. saveToLocal ( "output.pdf" );
OperationResult result = api . convert ( builder );
CURL The following example demonstrates how to convert HTML to PDF using REST API. HTML is taken from the Web, converted to PDF and saved to the local file system. Follow a few required steps:
Call REST API to execute conversion (in the example below). Download conversion result back from storage using Storage API
. curl -X POST -v \
"https://api.aspose.cloud/v4.0/html/conversion/html-pdf" \
-d "{'InputPath': 'https://example.com', 'OutputFile': 'test.pdf'}" \
-H "Content-Type: application/json" \
-H "Authorization:Bearer <JWT_token>"
HTML to PDF conversion occurs with the default conversion options : the resulting PDF document’s width and height correspond to A4, all margins have zero value.
Test HTML to PDF conversion online Insert URL to the text field. Press “Convert” button.
Example 4. Convert HTML to PDF inside cloud storageAspose.HTML Cloud allows you to get an HTML file from your cloud storage and save the conversion result back to cloud storage.
C# The following example shows how to convert HTML to PDF C# language applying. An HTML file is located in cloud storage, converted to PDF and saved back to cloud storage. You can download the C# SDK from the GitHub repository
.
// Initialize SDK API
var api = new HtmlApi ( "CLIENT_ID" , "CLIENT_SECRET" ). ConvertApi ;
// Convert HTML to PDF
var builder = new ConverterBuilder ()
. FromStorageFile ( "/test.html" )
. ToStorageFile ( "/test.pdf" );
var result = await api . ConvertAsync ( builder );
Java The following example shows how to convert HTML to PDF java language applying. The HTML file is in cloud storage, converted to PDF and saved back to cloud storage. You can download the java SDK from the GitHub repository
.
Configuration . setBasePath ( "https://api.aspose.cloud" );
Configuration . setAuthPath ( "https://api.aspose.cloud/connect/token" );
HtmlApi api = new HtmlApi ( "CLIENT_ID" , "CLIENT_SECRET" );
JobBuilder builder = new ConverterBuilder ()
. fromStorageFile ( "input.html" )
. saveToStorage ( "output.pdf" );
OperationResult result = api . convert ( builder );
C++ The following example demonstrates how to convert HTML to PDF C++ language applying. The HTML file is in cloud storage, converted to PDF and saved back to cloud storage.
const utility :: string_t clientId = L "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ;
const utility :: string_t clientSecret = L "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ;
const utility :: string_t basePath = L "https://api.aspose.cloud/v4.0" ;
const utility :: string_t authPath = L "https://api.aspose.cloud/connect/token" ;
// Create configuration for authorization
std :: shared_ptr < ApiConfiguration > apiConfig ( new ApiConfiguration ( clientId , clientSecret , basePath , authPath ));
// Create client from configuration
std :: shared_ptr < ApiClient > apiClient ( new ApiClient ( apiConfig ));
// Create ConversionApi
std :: shared_ptr < ConversionApi > api = std :: make_shared < ConversionApi > ( apiClient );
// File name for conversion
utility :: string_t src = L "file/in/storage/index.html" ;
utility :: string_t dst = L "result/in/storage/result.pdf" ;
//Conversion
auto result = api -> convertStorageToStorage ( src , dst );
Python The following example shows how to convert HTML to PDF Python language applying. The HTML file is in cloud storage, converted to PDF and saved back to cloud storage. You can download the Python SDK from the GitHub repository
.
from asposehtmlcloud.configuration import Configuration
from asposehtmlcloud.api.html_api import HtmlApi
from asposehtmlcloud.api_client import ApiClient as Client
from asposehtmlcloud.rest import ApiException
configuration = Configuration ( apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
appSid = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
basePath = "https://api.aspose.cloud/v4.0" ,
authPath = "https://api.aspose.cloud/connect/token" ,
debug = True )
client = Client ( configuration )
html_api = HtmlApi ( client )
try :
res = html_api . convertApi . convert_storage_to_storage ( input_file = "test.html" , output_file = "test.pdf" ,
storage_name = None )
except ApiException as ex :
print ( "Exception" )
print ( "Info: " + str ( ex ))
raise ex
PHP The following example demonstrates how to convert HTML to PDF PHP language applying. The HTML file is in cloud storage, converted to PDF and saved back to cloud storage. You can download the PHP SDK from the GitHub repository
.
<? php
require_once ( __DIR__ . '/vendor/autoload.php' );
$configuration = array (
"basePath" => "https://api.aspose.cloud/v4.0" ,
"authPath" => "https://api.aspose.cloud/connect/token" ,
"apiKey" => "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
"appSID" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
"defaultUserAgent" => "Webkit"
);
$api_html = new HtmlApi ( $configuration );
$src = "FolderInStorage/test.html" ;
$dst = 'FolderInStorage/test.pdf' ;
$options = null ;
try {
$result = $api_html -> convertStorageToStorage ( $src , $dst , null , $options );
print_r ( $result );
} catch ( Exception $e ) {
echo 'Exception when calling $api_html->convertStorageToStorage: ' , $e -> getMessage (), PHP_EOL ;
}
?>
Ruby The following example shows how to convert HTML to PDF Ruby language applying. The HTML file is in cloud storage, converted to PDF and saved back to cloud storage. You can download the Ruby SDK from the GitHub repository
.
# load the gem
require 'aspose_html_cloud'
# Get keys from aspose site.
# There is free quota available.
# For more details, see https://purchase.aspose.cloud/pricing
CONFIG = {
"basePath" :"https://api.aspose.cloud/v4.0" ,
"authPath" :"https://api.aspose.cloud/connect/token" ,
"apiKey" :"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
"appSID" :"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
"debug" :true
}
api_instance = AsposeHtml :: HtmlApi . new CONFIG
src = "FolderInStorage/test.html" # String | Source file.
dst = "FolderInStorage/test.md" # String | Result file.
storage = nil
begin
#Convert the file from the storage and save result to the storage.
result = api_instance . convert_storage_to_storage ( src , dst , storage )
p result
rescue AsposeHtml :: ApiError => e
puts "Exception when calling api_instance.convert_storage_to_storage: #{ e } "
end
Node.js The following example shows how to convert HTML to PDF Node.js language applying. The HTML file is in cloud storage, converted to PDF and saved back to cloud storage.
// Get keys from aspose site.
// There is free quota available.
// For more details, see https://purchase.aspose.cloud/pricing
var conf = {
"basePath" : "https://api.aspose.cloud/v4.0" ,
"authPath" : "https://api.aspose.cloud/connect/token" ,
"apiKey" : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
"appSID" : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
"defaultUserAgent" : "NodeJsWebkit"
};
var api = require ( '@asposecloud/aspose-html-cloud' );
// Create Conversion Api object
var conversionApi = new api . ConversionApi ( conf );
var src = "FolderInStorage/test.html" ; // {String} Source document.
var dst = "FolderInStorage/test.pdf" ; // {String} Result document.
var opts = null ;
var storage = null ;
var callback = function ( error , data , response ) {
if ( error ) {
console . error ( error );
} else {
console . log ( data );
}
};
conversionApi . convertStorageToStorage ( src , dst , storage , opts , callback );
Swift The following example shows how to convert HTML to PDF Swift language applying. The HTML file is in cloud storage, converted to PDF and saved back to cloud storage. You can download the Swift SDK from the GitHub repository
.
import Alamofire
import Foundation
import XCTest
import AsposeHtmlCloud
ClientAPI . setConfig (
basePath : "https://api.aspose.cloud/v4.0" ,
authPath : "https://api.aspose.cloud/connect/token" ,
apiKey : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
appSID : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
debugging : true
)
let src = "FolderInStorage/test.html"
let dst = "FolderInStorage/test.pdf"
let expectation = self . expectation ( description : "testConvert to pdf" )
HtmlAPI . convertStorageToStorage ( src : src , dst : dst , storage : nil , options : nil ) { ( data , error ) in
guard error == nil else {
XCTFail ( "Error convert html to pdf). Error= \( error !. localizedDescription ) " )
return
}
let resultPath = data !. file !
StorageAPI . objectExists ( path : resultPath , storageName : nil , versionId : nil ) {( data , error ) in
guard error == nil else {
XCTFail ( "Error objectExists exist. Error= \( error !. localizedDescription ) " )
return
}
XCTAssertTrue ( data !. exists )
XCTAssertFalse ( data !. isFolder )
expectation . fulfill ()
}
}
self . waitForExpectations ( timeout : 100.0 , handler : nil )
Java/Android The following example shows how to convert HTML to PDF Java/Android applying. The HTML file is in cloud storage, converted to PDF and saved back to cloud storage. You can download the Java/Android SDK from the GitHub repository
.
Configuration . setBasePath ( "https://api.aspose.cloud" );
Configuration . setAuthPath ( "https://api.aspose.cloud/connect/token" );
HtmlApi api = new HtmlApi ( "CLIENT_ID" , "CLIENT_SECRET" );
JobBuilder builder = new ConverterBuilder ()
. fromStorageFile ( "input.html" )
. saveToStorage ( "output.pdf" );
OperationResult result = api . convert ( builder );
CURL The following example demonstrates how to convert HTML to PDF using REST API. HTML file is located in cloud storage, converted to PDF and saved back to cloud storage.
curl -X POST -v \
"https://api.aspose.cloud/v4.0/html/conversion/html-pdf" \
-d "{'InputPath': '/test.html', 'OutputFile': '/test.pdf'}" \
-H "Content-Type: application/json" \
-H "Authorization:Bearer <JWT_token>"