Convert HTML to Image - Cloud SDKs Summary A widespread use case for Aspose.HTML Cloud functions is file processing and converting. This article explains in a set of code examples how to convert HTML to Image file formats such as JPG, PNG, GIF, TIFF, and BMP. We will consider various scenarios of HTML to Image conversion: from storage to storage, from a local file system to a local drive, and from the Web to the local file system.
This article explains in a set of code examples how to convert an HTML document to JPEG , PNG , GIF , TIFF or BMP formats using Aspose.HTML Cloud SDKs and REST API calls.
Examples of HTML to Image Conversion Aspose.HTML Cloud SDK allows you to fetch an HTML document from 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 Image formats for different cases. These examples show how to use available SDKs and REST API for conversion operations.
Example 1. Convert a local HTML file to JPEG and save the result to local pathJPEG is one of the most commonly used image formats. Its uniqueness is the controlled loss of quality during compression. Therefore, it is widely used to store and send graphic content (photos, scanned copies, digitized images) over the Internet.
C# The following example demonstrates the simplest way to convert HTML to JPEG C# language applying. Local HTML converted to JPEG 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 JPEG
var result = await api . ConvertAsync ( "test.html" , "test.jpeg" );
Java The following example demonstrates how to convert HTML to JPEG java language applying. Local HTML converted to JPEG 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.jpeg" );
OperationResult result = api . convert ( builder );
C++ The following example demonstrates how to convert HTML to JPEG C++ language applying. Local HTML converted to JPEG 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.jpeg" ;
//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 JPEG Python language applying. Local HTML converted to JPEG 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.jpeg" )
except ApiException as ex :
print ( "Exception" )
print ( "Info: " + str ( ex ))
raise ex
PHP The following example demonstrates how to convert HTML to JPEG PHP language applying. Local HTML converted to JPEG 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.jpeg' ;
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 JPEG Ruby language applying. Local HTML converted to JPEG 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.jpeg" # 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 JPEG Node.js language applying. Local HTML converted to JPEG 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.jpeg" ; // {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 JPEG Swift language applying. Local HTML converted to JPEG 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 = "jpeg"
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 JPEG Java/Android applying. Local HTML converted to JPEG 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.jpeg" );
OperationResult result = api . convert ( builder );
CURL The following example demonstrates how to convert HTML to JPEG REST API applying. Local HTML converted to JPEG and saved to the local path. Take 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-jpeg" \
-d "{'InputPath': '/testpage.html', 'OutputFile': 'test.jpeg'}" \
-H "Content-Type: application/json" \
-H "Authorization:Bearer <JWT_token>"
HTML to JPEG conversion occurs with the default conversion options : the resulting JPEG document’s width and height correspond to A4, all margins have zero value.
Example 2. Convert HTML from the local file system to PNG with explicitly specified options and save it to the local pathPNG image format widely takes to transmit pictures over the network, display photos and graphics on web-pages and reserve in cloud storages. HTML to PNG conversion may be required, for example, if you want to add a web page in a PowerPoint presentation, insert it on a blog for your readers, or send it by e-mail. The example below shows how to convert HTML to PNG with explicitly specified options and save the result back to the local file system.
C# The following SDK example demonstrates how to convert HTML to PNG C# language applying. HTML is taken from the local file system, converted to PNG and saved to the local drive. 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 instance and specify options for HTML to PNG conversion
var options = new ImageConversionOptions ()
. SetHeight ( 800 )
. SetWidth ( 1000 )
. SetLeftMargin ( 10 )
. SetRightMargin ( 10 )
. SetBottomMargin ( 10 )
. SetTopMargin ( 10 );
// Convert HTML to PNG
var result = await api . ConvertAsync ( "test.html" , "test.png" , options );
Java The following example demonstrates how to convert HTML to PNG java language applying. HTML is taken from the local file system, converted to PNG 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" );
ImageConversionOptions opt = new ImageConversionOptions ()
. setWidth ( 600 )
. setHeight ( 900 )
. setTopMargin ( 20 )
. setBottomMargin ( 20 )
. setLeftMargin ( 20 )
. setRightMargin ( 20 );
JobBuilder builder = new ConverterBuilder ()
. fromLocalFile ( "input.html" )
. useOptions ( opt )
. saveToLocal ( "output.png" );
OperationResult result = api . convert ( builder );
C++ The following example demonstrates how to convert HTML to PNG C++ language applying. HTML is taken from the local file system, converted to PNG 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 = w_cur_dir + L "test.html" ;
utility :: string_t dst = w_cur_dir + L "result.png" ;
std :: shared_ptr < ConversionOptions > opts = std :: make_shared < ConversionOptions > ();
opts -> setWidth ( 800 )
-> setHeight ( 600 )
-> setLeftMargin ( 10 )
-> setRightMargin ( 10 )
-> setTopMargin ( 10 )
-> setBottomMargin ( 10 );
//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 PNG Python language applying. HTML is taken from the local file system, converted to PNG and saved to the local drive. 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' : 600 ,
'height' : 900 ,
'topmargin' : 20 ,
'bottommargin' : 20 ,
'leftmargin' : 20 ,
'rightmargin' : 20
}
try :
res = html_api . convertApi . convert_local_to_local ( input_file = "test.html" , output_file = "test.png" , options = options )
except ApiException as ex :
print ( "Exception" )
print ( "Info: " + str ( ex ))
raise ex
PHP The following example demonstrates how to convert HTML to PNG PHP language applying. HTML is taken from the local file system, converted to PNG and saved to the local file. 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.png' ;
$options = [
'width' => 800 ,
'height' => 600 ,
'left_margin' => 20 ,
'right_margin' => 20 ,
'top_margin' => 20 ,
'bottom_margin' => 20
];
try {
//Request to server Api
$result = $api_html -> convertLocalToLocal ( $src , $dst , $options );
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 PNG Ruby language applying. HTML is taken from the local file system, converted to PNG and saved to the local drive. 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 | Source file.
dst = "test.png" # String | Result file.
opts = {
width : 700 , # Float | Resulting image width in pixels.
height : 1000 , # Float | Resulting image height in pixels.
left_margin : 40 , # Float | Left resulting image margin in pixels.
right_margin : 40 , # Float | Right resulting image margin in pixels.
top_margin : 50 , # Float | Top resulting image margin in pixels.
bottom_margin : 50 # Float | Bottom resulting image margin in pixels.
}
begin
#Convert the HTML file 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 PNG Node.js language applying. HTML is taken from the local file system, converted to PNG and saved to the local file.
// 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.png" ; // {String} Result document.
var opts = {
'width' : 600 ,
'height' : 800 ,
'leftMargin' : 10 ,
'rightMargin' : 20 ,
'topMargin' : 30 ,
'bottomMargin' : 40
};
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 PNG Swift language applying. HTML is taken from the local file system, converted to PNG and saved to the local drive. 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 = "png"
let src = url ( forResource : fileName ). absoluteString
let options = Options ( width : 800 , height : 600 , leftMargin : 20 ,
rightMargin : 20 , topMargin : 20 , bottomMargin : 20 )
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 PNG Java/Android applying. HTML is taken from the local file system, converted to PNG 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" );
ImageConversionOptions opt = new ImageConversionOptions ()
. setWidth ( 600 )
. setHeight ( 900 )
. setTopMargin ( 20 )
. setBottomMargin ( 20 )
. setLeftMargin ( 20 )
. setRightMargin ( 20 );
JobBuilder builder = new ConverterBuilder ()
. fromLocalFile ( "input.html" )
. useOptions ( opt )
. saveToLocal ( "output.png" );
OperationResult result = api . convert ( builder );
CURL The following example demonstrates how to convert HTML to PNG using REST API. Local HTML converted to PNG and saved to the local file system.
Please take a few steps:
Upload 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-png" \
-d "{'InputPath': '/testpage.html', 'OutputFile': 'test.png', '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 GIF 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 GIF with the default conversion parameters.
C# The following example shows how to convert HTML to GIF C# language applying. HTML is taken from the Web, converted to GIF 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 GIF using ConvertUrlAsync() method
var result = await api . ConvertUrlAsync ( "https://example.com" , "test.gif" );
Java The following example shows how to convert HTML to GIF java language applying. HTML is taken from the Web, converted to GIF 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.gif" );
OperationResult result = api . convert ( builder );
C++ The following example demonstrates how to convert HTML to GIF C++ language applying. HTML is taken from the Web, converted to GIF 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.gif" ;
//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 GIF Python language applying. HTML is taken from the Web, converted to GIF 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.gif" )
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 GIF PHP language applying. HTML is taken from the Web, converted to GIF 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.gif' ;
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 GIF Ruby language applying. HTML is taken from the Web, converted to GIF 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.gif" # 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 GIF Node.js language applying. HTML is taken from the Web, converted to GIF 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.gif" ; // {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 GIF Swift language applying. HTML is taken from the Web, converted to GIF 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 = "gif"
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 GIF Java/Android applying. HTML is taken from the Web, converted to GIF 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.gif" );
OperationResult result = api . convert ( builder );
CURL The following example demonstrates how to convert HTML to GIF using REST API. HTML is taken from the Web, converted to GIF and saved to the local file system.
Please take a few 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-gif" \
-d "{'InputPath': 'https://example.com', 'OutputFile': 'test.gif'}" \
-H "Content-Type: application/json" \
-H "Authorization:Bearer <JWT_token>"
HTML to GIF conversion occurs with the default conversion options : the resulting GIF document’s width and height correspond to A4, all margins have zero value.
Test HTML to GIF conversion online Insert URL to the text field. Press “Convert” button.
Example 4. Convert HTML to JPEG inside cloud storageAspose.HTML Cloud allows you to get an HTML file from your cloud storage and save conversion result back to cloud storage.
C# The following example shows how to convert HTML to JPEG C# language applying. HTML file is located in cloud storage, converted to JPEG and saved back to the 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 JPEG
var builder = new ConverterBuilder ()
. FromStorageFile ( "/test.html" )
. ToStorageFile ( "/test.jpeg" );
var result = await api . ConvertAsync ( builder );
Java The following example shows how to convert HTML to JPEG java language applying. HTML file is located in cloud storage, converted to JPEG and saved back to the 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.jpeg" );
OperationResult result = api . convert ( builder );
C++ The following example demonstrates how to convert HTML to JPEG C++ language applying. HTML file is located in cloud storage, converted to JPEG and saved back to the 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.jpeg" ;
//Conversion
auto result = api -> convertStorageToStorage ( src , dst );
Python The following example shows how to convert HTML to JPEG Python language applying. HTML file is located in cloud storage, converted to JPEG and saved back to the 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.jpeg" ,
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 JPEG PHP language applying. HTML file is located in cloud storage, converted to JPEG and saved back to the 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.jpeg' ;
$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 JPEG Ruby language applying. HTML file is located in cloud storage, converted to JPEG and saved back to the 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.jpeg" # 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 JPEG Node.js language applying. HTML file is located in cloud storage, converted to JPEG and saved back to the 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.jpeg" ; // {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 JPEG Swift language applying. HTML file is located in cloud storage, converted to JPEG and saved back to the 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.jpeg"
let expectation = self . expectation ( description : "testConvert to jpeg" )
HtmlAPI . convertStorageToStorage ( src : src , dst : dst , storage : nil , options : nil ) { ( data , error ) in
guard error == nil else {
XCTFail ( "Error convert html to jpeg. 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 JPEG Java/Android applying. HTML file is located in cloud storage, converted to JPEG and saved back to the 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.jpeg" );
OperationResult result = api . convert ( builder );
CURL The following example demonstrates how to convert HTML to JPEG using REST API. HTML file is located in a cloud storage, converted to JPEG and saved back to the cloud storage.
curl -X POST -v \
"https://api.aspose.cloud/v4.0/html/conversion/html-jpeg" \
-d "{'InputPath': '/test.html', 'OutputFile': '/test.jpeg'}" \
-H "Content-Type: application/json" \
-H "Authorization:Bearer <JWT_token>"