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.
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 = "ABCD-1234"; 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"); } }
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 = "ABCD-1234"; string value = "An ExampleHTML String
"; // 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); // 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\myimage.pdf")), result); } }
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); } } }
// Set parameters $apikey = 'YOUR-API-KEY'; $value = 'Test PDF conversion This is the body'; // can aso 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 also shows how you can download the file as an attachment, or show it inline in the web browser.
// Set parameters $apikey = 'YOUR-API-KEY'; $value = 'Test PDF conversion This is the body'; // can aso 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;
For PDF conversion taking more than 30 seconds or input/output files more than 6 Mb, you need to use the batch/asynchronous parameters.
<?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: