HTML to XPS

Convert HTML to XPS

HyperText Markup Language (HTML) is a standard markup language for web page creation. It allows the creation and structure of sections, paragraphs, and links using HTML elements/tags. And in case some custom fonts are used in an HTML file or any dynamic object is referenced which requires an active connection to the source machine/server, there are chances of compromising the fidelity of the document. On the other side, in XML Paper Specification(XPS), the page elements are defined independently of a particular operating system, printer, or viewing application. So an intelligent approach is to convert HTML to XPS format.

HTML Conversion API

Aspose.HTML Cloud SDK for Java is a lightweight REST architecture-based API providing the capabilities to create, manipulate and convert HTML files to PDF, DOCX, TIFF, JPEG, etc. It also supports the conversion of HTML to XPS. So, first, we need to add the following details in pom.xml of the Maven build type project to include the SDK in our Java project.

<repositories> 
    <repository>
        <id>aspose-cloud</id>
        <name>artifact.aspose-cloud-releases</name>
        <url>https://artifact.aspose.cloud/repo</url>
    </repository>   
</repositories>

<dependencies>
    <dependency>
        <groupId>com.aspose</groupId>
	<artifactId>aspose-html-cloud</artifactId>
	<version>20.7.0</version>
	<scope>compile</scope>
    </dependency>
</dependencies>

After installation, the next step is a free subscription to our cloud services via Aspose.Cloud dashboard using GitHub or Google account. Or, simply create a new Account and obtain your Client Credentials details.

Convert HTML to XPS in Java

Please follow the instructions specified below to develop an HTML to XPS converter.

  • First of all, we need to specify details against Configuration.setAPP_SID and Configuration.setAPI_KEY methods
  • Secondly, we set details for setBasePath(..), setAuthPath(..) and specify setUserAgent(…) as WebKit
  • Thirdly, for our own assistance, we are going to set setDebug(..) as true
  • Now create an object of ConversionApi class
  • Specify the margin details and name for information for the resultant file
  • Finally, call GetConvertDocumentToXps(…) method which requires input HTML name, dimensions and margin details as arguments
// for more examples, please visit https://github.com/aspose-html-cloud/aspose-html-cloud-java
try
{
// Get ClientID and ClientSecret from https://dashboard.aspose.cloud/
String clientId = "bbf94a2c-6d7e-4020-b4d2-b9809741374e";
String clientSecret = "1c9379bb7d701c26cc87e741a29987bb";
// details for Api invocation
com.aspose.html.Configuration.setAPP_SID(clientId);
com.aspose.html.Configuration.setAPI_KEY(clientSecret);
com.aspose.html.Configuration.setBasePath("https://api.aspose.cloud/v3.0");
com.aspose.html.Configuration.setAuthPath("https://api.aspose.cloud/connect/token");
com.aspose.html.Configuration.setUserAgent("WebKit");
com.aspose.html.Configuration.setDebug(true);
// Create an object of Aspose.HTML Cloud API
com.aspose.html.api.ConversionApi htmlApi = new ApiClient().createService(ConversionApi.class);
// The html document from cloud storage
String name = "list.html";
// resultant image format
String outFormat = "PNG";
Integer width = 800; // Resulting image width.
Integer height = 1000; // Resulting image height.
Integer leftMargin = 10; // Left resulting image margin.
Integer rightMargin = 10; // Right resulting image margin.
Integer topMargin = 10; // Top resulting image margin.
Integer bottomMargin = 10; // Bottom resulting image margin.
Integer resolution = 300; // Resolution of resulting image.
String folder = null; // The folder in the storage. Should exist.
String storage = "Internal"; // Name of the storage. null
// Invoke the API for HTML to XPS conversion
retrofit2.Call<okhttp3.ResponseBody> call = htmlApi.GetConvertDocumentToXps(name, width, height, leftMargin, rightMargin, topMargin, bottomMargin, folder, storage);
System.out.println("HTML to XPS conversion sucessfull !");
}catch(Exception ex)
{
System.out.println(ex);
}

The above code returns the result in the response stream so, in order to save the output on a local drive, we may consider using the following custom method.

/*
* Method taking ResponseBody and resultant file name as arguments
*/
public static void checkAndSave(retrofit2.Call<okhttp3.ResponseBody> call, String fileName) throws IOException
{
// Synchronously send the request and return its response.
retrofit2.Response<okhttp3.ResponseBody> res = call.execute();
// The deserialized response body of a successful response
okhttp3.ResponseBody answer = res.body();
//Save to test directory
boolean result = saveToDisc(answer, fileName);
// validate the result value is true (optional step)
Assert.assertTrue(result);
}
/*
*
* Call this method to save Response content as file on local drive
*
*/
public static boolean saveToDisc(okhttp3.ResponseBody body, String fileName)
{
// create file object indicating location for resultant file
File savedFile = new File("c:\\Downloads\\"+fileName);
try (InputStream inputStream = body.byteStream();
OutputStream outputStream = new FileOutputStream(savedFile))
{
byte[] fileReader = new byte[4096];
long fileSizeDownloaded = 0;
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) break;
// save file stream to local drive
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
}
// clear the output stream instance
outputStream.flush();
// return true as file save successfully
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} // saveToDisc ends here
HTML to XPS

Image1:- HTML to XPS preview

The sample files used in the above example can be downloaded from list.html and resultantFile.xps.

HTML to XPS using cURL Commands

The REST APIs can also be accessed via cURL commands so in this section, we are going to learn the steps on how to perform the HTML to XPS conversion using the cURL command. Now as a pre-requisite, we need to first generate a JSON Web Token (JWT) based on your individual client credentials. Please execute the following command to generate the JWT token.

curl -v "https://api.aspose.cloud/connect/token" \
-X POST \
-d "grant_type=client_credentials&client_id=bbf94a2c-6d7e-4020-b4d2-b9809741374e&client_secret=1c9379bb7d701c26cc87e741a29987bb" \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "Accept: application/json"

Now that we have the JWT token, please execute the following command on the terminal to perform HTML to XPS conversion.

curl -v -X GET "https://api.aspose.cloud/html/list.html/convert/xps" \
-H  "accept: multipart/form-data" \
-H  "authorization: Bearer <JWT Token>" \
-o final.xps

Conclusion

This article has explained the details for converting HTML to XPS using REST API. We have learned the steps to convert HTML to XPS using Java code snippets as well as through cURL commands. Furthermore, please note that the Product Documentation is a great source for learning the amazing capabilities being offered by the API. Furthermore, if you encounter any issues while using the API, please feel free to contact the Free product support forum.

We also recommend visiting the following blogs for further details regarding: