Skip to content

Instantly share code, notes, and snippets.

@html2pdf-rocket
Last active February 28, 2025 13:38
Show Gist options
  • Save html2pdf-rocket/1d1bd00b6d788f52a27156011eb53db3 to your computer and use it in GitHub Desktop.
Save html2pdf-rocket/1d1bd00b6d788f52a27156011eb53db3 to your computer and use it in GitHub Desktop.
How to stream a PDF directly to the end user with ASP.NET C# MVC
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
public class PdfController : Controller
{
private static readonly HttpClient httpClient = new HttpClient();
public async Task<IActionResult> Run()
{
string apiKey = "YOUR-API-KEY";
string value = "http://www.google.com"; // URL or HTML string
var formData = new Dictionary<string, string>
{
{ "apikey", apiKey },
{ "value", value }
};
using (var content = new FormUrlEncodedContent(formData))
{
HttpResponseMessage response = await httpClient.PostAsync("https://api.html2pdfrocket.com/pdf", content);
response.EnsureSuccessStatusCode();
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
MemoryStream ms = new MemoryStream(pdfBytes);
return File(ms, "application/pdf", "myfilename.pdf");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment