How to create a PDF from my HTML and CSS Code?

In this article, we describe how to create a PDF from your HTML and CSS code. To create a PDF from your HTML, you need to pass both HTML and CSS code in a JSON structure as the body of the POST request to our API. The JSON structure you need to send should look like the following:

{
	"html": "",
	"css":  ""
}

Now let us assume you have the following HTML and CSS code.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Basic Example</title>
        <link rel="stylesheet" href="style.css" />
    </head>
    <body>
    	<h1>Hello PrintCSS Cloud!</h1>
    </body>
</html>

The style.css only sets the color of the H1 element to blue.

h1{
	color:blue;
}

For our API, you will only need the HTML, which is in between the BODY tag. The rest can be skipped. So the same content in our JSON structure would look like this:

{
	"html": "<h1>Hello PrintCSS Cloud!</h1>",
	"css":  "h1{ color:blue; }"
}

To send the request to our API now, you need to subscribe to a plan on RapidAPI. With this, you get the API key that is required to authenticate with our REST service.

The Request as cURL would look like the following:

curl --location --request POST 'https://printcss-cloud.p.rapidapi.com/render' \
--header 'x-rapidapi-host: printcss-cloud.p.rapidapi.com' \
--header 'x-rapidapi-key: YOUR_API_KEY' \
--data-raw '{
    "html": "<h1>Hello PrintCSS Cloud!</h1>",
    "css":  "h1{ color:blue; }"
}'

In PHP you can do it like this:

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://printcss-cloud.p.rapidapi.com/render',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{
	"html": "<h1>Hello PrintCSS Cloud!</h1>",
	"css":  "h1{ color:blue; }"
}',
  CURLOPT_HTTPHEADER => array(
    'x-rapidapi-host: printcss-cloud.p.rapidapi.com',
    'x-rapidapi-key: YOUR_API_KEY'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

and in JavaScript:

var data = "{\r\n	\"html\": \"<h1>Hello PrintCSS Cloud!</h1>\",\r\n	\"css\":  \"h1{ color:blue; }\"\r\n}";

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
  if(this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://printcss-cloud.p.rapidapi.com/render");
xhr.setRequestHeader("x-rapidapi-host", "printcss-cloud.p.rapidapi.com");
xhr.setRequestHeader("x-rapidapi-key", "YOUR_API_KEY");

xhr.send(data);

The resulting PDF is attached to the article.

HTML and CSS Code.pdf