SelectPdf HTML to PDF online API provides an easy to use, powerful tool that can be used to generate fully structured PDFs with just a few lines of code.
SelectPdf is a web service that can be called from any programming language: Java, PHP, .NET, Ruby, Perl, Python, Javascript, etc. Try SelectPdf API to experience SaaS at its best.
The following examples are in C# for SelectPdf Online REST API. Make sure that you are interested in the online API, because if you are interested in the .NET library, there are other places where you can find C# samples for SelectPdf .NET Library.
Until recently, we did not provide any .NET samples for the online API, because the recommended product if .NET was available, was our SelectPdf Library for .NET. What changed is that more and more users are moving to systems where the full .NET Framework (required by our .NET library) is not available (they use Azure websites or .NET Core or Mono), but they still code in VB.NET or C#. Here, the online Html to Pdf API comes into play.
There are a variety of methods in .NET that you can use to access a REST API. We will show you 3 of them in this article. One important thing to remember is that the PDF is returned to the client in binary form. Trying to read this binary format as text will cause problems and your PDF will not be saved correctly. So, remember, binary mode for PDF reading.
Later Edit: The recommended approach to access SelectPdf Online REST API from C# is to use the dedicated .NET Client Library for SelectPdf API. Alternatively, you can write your own code to access the API. Below are some examples for this approach.
Example #1 – How to use C# to convert a webpage to PDF and save it on the disk using HttpWebRequest / HttpWebResponse
This code converts an url to pdf in C# using SelectPdf REST API through a POST request. It uses HttpWebRequest / HttpWebResponse (and Newtonsoft for JSON serialization). The content is saved into a file on the disk.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
using System; using System.Net; using System.IO; using System.Text; using Newtonsoft.Json; namespace SelectPdf.APi.CSharp { public class SelectPdfTest { public static string apiEndpoint = "https://selectpdf.com/api2/convert/"; public static string apiKey = "your license key here"; public static string testUrl = "https://selectpdf.com"; public static void Main(string[] args) { // POST JSON example using HttpWebRequest / HttpWebResponse (and Newtonsoft for JSON serialization) SelectPdfPostWithHttpWebRequest(); } // POST JSON example using HttpWebRequest / HttpWebResponse (and Newtonsoft for JSON serialization) public static void SelectPdfPostWithHttpWebRequest() { System.Console.WriteLine("Starting conversion with HttpWebRequest ..."); // set parameters SelectPdfParameters parameters = new SelectPdfParameters(); parameters.key = apiKey; parameters.url = testUrl; // JSON serialize parameters string jsonData = JsonConvert.SerializeObject(parameters); byte[] byteData = Encoding.UTF8.GetBytes(jsonData); // create request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiEndpoint); request.ContentType = "application/json"; request.Method = "POST"; request.Credentials = CredentialCache.DefaultCredentials; // POST parameters Stream dataStream = request.GetRequestStream(); dataStream.Write(byteData, 0, byteData.Length); dataStream.Close(); // GET response (if response code is not 200 OK, a WebException is raised) try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); if (response.StatusCode == HttpStatusCode.OK) { // all ok - read PDF and write on disk (binary read!!!!) MemoryStream ms = BinaryReadStream(responseStream); // write to file FileStream file = new FileStream("test1.pdf", FileMode.Create, FileAccess.Write); ms.WriteTo(file); file.Close(); } else { // error - get error message System.Console.WriteLine("Error code: " + response.StatusCode.ToString()); } responseStream.Close(); } catch (WebException webEx) { // an error occurred System.Console.WriteLine("Error: " + webEx.Message); HttpWebResponse response = (HttpWebResponse)webEx.Response; Stream responseStream = response.GetResponseStream(); // get details of the error message if available (text read!!!) StreamReader readStream = new StreamReader(responseStream); string message = readStream.ReadToEnd(); responseStream.Close(); System.Console.WriteLine("Error Message: " + message); } catch (Exception ex) { System.Console.WriteLine("Error: " + ex.Message); } System.Console.WriteLine("Finished."); } // Binary read from Stream into a MemoryStream public static MemoryStream BinaryReadStream(Stream input) { int bytesNumber = 0; byte[] bytes = new byte[1025]; MemoryStream stream = new MemoryStream(); BinaryReader reader = new BinaryReader(input); do { bytesNumber = reader.Read(bytes, 0, bytes.Length); if (bytesNumber > 0) stream.Write(bytes, 0, bytesNumber); } while (bytesNumber > 0); stream.Position = 0; return stream; } } // API parameters - add the rest here if needed public class SelectPdfParameters { public string key { get; set; } public string url { get; set; } public string html { get; set; } public string base_url { get; set; } } } |
Example #2 – How to use C# to convert a webpage to PDF and save it on the disk using WebClient
This code converts an url to pdf in C# using SelectPdf HTML to PDF REST API through a POST request. It uses WebClient (and Newtonsoft for JSON serialization). The content is saved into a file on the disk.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
using System; using System.Net; using System.IO; using System.Text; using Newtonsoft.Json; namespace SelectPdf.APi.CSharp { public class SelectPdfTest { public static string apiEndpoint = "https://selectpdf.com/api2/convert/"; public static string apiKey = "your license key here"; public static string testUrl = "https://selectpdf.com"; public static void Main(string[] args) { // POST JSON example using WebClient (and Newtonsoft for JSON serialization) SelectPdfPostWithWebClient(); } // POST JSON example using WebClient (and Newtonsoft for JSON serialization) public static void SelectPdfPostWithWebClient() { System.Console.WriteLine("Starting conversion with WebClient ..."); // set parameters SelectPdfParameters parameters = new SelectPdfParameters(); parameters.key = apiKey; parameters.url = testUrl; // JSON serialize parameters string jsonData = JsonConvert.SerializeObject(parameters); byte[] byteData = Encoding.UTF8.GetBytes(jsonData); // create WebClient object WebClient webClient = new WebClient(); webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json"); // POST parameters (if response code is not 200 OK, a WebException is raised) try { byte[] result = webClient.UploadData(apiEndpoint, "POST", byteData); // all ok - read PDF and write on disk (binary read!!!!) MemoryStream ms = new MemoryStream(result); // write to file FileStream file = new FileStream("test2.pdf", FileMode.Create, FileAccess.Write); ms.WriteTo(file); file.Close(); } catch (WebException webEx) { // an error occurred System.Console.WriteLine("Error: " + webEx.Message); HttpWebResponse response = (HttpWebResponse)webEx.Response; Stream responseStream = response.GetResponseStream(); // get details of the error message if available (text read!!!) StreamReader readStream = new StreamReader(responseStream); string message = readStream.ReadToEnd(); responseStream.Close(); System.Console.WriteLine("Error Message: " + message); } catch (Exception ex) { System.Console.WriteLine("Error: " + ex.Message); } System.Console.WriteLine("Finished."); } } // API parameters - add the rest here if needed public class SelectPdfParameters { public string key { get; set; } public string url { get; set; } public string html { get; set; } public string base_url { get; set; } } } |
Example #3 – How to use C# to convert a webpage to PDF and save it on the disk using RestSharp
This code converts an url to pdf in C# using SelectPdf Online Web Service through a POST request. It uses RestSharp for the HTTP communication with the API. The content is saved into a file on the disk.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
using System; using System.Net; using System.IO; using System.Text; namespace SelectPdf.APi.CSharp { public class SelectPdfTest { public static string apiEndpoint = "https://selectpdf.com/api2/convert/"; public static string apiKey = "your license key here"; public static string testUrl = "https://selectpdf.com"; public static void Main(string[] args) { // POST JSON example using RestSharp (Simple REST and HTTP API Client for .NET) SelectPdfPostWithRestSharp(); } // POST JSON example using RestSharp (Simple REST and HTTP API Client for .NET) public static void SelectPdfPostWithRestSharp() { System.Console.WriteLine("Starting conversion with RestSharp ..."); // set parameters var parameters = new { key = apiKey, url = testUrl }; // create request RestSharp.RestClient client = new RestSharp.RestClient(apiEndpoint); RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.POST); request.RequestFormat = RestSharp.DataFormat.Json; request.AddHeader("Content-Type", "application/json"); // add parameters to request request.AddJsonBody(parameters); // execute request try { dynamic response = client.Execute(request); if (response.StatusCode == HttpStatusCode.OK) { // all ok - read PDF and write on disk (binary read!!!!) byte[] result = response.RawBytes; MemoryStream ms = new MemoryStream(result); // write to file FileStream file = new FileStream("test3.pdf", FileMode.Create, FileAccess.Write); ms.WriteTo(file); file.Close(); } else { // an error occurred System.Console.WriteLine("Error code: " + response.StatusCode.ToString()); System.Console.WriteLine("Error message: " + response.StatusDescription); System.Console.WriteLine("Error details: " + response.Content); } } catch (Exception ex) { System.Console.WriteLine("Error: " + ex.Message); } System.Console.WriteLine("Finished."); } } } |
The above samples use only the 2 mandatory parameters (key and url or html) for the html to pdf conversion. For the full list of optional parameters, take a look at SelectPdf HTML To PDF API – SaaS page. Using the API optional parameters, you can control the page size, orientation and margins in the pdf document, the document information and security, the headers and footers and a lot more.
Hopefully these examples will help you to be on your way using the API for URL to PDF conversion in C#.