Skip to content

Commit

Permalink
Add PdfController for PDF generation
Browse files Browse the repository at this point in the history
  • Loading branch information
yorickdewid committed Sep 11, 2024
1 parent b0e21b2 commit 4e7fe27
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/FunderMaps.WebApi/Controllers/PdfController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System.Text;
using System.Text.Json;
using FunderMaps.Core.Controllers;
using Microsoft.AspNetCore.Mvc;

namespace FunderMaps.WebApi.Controllers;

// TODO: This is a makeshift controller to demonstrate the PDF generation.
public class PdfController(IConfiguration configuration) : FunderMapsController
{
[HttpGet("api/pdf/{id}")]
public async Task<IActionResult> GetAsync(string id)
{
var httpClient = new HttpClient
{
Timeout = TimeSpan.FromMinutes(5),
DefaultRequestHeaders =
{
{ "x-api-key", configuration.GetSection("PdfCo:ApiKey").Value}
}
};

try
{
string jsonBody = JsonSerializer.Serialize(new
{
url = $"https://whale-app-nm9uv.ondigitalocean.app/{id}",
name = $"{id}.pdf",
paperSize = "A4",
async = false,
});
using var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

HttpResponseMessage response = await httpClient.PostAsync("https://api.pdf.co/v1/pdf/convert/from/url", content);
response.EnsureSuccessStatusCode(); // Throw an exception if the request failed

var jsonResponse = await response.Content.ReadAsStringAsync();
var url = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonResponse)["url"];

Check warning on line 38 in src/FunderMaps.WebApi/Controllers/PdfController.cs

View workflow job for this annotation

GitHub Actions / Build & Test

Dereference of a possibly null reference.

Check warning on line 38 in src/FunderMaps.WebApi/Controllers/PdfController.cs

View workflow job for this annotation

GitHub Actions / Build & Test

Dereference of a possibly null reference.

return Ok(url);
}
catch (HttpRequestException ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}

httpClient.Dispose();

return Ok();
}
}

0 comments on commit 4e7fe27

Please sign in to comment.