HTML to PDF Converter, A Must-have Tool to Save a Web Page

What is an HTML to PDF converter?

HTML to PDF converter is a very useful tool in making reports and presentations from website sources. A HTML file converted to PDF can be easily viewed in any device without any formatting changes. It is also readily available for viewing even without Internet connection.

A very simple way to convert a HTML file or HTML string is to enter the URL of the web page or the HTML code on the space provided like this

Then click the “Convert to PDF” button. You will find the converted file in PDF format downloaded instantly to your device.

This works well if you are converting only a few web pages at a time. If you are a developer looking for a faster way to convert to PDF large volume of HTML files, the use of API is the way to go.

This HTML to PDF converter API web service will convert webpages to pdfs online by reading your webpage and dynamically generate a PDF. It can seamlessly handle even complex documents and layouts including images.

Here are some examples of codes that you can use.

Example #1 – How to stream a PDF directly to the end user with ASP.NET C# MVC

By commenting out line #17 you can switch between showing the file inside the browser window itself (if supported by the browser), and downloading as an attachment.

public ActionResult Run()
{
string apiKey = "YOUR-API-KEY";
string value = "http://www.google.com"; // a url starting with http or an HTML string
using (var client = new WebClient())
{
// Build the conversion options
NameValueCollection options = new NameValueCollection();
options.Add("apikey", apiKey);
options.Add("value", value);
// Call the API convert to a PDF
MemoryStream ms = new MemoryStream(client.UploadValues("https://api.html2pdfrocket.com/pdf", options));
// Make the file a downloadable attachment - comment this out to show it directly inside
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=myfilename.pdf");
// Return the file as a PDF
return new FileStreamResult(ms, "application/pdf");
}
}

Example #2 – How to convert an HTML string to a PDF using ASP.NET C#

You can also convert an HTML string to a PDF by supplying the HTML directly. It can be as complex as you like and may include image references and stylesheeet information — just make sure it is valid HTML

public void Run()
{
string apiKey = "YOUR-API-KEY";
string value = "<h1>An <strong>Example</strong>HTML String</h1>"; // a direct HTML string
using (var client = new WebClient())
{
// Build the conversion options
NameValueCollection options = new NameValueCollection();
options.Add("apikey", apiKey);
options.Add("value", value);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //needed for older .net versions
// Call the API convert to an image
byte[] result = client.UploadValues("https://api.html2pdfrocket.com/pdf", options);
// Save the image to disk
System.IO.File.WriteAllBytes(Server.MapPath(Path.Combine("~/", @"c:\temp\mypdf.pdf")), result);
}
}
//using query string in a Get
public void DownloadFile()
{
string apiKey = "YOUR-API-KEY";
string value = "http://www.google.com"; // a url starting with http or an HTML string.
using (var client = new WebClient())
{
client.QueryString.Add("apikey", apiKey);
client.QueryString.Add("value", value);
client.DownloadFile("https://api.html2pdfrocket.com/pdf/", @"c:\temp\mypdf.pdf");
}
}

Example #3 – C# Batch/Asynchronous Process

For PDF conversion taking more than 30 seconds or input/output files more than 6 Mb, you need to use the batch/asynchronous parameters.

using (var client = new HttpClient())
{
var param = new Dictionary<string, string>();
param.Add("apikey", apiKey);
param.Add("value", url);
param.Add("Batch", "true");
//as an alternative to polling, you can pass the webhook option parameter
//from your website where the api could post back once the pdf file is ready
//the same JSON Result is posted back with Status=Ready and the PDFLink
param.Add("Webhook", "https://b2b-example.customer.com/my-webhook");
var content = new FormUrlEncodedContent(param);
var result = client.PostAsync(apiUrl, content).Result;
if (result.IsSuccessStatusCode)
{
string jsonResult = result.Content.ReadAsStringAsync().Result;
JObject jsonParsed = JObject.Parse(jsonResult);
if (jsonParsed["PdfToken"] != null)
{
string pdfToken = jsonParsed["PdfToken"].ToString();
param.Add("PdfToken", pdfToken);
content = new FormUrlEncodedContent(param);
//polling every 30 seconds to check if the pdf file is ready
do
{
result = client.PostAsync(apiUrl, content).Result;
jsonResult = result.Content.ReadAsStringAsync().Result;
jsonParsed = JObject.Parse(jsonResult);
string status = "";
if (jsonParsed["Status"] != null)
status = jsonParsed["Status"].ToString();
if (status == "Ready")
{
File.WriteAllBytes("MyPdfFile.pdf", client.GetByteArrayAsync(jsonParsed["PdfLink"].ToString()).Result);
break;
}
else
{
//wait for 30 seconds
System.Threading.Thread.Sleep(30000);
}
} while (true);
}
}
}

