Using RestSharp in CSharp
RestSharp is a popular third-party library that simplifies making HTTP requests and handling responses in .NET applications. It provides an intuitive and easy-to-use API for interacting with RESTful web services, enabling developers to perform common HTTP operations such as GET, POST, PUT, DELETE, and more. RestSharp abstracts away the complexities of HTTP communication, streamlining the process of consuming web APIs and processing their responses.
We've implemented a code sample that you can re-use to convert your HTML documents to PDF, JPG, PNG or WEBP using PDFShift and CSharp:
using RestSharp;
using System;
using System.IO;
using Newtonsoft.Json;
using RestSharp.Authenticators;
public class Conversion
{
private RestClient Client;
string api_key = "sk_XXXXXXXXXXXXXX";
public Conversion(string api_key, string endpoint = "pdf")
{
if (! (new[] {"pdf", "png", "jpg", "webp"}.Contains(endpoint)))
{
throw new ArgumentException("Invalid endpoint");
}
Client = new RestClient("https://api.pdfshift.io/v3/convert/" + endpoint)
Client.Authenticator = new HttpBasicAuthenticator("api", api_key);
}
public byte[] Convert(dynamic parameters)
{
RestRequest Request = new RestRequest(Method.POST);
Request.AddJsonBody(parameters);
var response = Client.Execute(Request);
if(response.IsSuccessful)
{
if (parameters.ContainsKey("filename") || parameters.ContainsKey("webhook"))
{
return System.Text.Encoding.Default.GetBytes(response.Content);
}
return response.RawBytes;
}
else
{
throw new Exception(response.ErrorMessage);
}
}
}
Here's how you can use the above code:
We've tested this code with the latest version of RestSharp and it's ready to be used in your project.
But if you were to encounter any bugs or issues while running it (or if you want to suggest changes to improve the code), please contact us and we'll be happy to help you out.