Convierta HTML a PDF usando Cloud SDK – Aspose.HTML Cloud Los archivos HTML se utilizan con frecuencia para crear, editar o comunicar mucha información. Sin embargo, hay ocasiones en las que convertir documentos HTML a PDF se vuelve imperativo. La conversión de HTML a PDF a menudo es necesaria para establecer un acceso limitado a la edición o copia de documentos, para producir documentación oficial o enviar información, por ejemplo, por correo electrónico.
Este artículo explica en un conjunto de ejemplos de Aspose.HTML Cloud SDK y REST API cómo convertir HTML a PDF. Veremos diferentes escenarios de conversión de HTML a PDF: de almacenamiento en almacenamiento, de archivo local a sistema de archivos local y de la Web a sistema de archivos local.
Conversión de HTML a PDF Un caso de uso generalizado de las funciones de Aspose.HTML Cloud es el procesamiento y conversión de archivos. Aspose.HTML Cloud le permite recuperar un documento HTML desde una ubicación de almacenamiento por su nombre, desde una URL o un archivo local en su disco, convertirlo a un formato específico y guardarlo en el almacenamiento o en el disco local. Los siguientes ejemplos de código demuestran cómo convertir HTML a PDF para diferentes casos utilizando los SDK y la API REST disponibles. Hay disponible una familia de SDK para ayudar a los desarrolladores a acelerar su desarrollo, incluidos C#, Java, C++, Python, PHP, Ruby, Swift, Java/Android, Node.js, etc. Estos SDK permiten a los desarrolladores integrar fácilmente la conversión de HTML a PDF. funcionalidad en sus aplicaciones, independientemente de la plataforma en la que se ejecuten.
Ejemplo 1. Convertir HTML a PDF con opciones de guardado predeterminadas Veamos un ejemplo de cómo convertir un archivo HTML local a PDF y guardar el resultado en una ruta local. La conversión se produce con las opciones de conversión predeterminadas.
C# El siguiente ejemplo demuestra la forma más sencilla de convertir HTML a PDF usando C#. Puede descargar el SDK de C# desde el
repositorio de GitHub .
Copy 1 // Initialize SDK API
2 var api = new HtmlApi("CLIENT_ID" , "CLIENT_SECRET" ).ConvertApi ;
3
4 // Convert HTML to PDF
5 var result = await api.ConvertAsync ("test.html" , "test.pdf" );
Java El siguiente ejemplo demuestra cómo convertir HTML a PDF usando Java. Puede descargar el SDK de Java desde el
repositorio de GitHub .
Copy 1 Configuration.setBasePath ("https://api.aspose.cloud" );
2 Configuration.setAuthPath ("https://api.aspose.cloud/connect/token" );
3
4 HtmlApi api = new HtmlApi("CLIENT_ID" , "CLIENT_SECRET" );
5
6 JobBuilder builder = new ConverterBuilder()
7 .fromLocalFile ("input.html" )
8 .saveToLocal ("output.pdf" );
9
10 OperationResult result = api.convert (builder);
C++ El siguiente ejemplo demuestra cómo convertir HTML a PDF aplicando el lenguaje C++. HTML local convertido a PDF y guardado en la ruta local.
Copy 1 // Get current directory
2 std ::string cur_dir (argv[ 0] );
3 int pos = cur_dir.find_last_of ("/\\" );
4 cur_dir = cur_dir.substr (0, pos + 1); // Include the last slash
5 std ::wstring w_cur_dir (cur_dir.begin (), cur_dir.end ());
6
7 const utility::string_t clientId = L"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ;
8 const utility::string_t clientSecret = L"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ;
9 const utility::string_t basePath = L"https://api.aspose.cloud/v4.0" ;
10 const utility::string_t authPath = L"https://api.aspose.cloud/connect/token" ;
11
12 // Create configuration for authorization
13 std ::shared_ptr< ApiConfiguration> apiConfig (new ApiConfiguration(clientId, clientSecret, basePath, authPath));
14
15 // Create client from configuration
16 std ::shared_ptr< ApiClient> apiClient (new ApiClient(apiConfig));
17
18 // Create ConversionApi
19 std ::shared_ptr< ConversionApi> api = std::make_shared< ConversionApi> (apiClient);
20
21 // File name for conversion
22 utility ::string_t src = w_cur_dir + L"test.html" ;
23 utility ::string_t dst = w_cur_dir + L"result.pdf" ;
24
25 //Conversion
26 auto result = api-> convertLocalToLocal(src, dst);
27
28 // Check the result file
29 auto re = result-> getFile();
30 std ::ifstream f (re.c_str ());
31 if (! f.good ())
32 {
33 throw std::runtime_error("Conversion failed" );
34 }
Python El siguiente ejemplo demuestra cómo convertir HTML a PDF aplicando el lenguaje Python. Puede descargar el SDK de Python desde el
repositorio de GitHub .
Copy 1 from asposehtmlcloud.configuration import Configuration
2 from asposehtmlcloud.api .html_api import HtmlApi
3 from asposehtmlcloud.api_client import ApiClient as Client
4 from asposehtmlcloud.rest import ApiException
5
6 configuration = Configuration(apiKey= "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
7 appSid= "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
8 basePath= "https://api.aspose.cloud/v4.0" ,
9 authPath= "https://api.aspose.cloud/connect/token" ,
10 debug= True)
11 client = Client(configuration)
12 html_api = HtmlApi(client)
13
14 try :
15 res = html_api.convertApi .convert_local_to_local (input_file= "test.html" , output_file= "test.pdf" )
16 except ApiException as ex:
17 print("Exception" )
18 print("Info: " + str(ex))
19 raise ex
PHP El siguiente ejemplo demuestra cómo convertir HTML a PDF usando PHP. Puede descargar el SDK de PHP desde el
repositorio de GitHub
Copy 1 <? php
2 require_once (__DIR__ . ' / vendor/ autoload.php ' );
3
4 $conf = array(
5 "basePath" => "https://api.aspose.cloud/v4.0" ,
6 "authPath" => "https://api.aspose.cloud/connect/token" ,
7 "apiKey" => "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
8 "appSID" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
9 "defaultUserAgent" => "Webkit"
10 );
11
12 $api_html = new Client\ Invoker\ Api\ HtmlApi($conf);
13
14 $src = ' input.html ' ;
15 $dst = ' output.pdf ' ;
16
17 try {
18 // Request to server Api
19 $result = $api_html-> convertLocalToLocal($src, $dst);
20 print_r($result);
21 } catch (Exception $e) {
22 echo ' Exception when calling HtmlApi-> convertLocalToLocal: ' , $e-> getMessage(), PHP_EOL;
23 }
24
25 ?>
Ruby El siguiente ejemplo demuestra cómo convertir HTML a PDF aplicando el lenguaje Ruby. Puede descargar el SDK de Ruby desde el
repositorio de GitHub .
Copy 1 # load the gem
2 require ' aspose_html_cloud'
3
4 # Get keys from aspose site.
5 # There is free quota available.
6 # For more details, see https://purchase.aspose.cloud/pricing
7
8 CONFIG = {
9 "basePath" :"https://api.aspose.cloud/v4.0" ,
10 "authPath" :"https://api.aspose.cloud/connect/token" ,
11 "apiKey" :"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
12 "appSID" :"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
13 "debug" :true
14 }
15
16 api_instance = AsposeHtml::HtmlApi.new CONFIG
17
18 src = "test.html" # String | Full path to the input file.
19 dst = "test.pdf" # String | Full path to the result.
20
21 begin
22 # Convert the document from the local file and save result to the local file.
23 result = api_instance.convert_local_to_local (src, dst)
24 p result
25 rescue AsposeHtml::ApiError => e
26 puts "Exception when calling api_instance.convert_local_to_local: #{e}"
27 end
Node.js El siguiente ejemplo demuestra cómo convertir HTML a PDF aplicando el lenguaje Node.js. HTML local convertido a PDF y guardado en la ruta local.
Copy 1 // Get keys from aspose site.
2 // There is free quota available.
3 // For more details, see https://purchase.aspose.cloud/pricing
4
5 var conf = {
6 "basePath" :"https://api.aspose.cloud/v4.0" ,
7 "authPath" :"https://api.aspose.cloud/connect/token" ,
8 "apiKey" :"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
9 "appSID" :"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
10 "defaultUserAgent" :"NodeJsWebkit"
11 };
12
13 var api = require(' @asposecloud / aspose- html- cloud' );
14
15 // Create Conversion Api object
16 var conversionApi = new api.ConversionApi (conf);
17
18 var src = "/path/to/src/test.html" ; // {String} Source document.
19 var dst = "/path/to/dst/test.pdf" ; // {String} Result document.
20 var opts = null ;
21
22 var callback = function(error, data, response) {
23 if (error) {
24 console.error (error);
25 } else {
26 console.log (data);
27 }
28 };
29
30 conversionApi.convertLocalToLocal (src, dst, opts, callback);
Swift El siguiente ejemplo demuestra cómo convertir HTML a PDF aplicando el lenguaje Swift. Puede descargar el SDK de Swift desde el
repositorio de GitHub .
Copy 1 import Alamofire
2 import Foundation
3 import XCTest
4 import AsposeHtmlCloud
5
6 static let fm = FileManager.default
7 let resourceDir = fm.homeDirectoryForCurrentUser .appendingPathComponent ("Documents/Aspose.HTML.Cloud.SDK.Swift/Tests/AsposeHtmlCloudTests/Resources" )
8 let resultDir = fm.homeDirectoryForCurrentUser .appendingPathComponent ("Documents/Aspose.HTML.Cloud.SDK.Swift/Tests/AsposeHtmlCloudTests/TestResult" )
9
10 func url (forResource fileName: String) -> URL {
11 return resourceDir.appendingPathComponent (fileName)
12 }
13
14 func fileExist (name: String) -> Bool {
15 return FileManager.default .fileExists (atPath: name)
16 }
17
18 ClientAPI.setConfig (
19 basePath: "https://api.aspose.cloud/v4.0" ,
20 authPath: "https://api.aspose.cloud/connect/token" ,
21 apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
22 appSID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
23 debugging: true
24 )
25
26 let fileName = "test.html"
27 let format = "pdf"
28 let src = url(forResource: fileName).absoluteString
29
30 let expectation = self.expectation (description: "testConvert to \(format)" )
31 let dst = resultDir.appendingPathComponent ("Output.\(format)" ).absoluteString
32 HtmlAPI.convertLocalToLocal (src: src, dst: dst, options: nil) { (data, error) in
33
34 guard error == nil else {
35 XCTFail("Error convert html to \(format)). Error=\(error!.localizedDescription)" )
36 return
37 }
38 let resultPath = data! .file !
39 XCTAssertTrue(fileExist(name: resultPath))
40 expectation.fulfill ()
41 }
42 self.waitForExpectations (timeout: 100.0 , handler: nil)
Java/Android El siguiente ejemplo demuestra cómo convertir HTML a PDF usando Java/Android. Puede descargar el SDK de Java/Android desde el
repositorio de GitHub .
Copy 1 Configuration.setBasePath ("https://api.aspose.cloud" );
2 Configuration.setAuthPath ("https://api.aspose.cloud/connect/token" );
3
4 HtmlApi api = new HtmlApi("CLIENT_ID" , "CLIENT_SECRET" );
5
6 JobBuilder builder = new ConverterBuilder()
7 .fromLocalFile ("input.html" )
8 .saveToLocal ("output.pdf" );
9
10 OperationResult result = api.convert (builder);
CURL El siguiente ejemplo demuestra cómo convertir HTML a PDF usando la API REST. Siga algunos pasos requeridos:
Cargue un archivo local al almacenamiento usando
API de almacenamiento . Llame a la API REST para ejecutar la conversión (en el ejemplo siguiente). Descargue el resultado de la conversión desde el almacenamiento usando
API de almacenamiento . Copy 1 curl - X POST - v \
2 "https://api.aspose.cloud/v4.0/html/conversion/html-pdf" \
3 - d "{'InputPath': '/testpage.html', 'OutputFile': 'test.pdf'}" \
4 - H "Content-Type: application/json" \
5 - H "Authorization:Bearer <JWT_token>"
La conversión de HTML a PDF se produce con las opciones de conversión predeterminadas : el ancho y el alto del documento PDF resultante corresponden a A4, y todos los márgenes tienen valor cero.
Ejemplo 2. Convertir HTML a PDF con opciones especificadas explícitamente El siguiente ejemplo demuestra cómo convertir un archivo HTML de un sistema de archivos local a PDF con opciones especificadas explícitamente y guardar el resultado en una ruta local.
C# El siguiente ejemplo de SDK demuestra cómo convertir HTML a PDF usando C#. El HTML se toma del sistema de archivos local, se convierte a PDF y se guarda en la ruta local. Puede descargar el SDK de C# desde el
repositorio de GitHub .
Copy 1 // Initialize SDK API
2 var api = new HtmlApi("CLIENT_ID" , "CLIENT_SECRET" ).ConvertApi ;
3
4 // Create an options object and specify options for HTML to PDF conversion
5 var options = new PDFConversionOptions()
6 .SetHeight (11.7 ) // A4 format in inches
7 .SetWidth (8.3 ) // A4 format in inches
8 .SetLeftMargin (0.5 )
9 .SetRightMargin (0.5 )
10 .SetBottomMargin (0.5 )
11 .SetTopMargin (0.5 );
12
13 // Convert HTML to PDF file
14 var result = await api.ConvertAsync ("test.html" , "test.pdf" , options);
Java El siguiente ejemplo demuestra cómo convertir HTML a PDF usando Java. El HTML se toma del sistema de archivos local, se convierte a PDF y se guarda en la ruta local. Puede descargar el SDK de Java desde el
repositorio de GitHub .
Copy 1 Configuration.setBasePath ("https://api.aspose.cloud" );
2 Configuration.setAuthPath ("https://api.aspose.cloud/connect/token" );
3
4 HtmlApi api = new HtmlApi("CLIENT_ID" , "CLIENT_SECRET" );
5
6 PDFConversionOptions opt_A5 = new PDFConversionOptions()
7 .setWidth (5.8 ) // A5 format in inches
8 .setHeight (8.3 )
9 .setTopMargin (0.5 )
10 .setBottomMargin (0.5 )
11 .setLeftMargin (0.5 )
12 .setRightMargin (0.5 )
13 .setQuality (95);
14
15 JobBuilder builder = new ConverterBuilder()
16 .fromLocalFile ("input.html" )
17 .useOptions (opt_A5)
18 .saveToLocal ("output.pdf" );
19
20 OperationResult result = api.convert (builder);
C++ El siguiente ejemplo demuestra cómo convertir HTML a PDF usando C++. El HTML se toma del sistema de archivos local, se convierte a PDF y se guarda en la ruta local.
Copy 1 // Get current directory
2 std ::string cur_dir (argv[ 0] );
3 int pos = cur_dir.find_last_of ("/\\" );
4 cur_dir = cur_dir.substr (0, pos + 1); // Include the last slash
5 std ::wstring w_cur_dir (cur_dir.begin (), cur_dir.end ());
6
7 const utility::string_t clientId = L"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ;
8 const utility::string_t clientSecret = L"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ;
9 const utility::string_t basePath = L"https://api.aspose.cloud/v4.0" ;
10 const utility::string_t authPath = L"https://api.aspose.cloud/connect/token" ;
11
12 // Create configuration for authorization
13 std ::shared_ptr< ApiConfiguration> apiConfig (new ApiConfiguration(clientId, clientSecret, basePath, authPath));
14
15 // Create client from configuration
16 std ::shared_ptr< ApiClient> apiClient (new ApiClient(apiConfig));
17
18 // Create ConversionApi
19 std ::shared_ptr< ConversionApi> api = std::make_shared< ConversionApi> (apiClient);
20
21 // File name for conversion
22 utility ::string_t src = w_cur_dir + L"test.html" ;
23 utility ::string_t dst = w_cur_dir + L"result.pdf" ;
24
25 std ::shared_ptr< ConversionOptions> opts = std::make_shared< ConversionOptions> ();
26 opts-> setWidth(8.3 )
27 -> setHeight(11.7 )
28 -> setLeftMargin(0.2 )
29 -> setRightMargin(0.2 )
30 -> setTopMargin(0.2 )
31 -> setBottomMargin(0.2 );
32
33 //Conversion
34 auto result = api-> convertLocalToLocal(src, dst, opts);
35
36 // Check the result file
37 auto re = result-> getFile();
38 std ::ifstream f (re.c_str ());
39 if (! f.good ())
40 {
41 throw std::runtime_error("Conversion failed" );
42 }
Python El siguiente ejemplo demuestra cómo convertir HTML a PDF aplicando el lenguaje Python. El HTML se toma del sistema de archivos local, se convierte a PDF y se guarda en la ruta local. Puede descargar el SDK de Python desde el
repositorio de GitHub .
Copy 1 from asposehtmlcloud.configuration import Configuration
2 from asposehtmlcloud.api .html_api import HtmlApi
3 from asposehtmlcloud.api_client import ApiClient as Client
4 from asposehtmlcloud.rest import ApiException
5
6 configuration = Configuration(apiKey= "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
7 appSid= "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
8 basePath= "https://api.aspose.cloud/v4.0" ,
9 authPath= "https://api.aspose.cloud/connect/token" ,
10 debug= True)
11 client = Client(configuration)
12 html_api = HtmlApi(client)
13
14 options = {
15 ' width' : 8.3 ,
16 ' height' : 11.7 ,
17 ' topmargin' : 0.2 ,
18 ' bottommargin' : 0.2 ,
19 ' leftmargin' : 0.2 ,
20 ' rightmargin' : 0.2 ,
21 ' jpegquality' : 95
22 }
23
24 try :
25 res = html_api.convertApi .convert_local_to_local (input_file= "test.html" , output_file= "test.pdf" , options= options)
26 except ApiException as ex:
27 print("Exception" )
28 print("Info: " + str(ex))
29 raise ex
PHP El siguiente ejemplo demuestra cómo convertir HTML a PDF usando PHP. El HTML se toma del sistema de archivos local, se convierte a PDF y se guarda en la ruta local. Puede descargar el SDK de PHP desde el
repositorio de GitHub
Copy 1 <? php
2 require_once (__DIR__ . ' / vendor/ autoload.php ' );
3
4 $conf = array(
5 "basePath" => "https://api.aspose.cloud/v4.0" ,
6 "authPath" => "https://api.aspose.cloud/connect/token" ,
7 "apiKey" => "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
8 "appSID" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
9 "defaultUserAgent" => "Webkit"
10 );
11
12 $api_html = new Client\ Invoker\ Api\ HtmlApi($conf);
13
14 $src = ' input.html ' ;
15 $dst = ' output.pdf ' ;
16
17 $options_a4 = [
18 ' width' => 8.3 ,
19 ' height' => 11.7 ,
20 ' left_margin' => 0.2 ,
21 ' right_margin' => 0.2 ,
22 ' top_margin' => 0.2 ,
23 ' bottom_margin' => 0.2
24 ] ;
25
26
27 try {
28 // Request to server Api
29 $result = $api_html-> convertLocalToLocal($src, $dst, $options_a4);
30 print_r($result);
31 } catch (Exception $e) {
32 echo ' Exception when calling HtmlApi-> convertLocalToLocal: ' , $e-> getMessage(), PHP_EOL;
33 }
34 ?>
Ruby El siguiente ejemplo demuestra cómo convertir HTML a PDF aplicando el lenguaje Ruby. El HTML se toma del sistema de archivos local, se convierte a PDF y se guarda en la ruta local. Puede descargar el SDK de Ruby desde el
repositorio de GitHub .
Copy 1 # load the gem
2 require ' aspose_html_cloud'
3
4 # Get keys from aspose site.
5 # There is free quota available.
6 # For more details, see https://purchase.aspose.cloud/pricing
7
8 CONFIG = {
9 "basePath" :"https://api.aspose.cloud/v4.0" ,
10 "authPath" :"https://api.aspose.cloud/connect/token" ,
11 "apiKey" :"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
12 "appSID" :"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
13 "debug" :true
14 }
15
16 api_instance = AsposeHtml::HtmlApi.new CONFIG
17
18 src = "test.html" # String | Full path to the input file.
19 dst = "test.pdf" # String | Full path to the result.
20 opts = {
21 width: 8.3 , # Float | Resulting document width in inches.
22 height: 11.7 , # Float | Resulting document height in inches.
23 left_margin: 0.2 , # Float | Left resulting document margin in inches.
24 right_margin: 0.2 , # Float | Right resulting document margin in inches.
25 top_margin: 0.2 , # Float | Top resulting document margin in inches.
26 bottom_margin: 0.2 # Float | Bottom resulting document margin in inches.
27 }
28
29 begin
30 # Convert the document from the local file and save result to the local file.
31 result = api_instance.convert_local_to_local (src, dst,opts)
32 p result
33 rescue AsposeHtml::ApiError => e
34 puts "Exception when calling api_instance.convert_local_to_local: #{e}"
35 end
Node.js El siguiente ejemplo demuestra cómo convertir HTML a PDF aplicando el lenguaje Node.js. El HTML se toma del sistema de archivos local, se convierte a PDF y se guarda en la ruta local.
Copy 1 // Get keys from aspose site.
2 // There is free quota available.
3 // For more details, see https://purchase.aspose.cloud/pricing
4
5 var conf = {
6 "basePath" :"https://api.aspose.cloud/v4.0" ,
7 "authPath" :"https://api.aspose.cloud/connect/token" ,
8 "apiKey" :"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
9 "appSID" :"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
10 "defaultUserAgent" :"NodeJsWebkit"
11 };
12
13 var api = require(' @asposecloud / aspose- html- cloud' );
14
15 // Create Conversion Api object
16 var conversionApi = new api.ConversionApi (conf);
17
18 var src = "/path/to/src/test.html" ; // {String} Source document.
19 var dst = "/path/to/dst/test.pdf" ; // {String} Result document.
20 var opts = {
21 ' width' : 8.3 ,
22 ' height' : 11.7 ,
23 ' leftMargin' : 0.2 ,
24 ' rightMargin' : 0.2 ,
25 ' topMargin' : 0.2 ,
26 ' bottomMargin' : 0.2
27 };
28
29 var callback = function(error, data, response) {
30 if (error) {
31 console.error (error);
32 } else {
33 console.log (data);
34 }
35 };
36
37 conversionApi.convertLocalToLocal (src, dst, opts, callback);
Swift El siguiente ejemplo demuestra cómo convertir HTML a PDF aplicando el lenguaje Swift. El HTML se toma del sistema de archivos local, se convierte a PDF y se guarda en la ruta local. Puede descargar el SDK de Swift desde el
repositorio de GitHub .
Copy 1 import Alamofire
2 import Foundation
3 import XCTest
4 import AsposeHtmlCloud
5
6 static let fm = FileManager.default
7 let resourceDir = fm.homeDirectoryForCurrentUser .appendingPathComponent ("Documents/Aspose.HTML.Cloud.SDK.Swift/Tests/AsposeHtmlCloudTests/Resources" )
8 let resultDir = fm.homeDirectoryForCurrentUser .appendingPathComponent ("Documents/Aspose.HTML.Cloud.SDK.Swift/Tests/AsposeHtmlCloudTests/TestResult" )
9
10 func url (forResource fileName: String) -> URL {
11 return resourceDir.appendingPathComponent (fileName)
12 }
13
14 func fileExist (name: String) -> Bool {
15 return FileManager.default .fileExists (atPath: name)
16 }
17
18 ClientAPI.setConfig (
19 basePath: "https://api.aspose.cloud/v4.0" ,
20 authPath: "https://api.aspose.cloud/connect/token" ,
21 apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
22 appSID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
23 debugging: true
24 )
25
26 let fileName = "test.html"
27 let format = "pdf"
28 let src = url(forResource: fileName).absoluteString
29 let options = Options(width: 8.3 , height: 11.7 , leftMargin: 0.2 ,
30 rightMargin: 0.2 , topMargin: 0.2 , bottomMargin: 0.2 )
31
32
33 let expectation = self.expectation (description: "testConvert to \(format)" )
34 let dst = resultDir.appendingPathComponent ("Output.\(format)" ).absoluteString
35 HtmlAPI.convertLocalToLocal (src: src, dst: dst, options: options) { (data, error) in
36
37 guard error == nil else {
38 XCTFail("Error convert html to \(format)). Error=\(error!.localizedDescription)" )
39 return
40 }
41 let resultPath = data! .file !
42 XCTAssertTrue(fileExist(name: resultPath))
43 expectation.fulfill ()
44 }
45 self.waitForExpectations (timeout: 100.0 , handler: nil)
Java/Android El siguiente ejemplo demuestra cómo convertir HTML a PDF usando Java/Android. El HTML se toma del sistema de archivos local, se convierte a PDF y se guarda en la ruta local. Puede descargar el SDK de Java/Android desde el
repositorio de GitHub .
Copy 1 Configuration.setBasePath ("https://api.aspose.cloud" );
2 Configuration.setAuthPath ("https://api.aspose.cloud/connect/token" );
3
4 HtmlApi api = new HtmlApi("CLIENT_ID" , "CLIENT_SECRET" );
5
6 PDFConversionOptions opt_A5 = new PDFConversionOptions()
7 .setWidth (5.8 )
8 .setHeight (8.3 )
9 .setTopMargin (0.5 )
10 .setBottomMargin (0.5 )
11 .setLeftMargin (0.5 )
12 .setRightMargin (0.5 )
13 .setQuality (95);
14
15 JobBuilder builder = new ConverterBuilder()
16 .fromLocalFile ("input.html" )
17 .useOptions (opt_A5)
18 .saveToLocal ("output.pdf" );
19
20 OperationResult result = api.convert (builder);
CURL Cargue un archivo local al almacenamiento usando
API de almacenamiento . Llame a la API REST para ejecutar la conversión (en el ejemplo siguiente). Descargue el resultado de la conversión desde el almacenamiento usando
API de almacenamiento . El siguiente ejemplo demuestra cómo convertir HTML a PDF usando la API REST. HTML local convertido a PDF y guardado en el sistema de archivos local. Siga algunos pasos requeridos:
Copy 1 curl - X POST - v \
2 "https://api.aspose.cloud/v4.0/html/conversion/html-pdf" \
3 - d "{'InputPath': '/testpage.html', 'OutputFile': 'test.pdf', 'Options': {'Width':1000, 'Height': 800, 'LeftMargin': 10, 'RightMargin': 10, 'TopMargin': 10, 'BottomMargin': 10}}" \
4 - H "Content-Type: application/json" \
5 - H "Authorization: bearer <token>"
Encontrará más detalles sobre los parámetros de conversión disponibles para archivos HTML en el artículo
Opciones de conversión .
Ejemplo 3. Convertir una página web a PDF Aspose.HTML Cloud le permite recuperar una página HTML de la web por su URL, convertirla a otro formato y guardarla en el sistema de archivos local. El siguiente ejemplo demuestra cómo convertir una página web a PDF con los parámetros de conversión predeterminados.
C# Este ejemplo ilustra cómo convertir una página web a PDF usando C#. HTML se toma de la Web, se convierte a PDF y se guarda en un sistema de archivos local. Puede descargar el SDK de C# desde el
repositorio de GitHub .
Copy 1 // Initialize SDK API
2 var api = new HtmlApi("CLIENT_ID" , "CLIENT_SECRET" ).ConvertApi ;
3
4 // Convert HTML to PDF using ConvertUrlAsync() method
5 var result = await api.ConvertUrlAsync ("https://example.com" , "test.pdf" );
Java El siguiente ejemplo muestra cómo convertir una página web a PDF usando Java. HTML se toma de la Web, se convierte a PDF y se guarda en un sistema de archivos local. Puede descargar el SDK de Java desde el
repositorio de GitHub .
Copy 1 Configuration.setBasePath ("https://api.aspose.cloud" );
2 Configuration.setAuthPath ("https://api.aspose.cloud/connect/token" );
3
4 HtmlApi api = new HtmlApi("CLIENT_ID" , "CLIENT_SECRET" );
5
6 JobBuilder builder = new ConverterBuilder()
7 .fromUrl ("https://example.com" )
8 .saveToLocal ("output.pdf" );
9
10 OperationResult result = api.convert (builder);
C++ El siguiente ejemplo demuestra cómo convertir una página web a PDF usando C++. HTML se toma de la Web, se convierte a PDF y se guarda en un sistema de archivos local.
Copy 1 // Get current directory
2 std ::string cur_dir (argv[ 0] );
3 int pos = cur_dir.find_last_of ("/\\" );
4 cur_dir = cur_dir.substr (0, pos + 1); // Include the last slash
5 std ::wstring w_cur_dir (cur_dir.begin (), cur_dir.end ());
6
7 const utility::string_t clientId = L"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ;
8 const utility::string_t clientSecret = L"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ;
9 const utility::string_t basePath = L"https://api.aspose.cloud/v4.0" ;
10 const utility::string_t authPath = L"https://api.aspose.cloud/connect/token" ;
11
12 // Create configuration for authorization
13 std ::shared_ptr< ApiConfiguration> apiConfig (new ApiConfiguration(clientId, clientSecret, basePath, authPath));
14
15 // Create client from configuration
16 std ::shared_ptr< ApiClient> apiClient (new ApiClient(apiConfig));
17
18 // Create ConversionApi
19 std ::shared_ptr< ConversionApi> api = std::make_shared< ConversionApi> (apiClient);
20
21 // File name for conversion
22 utility ::string_t src = L"https://example.com" ;
23 utility ::string_t dst = w_cur_dir + L"result.pdf" ;
24
25 //Conversion
26 auto result = api-> convertUrlToLocal(src, dst);
27
28 // Check the result file
29 auto re = result-> getFile();
30 std ::ifstream f (re.c_str ());
31 if (! f.good ())
32 {
33 throw std::runtime_error("Conversion failed" );
34 }
Python El siguiente ejemplo muestra cómo convertir una página web a PDF aplicando el lenguaje Python. HTML se toma de la Web, se convierte a PDF y se guarda en un sistema de archivos local. Puede descargar el SDK de Python desde el
repositorio de GitHub .
Copy 1 import os
2 from asposehtmlcloud.configuration import Configuration
3 from asposehtmlcloud.api .html_api import HtmlApi
4 from asposehtmlcloud.api_client import ApiClient as Client
5 from asposehtmlcloud.rest import ApiException
6
7 # Get keys from aspose site.
8 # There is free quota available.
9 # For more details, see https://purchase.aspose.cloud/pricing
10
11 configuration = Configuration(apiKey= "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
12 appSid= "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
13 basePath= "https://api.aspose.cloud/v4.0" ,
14 authPath= "https://api.aspose.cloud/connect/token" ,
15 debug= True)
16
17 client = Client(configuration)
18 html_api = HtmlApi(client)
19
20 try :
21 res = html_api.convert_url_to_local (input_file= "https://example.com" , output_file= "result.pdf" )
22 if not os.path .exists (res.file ):
23 print(' conversion failed' )
24 except ApiException as ex:
25 print("Exception" )
26 print("Info: " + str(ex))
27 raise ex
PHP El siguiente ejemplo demuestra cómo convertir una página web a PDF usando PHP. HTML se toma de la Web, se convierte a PDF y se guarda en un sistema de archivos local. Puede descargar el SDK de PHP desde el
repositorio de GitHub .
Copy 1 <? php
2 require_once (__DIR__ . ' / vendor/ autoload.php ' );
3
4 $conf = array(
5 "basePath" => "https://api.aspose.cloud/v4.0" ,
6 "authPath" => "https://api.aspose.cloud/connect/token" ,
7 "apiKey" => "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
8 "appSID" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
9 "defaultUserAgent" => "Webkit"
10 );
11
12 $api_html = new Client\ Invoker\ Api\ HtmlApi($conf);
13
14 $src = ' https://example.com';
15 $dst = ' output.pdf ' ;
16
17 try {
18 // Request to server Api
19 $result = $api_html-> convertUrlToLocal($src, $dst);
20 print_r($result);
21 } catch (Exception $e) {
22 echo ' Exception when calling HtmlApi-> convertUrlToLocal: ' , $e-> getMessage(), PHP_EOL;
23 }
24 ?>
Ruby El siguiente ejemplo muestra cómo convertir una página web a PDF aplicando el lenguaje Ruby. HTML se toma de la Web, se convierte a PDF y se guarda en un sistema de archivos local. Puede descargar el SDK de Ruby desde el
repositorio de GitHub .
Copy 1 # load the gem
2 require ' aspose_html_cloud'
3
4 # Get keys from aspose site.
5 # There is free quota available.
6 # For more details, see https://purchase.aspose.cloud/pricing
7
8
9 CONFIG = {
10 "basePath" :"https://api.aspose.cloud/v4.0" ,
11 "authPath" :"https://api.aspose.cloud/connect/token" ,
12 "apiKey" :"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
13 "appSID" :"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
14 "debug" :true
15 }
16
17 api_instance = AsposeHtml::HtmlApi.new CONFIG
18
19 src = "https://example.com" # String | Input url.
20 dst = "test.pdf" # String | Result file.
21
22 begin
23 # Convert the HTML file from the web and save result to the local file.
24 result = api_instance.convert_url_to_local (src, dst)
25 p result
26 rescue AsposeHtml::ApiError => e
27 puts "Exception when calling api_instance.convert_url_to_local: #{e}"
28 end
Node.js El siguiente ejemplo muestra cómo convertir una página web a PDF aplicando el lenguaje Node.js. HTML se toma de la Web, se convierte a PDF y se guarda en un sistema de archivos local.
Copy 1 // Get keys from aspose site.
2 // There is free quota available.
3 // For more details, see https://purchase.aspose.cloud/pricing
4
5 var conf = {
6 "basePath" :"https://api.aspose.cloud/v4.0" ,
7 "authPath" :"https://api.aspose.cloud/connect/token" ,
8 "apiKey" :"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
9 "appSID" :"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
10 "defaultUserAgent" :"NodeJsWebkit"
11 };
12
13 var api = require(' @asposecloud / aspose- html- cloud' );
14
15 // Create Conversion Api object
16 var conversionApi = new api.ConversionApi (conf);
17
18 var src = "https://example.com" ; // {String} Url for conversion.
19 var dst = "/path/to/dst/test.pdf" ; // {String} Result document.
20 var opts = null ;
21
22 var callback = function(error, data, response) {
23 if (error) {
24 console.error (error);
25 } else {
26 console.log (data);
27 }
28 };
29
30 conversionApi.convertUrlToLocal (src, dst, opts, callback);
Swift El siguiente ejemplo muestra cómo convertir una página web a PDF aplicando el lenguaje Swift. HTML se toma de la Web, se convierte a PDF y se guarda en un sistema de archivos local. Puede descargar el SDK de Swift desde el
repositorio de GitHub .
Copy 1 import Alamofire
2 import Foundation
3 import XCTest
4 import AsposeHtmlCloud
5
6 static let fm = FileManager.default
7 let resultDir = fm.homeDirectoryForCurrentUser .appendingPathComponent ("Documents/Aspose.HTML.Cloud.SDK.Swift/Tests/AsposeHtmlCloudTests/TestResult" )
8
9 func fileExist (name: String) -> Bool {
10 return FileManager.default .fileExists (atPath: name)
11 }
12
13 ClientAPI.setConfig (
14 basePath: "https://api.aspose.cloud/v4.0" ,
15 authPath: "https://api.aspose.cloud/connect/token" ,
16 apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
17 appSID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
18 debugging: true
19 )
20
21 let format = "pdf"
22 let src = "https://example.com"
23 let dst = resultDir.appendingPathComponent ("Output.\(format)" ).absoluteString
24
25 let expectation = self.expectation (description: "testConvert to \(format)" )
26
27 HtmlAPI.convertUrlToLocal (src: src, dst: dst, options: nil) { (data, error) in
28
29 guard error == nil else {
30 XCTFail("Error convert web site to \(format)). Error=\(error!.localizedDescription)" )
31 return
32 }
33 let resultPath = data! .file !
34 XCTAssertTrue(fileExist(name: resultPath))
35 expectation.fulfill ()
36 }
37 self.waitForExpectations (timeout: 100.0 , handler: nil)
Java/Android El siguiente ejemplo muestra cómo convertir una página web a PDF usando Java/Android. HTML se toma de la Web, se convierte a PDF y se guarda en un sistema de archivos local. Puede descargar el SDK de Java/Android desde el
repositorio de GitHub .
Copy 1 Configuration.setBasePath ("https://api.aspose.cloud" );
2 Configuration.setAuthPath ("https://api.aspose.cloud/connect/token" );
3
4 HtmlApi api = new HtmlApi("CLIENT_ID" , "CLIENT_SECRET" );
5
6 JobBuilder builder = new ConverterBuilder()
7 .fromUrl ("https://example.com" )
8 .saveToLocal ("output.pdf" );
9
10 OperationResult result = api.convert (builder);
CURL Llame a la API REST para ejecutar la conversión (en el ejemplo siguiente). Descargue el resultado de la conversión desde el almacenamiento usando
API de almacenamiento . El siguiente ejemplo demuestra cómo convertir una página web a PDF usando la API REST. HTML se toma de la Web, se convierte a PDF y se guarda en un sistema de archivos local. Siga algunos pasos requeridos:
Copy 1 curl - X POST - v \
2 "https://api.aspose.cloud/v4.0/html/conversion/html-pdf" \
3 - d "{'InputPath': 'https://example.com', 'OutputFile': 'test.pdf'}" \
4 - H "Content-Type: application/json" \
5 - H "Authorization:Bearer <JWT_token>"
La conversión de página web a PDF se produce con las opciones de conversión predeterminadas : el ancho y el alto del documento PDF resultante corresponden a A4, y todos los márgenes tienen valor cero.
Ejemplo 4. Convertir HTML a PDF dentro del almacenamiento en la nube Aspose.HTML Cloud le permite obtener un archivo HTML de su almacenamiento en la nube y guardar el resultado de la conversión en el almacenamiento en la nube. Veamos un ejemplo de conversión dentro del almacenamiento en la nube con opciones de guardado predeterminadas.
C# El siguiente ejemplo muestra cómo convertir HTML a PDF usando C#. Un archivo HTML de origen se almacena en la nube, se convierte a PDF y se vuelve a guardar en un almacenamiento en la nube. Puede descargar el SDK de C# desde el
repositorio de GitHub .
Copy 1 // Initialize SDK API
2 var api = new HtmlApi("CLIENT_ID" , "CLIENT_SECRET" ).ConvertApi ;
3
4 // Convert HTML to PDF
5 var builder = new ConverterBuilder()
6 .FromStorageFile ("/test.html" )
7 .ToStorageFile ("/test.pdf" );
8
9 var result = await api.ConvertAsync (builder);
Java El siguiente ejemplo muestra cómo convertir HTML a PDF usando Java. Un archivo HTML de origen se almacena en la nube, se convierte a PDF y se vuelve a guardar en un almacenamiento en la nube. Puede descargar el SDK de Java desde el
repositorio de GitHub .
Copy 1 Configuration.setBasePath ("https://api.aspose.cloud" );
2 Configuration.setAuthPath ("https://api.aspose.cloud/connect/token" );
3
4 HtmlApi api = new HtmlApi("CLIENT_ID" , "CLIENT_SECRET" );
5
6 JobBuilder builder = new ConverterBuilder()
7 .fromStorageFile ("input.html" )
8 .saveToStorage ("output.pdf" );
9
10 OperationResult result = api.convert (builder);
C++ El siguiente ejemplo demuestra cómo convertir HTML a PDF usando C++. Un archivo HTML de origen se almacena en la nube, se convierte a PDF y se vuelve a guardar en un almacenamiento en la nube.
Copy 1 const utility::string_t clientId = L"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ;
2 const utility::string_t clientSecret = L"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ;
3 const utility::string_t basePath = L"https://api.aspose.cloud/v4.0" ;
4 const utility::string_t authPath = L"https://api.aspose.cloud/connect/token" ;
5
6 // Create configuration for authorization
7 std ::shared_ptr< ApiConfiguration> apiConfig (new ApiConfiguration(clientId, clientSecret, basePath, authPath));
8
9 // Create client from configuration
10 std ::shared_ptr< ApiClient> apiClient (new ApiClient(apiConfig));
11
12 // Create ConversionApi
13 std ::shared_ptr< ConversionApi> api = std::make_shared< ConversionApi> (apiClient);
14
15 // File name for conversion
16 utility ::string_t src = L"file/in/storage/index.html" ;
17 utility ::string_t dst = L"result/in/storage/result.pdf" ;
18
19 //Conversion
20 auto result = api-> convertStorageToStorage(src, dst);
Python El siguiente ejemplo muestra cómo convertir HTML a PDF aplicando el lenguaje Python. Un archivo HTML de origen se almacena en la nube, se convierte a PDF y se vuelve a guardar en un almacenamiento en la nube. Puede descargar el SDK de Python desde el
repositorio de GitHub .
Copy 1 from asposehtmlcloud.configuration import Configuration
2 from asposehtmlcloud.api .html_api import HtmlApi
3 from asposehtmlcloud.api_client import ApiClient as Client
4 from asposehtmlcloud.rest import ApiException
5
6 configuration = Configuration(apiKey= "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
7 appSid= "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
8 basePath= "https://api.aspose.cloud/v4.0" ,
9 authPath= "https://api.aspose.cloud/connect/token" ,
10 debug= True)
11 client = Client(configuration)
12 html_api = HtmlApi(client)
13
14 try :
15 res = html_api.convertApi .convert_storage_to_storage (input_file= "test.html" , output_file= "test.pdf" ,
16 storage_name= None)
17 except ApiException as ex:
18 print("Exception" )
19 print("Info: " + str(ex))
20 raise ex
PHP El siguiente ejemplo demuestra cómo convertir HTML a PDF usando PHP. Un archivo HTML de origen se almacena en la nube, se convierte a PDF y se vuelve a guardar en un almacenamiento en la nube. Puede descargar el SDK de PHP desde el
repositorio de GitHub .
Copy 1 <? php
2 require_once (__DIR__ . ' / vendor/ autoload.php ' );
3
4 $configuration = array(
5 "basePath" => "https://api.aspose.cloud/v4.0" ,
6 "authPath" => "https://api.aspose.cloud/connect/token" ,
7 "apiKey" => "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
8 "appSID" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
9 "defaultUserAgent" => "Webkit"
10 );
11
12 $api_html = new HtmlApi($configuration);
13
14 $src = "FolderInStorage/test.html" ;
15 $dst = ' FolderInStorage/ test.pdf ' ;
16 $options = null ;
17
18 try {
19 $result = $api_html-> convertStorageToStorage($src, $dst, null , $options);
20 print_r($result);
21 } catch (Exception $e) {
22 echo ' Exception when calling $api_html-> convertStorageToStorage: ' , $e-> getMessage(), PHP_EOL;
23 }
24 ?>
Ruby El siguiente ejemplo muestra cómo convertir HTML a PDF aplicando el lenguaje Ruby. Un archivo HTML de origen se almacena en la nube, se convierte a PDF y se vuelve a guardar en un almacenamiento en la nube. Puede descargar el SDK de Ruby desde el
repositorio de GitHub .
Copy 1 # load the gem
2 require ' aspose_html_cloud'
3
4 # Get keys from aspose site.
5 # There is free quota available.
6 # For more details, see https://purchase.aspose.cloud/pricing
7
8
9 CONFIG = {
10 "basePath" :"https://api.aspose.cloud/v4.0" ,
11 "authPath" :"https://api.aspose.cloud/connect/token" ,
12 "apiKey" :"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
13 "appSID" :"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
14 "debug" :true
15 }
16
17 api_instance = AsposeHtml::HtmlApi.new CONFIG
18
19 src = "FolderInStorage/test.html" # String | Source file.
20 dst = "FolderInStorage/test.md" # String | Result file.
21 storage = nil
22
23 begin
24 # Convert the file from the storage and save result to the storage.
25 result = api_instance.convert_storage_to_storage (src, dst, storage)
26 p result
27 rescue AsposeHtml::ApiError => e
28 puts "Exception when calling api_instance.convert_storage_to_storage: #{e}"
29 end
Node.js El siguiente ejemplo muestra cómo convertir HTML a PDF aplicando el lenguaje Node.js. Un archivo HTML de origen se almacena en la nube, se convierte a PDF y se vuelve a guardar en un almacenamiento en la nube.
Copy 1 // Get keys from aspose site.
2 // There is free quota available.
3 // For more details, see https://purchase.aspose.cloud/pricing
4
5 var conf = {
6 "basePath" :"https://api.aspose.cloud/v4.0" ,
7 "authPath" :"https://api.aspose.cloud/connect/token" ,
8 "apiKey" :"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
9 "appSID" :"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
10 "defaultUserAgent" :"NodeJsWebkit"
11 };
12
13 var api = require(' @asposecloud / aspose- html- cloud' );
14
15 // Create Conversion Api object
16 var conversionApi = new api.ConversionApi (conf);
17
18 var src = "FolderInStorage/test.html" ; // {String} Source document.
19 var dst = "FolderInStorage/test.pdf" ; // {String} Result document.
20 var opts = null ;
21 var storage = null ;
22
23 var callback = function(error, data, response) {
24 if (error) {
25 console.error (error);
26 } else {
27 console.log (data);
28 }
29 };
30
31 conversionApi.convertStorageToStorage (src, dst, storage, opts, callback);
Swift El siguiente ejemplo muestra cómo convertir HTML a PDF aplicando el lenguaje Swift. Un archivo HTML de origen se almacena en la nube, se convierte a PDF y se vuelve a guardar en un almacenamiento en la nube. Puede descargar el SDK de Swift desde el
repositorio de GitHub .
Copy 1 import Alamofire
2 import Foundation
3 import XCTest
4 import AsposeHtmlCloud
5
6 ClientAPI.setConfig (
7 basePath: "https://api.aspose.cloud/v4.0" ,
8 authPath: "https://api.aspose.cloud/connect/token" ,
9 apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ,
10 appSID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ,
11 debugging: true
12 )
13
14 let src = "FolderInStorage/test.html"
15 let dst = "FolderInStorage/test.pdf"
16
17 let expectation = self.expectation (description: "testConvert to pdf" )
18
19 HtmlAPI.convertStorageToStorage (src: src, dst: dst, storage: nil, options: nil) { (data, error) in
20
21 guard error == nil else {
22 XCTFail("Error convert html to pdf). Error=\(error!.localizedDescription)" )
23 return
24 }
25
26 let resultPath = data! .file !
27
28 StorageAPI.objectExists (path: resultPath, storageName: nil, versionId: nil) {(data, error) in
29 guard error == nil else {
30 XCTFail("Error objectExists exist. Error=\(error!.localizedDescription)" )
31 return
32 }
33
34 XCTAssertTrue(data! .exists )
35 XCTAssertFalse(data! .isFolder )
36 expectation.fulfill ()
37 }
38 }
39 self.waitForExpectations (timeout: 100.0 , handler: nil)
Java/Android El siguiente ejemplo muestra cómo convertir HTML a PDF usando Java/Android. Un archivo HTML de origen se almacena en la nube, se convierte a PDF y se vuelve a guardar en un almacenamiento en la nube. Puede descargar el SDK de Java/Android desde el
repositorio de GitHub .
Copy 1 Configuration.setBasePath ("https://api.aspose.cloud" );
2 Configuration.setAuthPath ("https://api.aspose.cloud/connect/token" );
3
4 HtmlApi api = new HtmlApi("CLIENT_ID" , "CLIENT_SECRET" );
5
6 JobBuilder builder = new ConverterBuilder()
7 .fromStorageFile ("input.html" )
8 .saveToStorage ("output.pdf" );
9
10 OperationResult result = api.convert (builder);
CURL El siguiente ejemplo demuestra cómo convertir HTML a PDF usando la API REST. El archivo HTML se encuentra en el almacenamiento en la nube, se convierte a PDF y se guarda nuevamente en el almacenamiento en la nube.
Copy 1 curl - X POST - v \
2 "https://api.aspose.cloud/v4.0/html/conversion/html-pdf" \
3 - d "{'InputPath': '/test.html', 'OutputFile': '/test.pdf'}" \
4 - H "Content-Type: application/json" \
5 - H "Authorization:Bearer <JWT_token>"
Ver también El artículo
SDK disponibles le presenta la capacidad de Aspose.HTML Cloud para usar SDK en varios lenguajes de programación, como C#, Java, Python, Ruby, PHP, Node.js, Swift, Android y C++. El artículo
Opciones de conversión describe un conjunto de clases que representan opciones para convertir un documento fuente basado en HTML a PDF, XPS e imagen. Aspose.HTML Cloud API a la que puedes llamar directamente desde tu navegador accediendo a la
Referencia de API . Aspose.HTML ofrece un
Convertidor de HTML a PDF gratuito en línea que convierte rápidamente HTML a PDF con alta calidad. ¡Simplemente cargue sus archivos, conviértalos y obtenga el resultado en unos segundos!