Base64 to PDF in C# (.NET)
In the .NET ecosystem, converting Base64 strings to PDF files is a trivial task thanks to the robust System.Convert and System.IO classes. This is frequently used in backend services and desktop applications.
C# Code Example
The following C# code demonstrates how to decode a Base64 string and write it as a PDF file to the disk.
Program.cs
using System;
using System.IO;
public class Base64ToPdfConverter
{
public static void main()
{
// Your Base64 encoded PDF string
string base64String = "JVBERi0xLjQKJ...";
try
{
// 1. Convert Base64 string to byte array
byte[] pdfBytes = Convert.FromBase64String(base64String);
// 2. Define the path where the PDF will be saved
string filePath = "output.pdf";
// 3. Write all bytes to a file
File.WriteAllBytes(filePath, pdfBytes);
Console.WriteLine("PDF file saved successfully at: " + Path.GetFullPath(filePath));
}
catch (FormatException)
{
Console.WriteLine("Error: Invalid Base64 string format.");
}
catch (IOException ex)
{
Console.WriteLine("Error writing to file: " + ex.Message);
}
}
} Key Methods Explained
- Convert.FromBase64String(): This is the core method that converts the string representation of a base-64 encoded value to an equivalent 8-bit unsigned integer array.
- File.WriteAllBytes(): This convenient method creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
- Path.GetFullPath(): Useful for verifying exactly where your file was saved on the system.
Modern .NET (ASP.NET Core)
If you are working in an ASP.NET Core Web API, you might want to return the PDF directly to the browser. In that case, you can use the File() method in your controller:
PdfController.cs
[HttpGet("download")]
public IActionResult DownloadPdf()
{
string base64String = "...";
byte[] bytes = Convert.FromBase64String(base64String);
return File(bytes, "application/pdf", "document.pdf");
} Need an instant solution?
Use our secure online converter to decode Base64 to PDF in seconds, no coding required.
Back to Online Tool