Example #4 – How to use PHP to convert an HTML string to a PDF and save to disk

<?php
// Set parameters
$apikey = 'YOUR-API-KEY';
$value = '<title>Test PDF conversion</title>This is the body'; // can also be a url, starting with http..
// Convert the HTML string to a PDF using those parameters. Note if you have a very long HTML string use POST rather than get. See example #5
$result = file_get_contents("https://api.html2pdfrocket.com/pdf?apikey=" . urlencode($apikey) . "&value=" . urlencode($value));
// Save to root folder in website
file_put_contents('mypdf-1.pdf', $result);
?>

Example #5 – How to convert a PHP webpage to a PDF and stream it to a user as an attachment with PHP

Example also shows how you can download the file as an attachment, or show it inline in the web browser.

<?php
// Set parameters
$apikey = 'YOUR-API-KEY';
$value = '<title>Test PDF conversion</title>This is the body'; // can also be a url, starting with http..
// Convert the HTML string to a PDF using those parameters. Note if you have a very long HTML string use POST rather than get. See example #5
$result = file_get_contents("https://api.html2pdfrocket.com/pdf?apikey=" . urlencode($apikey) . "&value=" . urlencode($value));
// Output headers so that the file is downloaded rather than displayed
// Remember that header() must be called before any actual output is sent
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . strlen($result));
// Make the file a downloadable attachment - comment this out to show it directly inside the
// web browser. Note that you can give the file any name you want, e.g. alias-name.pdf below:
header('Content-Disposition: attachment; filename=' . 'alias-name.pdf' );
// Stream PDF to user
echo $result;
?>

Example #6 – PHP Batch/Asynchronous Process

The WebClient has been replaced with HttpClient in ASP.NET 5. Other aspects follow the same format.

<?php
function PostToWeb($postData) : string {
$apiUrl = 'https://api.html2pdfrocket.com/pdf';
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($postData)
)
);
$context = stream_context_create($opts);
$data = file_get_contents($apiUrl, false, $context);
return $data;
}
// Set parameters
$apikey = 'YOUR-API-KEY';
$sHTMLToConvert = 'https://www.google.com';
//as an alternative to polling, you can pass the webhook option parameter from your website
//where the api could post back once the pdf file is ready
//the same JSON Result is posted back with Status=Ready and the PDFLink
$webhook = 'https://b2b-example.customer.com/my-webhook';
$postdata = array(
'apikey' => $apikey,
'value' => $sHTMLToConvert,
'Batch' => true,
'Webhook' => $webhook
);
$data = json_decode(PostToWeb($postdata), true);
$postdata['PdfToken'] = $data["PdfToken"];
do
{
//polling every 30 seconds to check if the pdf file is ready
$data = json_decode(PostToWeb($postdata), true);
if ($data["Status"] === "Ready")
{
$result = file_get_contents($data["PdfLink"]);
file_put_contents('myFile.pdf',$result);
break;
}
sleep(30);
}while(true)
?>

There are more code examples in C#, PHP, Java, Javascript, Ruby, Android, and more. Check How to Convert HTMl to PDF page.

You can start converting in a matter of minutes, starting with downloading a Free API key.

References:

Smallpdf

Pspdfkit

Quora

Quora