Menu

C# – Convert HTML to PDF using pdf.co API

There are a lot of free and paid solutions out there to create PDFs using .net core. recently I wrote a blog post, about how I used PHP to convert PDFs from HTML. Let’s see how we can use pdf.co API to convert the same HTML using C# (.net)

I wrote a small service class using RestSharp.

public class PDFGenerateService : IPDFGenerateService
{
    private readonly AppSettingsOptions _appSettings;
    private readonly string _pdfCoApiUrl;
    private readonly string _pdfCoApiKey;

    public PDFGenerateService(IOptions appSettings)
    {
        _appSettings = appSettings.Value;
        _pdfCoApiUrl = _appSettings.PDFCoApiUrl; // this is "https://api.pdf.co/"
        _pdfCoApiKey = _appSettings.PDFCoApiKey; // and my key genarated by PDF.co
    }

    public async Task<byte[]> GenerateAsync(string htmlBody)
    {
        var pdfResponse = await GetGeneratedPdfResponseAsync(htmlBody);

        return GetGeneratedPdfBytesArray(pdfResponse.Url);
    }

    private byte[] GetGeneratedPdfBytesArray(string pdfUrl)
    {
        var client = new RestClient(pdfUrl);
        RestRequest request = new RestRequest(Method.GET);

        return client.DownloadData(request);
    }

    private async Task GetGeneratedPdfResponseAsync(string htmlBody)
    {
        var client = new RestClient(_pdfCoApiUrl)
        {
            ReadWriteTimeout = 300000; // probabaly wont need it ;)
        };
        client.Timeout = 300000; // probabaly wont need it ;)

        var request = new RestRequest("/v1/pdf/convert/from/html", Method.POST);
        request.AddHeader("x-api-key", _pdfCoApiKey);
        request.AddHeader("Content-Type", "application/json");
        request.AddJsonBody(new { Html = htmlBody, Name = $"{Guid.NewGuid()}.pdf" });
        var response = await client.ExecuteAsync(request);

        return response.Data;
    }
}

there are many configurations you can pass as part of the POST request to generate the PDF.

PDF.co will give you 1000 credits to play around and you can get a matching subscription for your needs.

Disclaimer: pdf.co did not sponsor me to write this post

 

Leave a comment