How to Convert Plain Text to PDF in .NET with C#

Generate styled, tagged PDFs from plain text in .NET with C# and choose preserved-line or reflowed layout.
Share this page

This .NET walkthrough shows how C# can convert a plain text file with the pdfRest Convert to PDF API Tool. It sends the source with structured settings for preserved lines, tagged output, page geometry, and text appearance.

Why Convert Plain Text to PDF in .NET with C#?

Many .NET environments integrate with manufacturing, financial, or mainframe systems that still emit fixed-format text. Those reports may contain valuable operational history, but distributing them as loose text files makes printing, review, and records retention inconsistent.

A manufacturing application, for example, may receive a production-run summary listing machine identifiers, quantities, exceptions, and operator messages. Converting the export to PDF gives supervisors a stable report for the run record. Preserved line handling keeps each entry in order, and choosing a monospaced font can maintain fixed-width alignment when the source depends on columns.

C# applications can switch to reflow mode for notes and narrative summaries that should wrap naturally across the page. The same endpoint then handles two distinct text layouts while applying repeatable margins, metadata, typography, and document structure.

C# Code Example for Converting Plain Text to PDF

/*
 * What this sample does:
 * - Converts plain text input to PDF through the /pdf endpoint.
 *
 * Setup (environment):
 * - Set PDFREST_API_KEY=your_api_key_here
 * - Optional: set PDFREST_URL to override the API region.
 *
 * Usage:
 *   dotnet run -- pdf-from-text-multipart 
 */
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Text;

namespace Samples.EndpointExamples.MultipartPayload;

public static class PdfFromText
{
    public static async Task Execute(string[] args)
    {
        var inputPath = args.Length > 0 ? args[0] : "/path/to/sample.txt";
        var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
        if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Missing PDFREST_API_KEY");
        var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";
        using var client = new HttpClient { BaseAddress = new Uri(baseUrl) };
        client.DefaultRequestHeaders.TryAddWithoutValidation("Api-Key", apiKey);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var options = JObject.Parse(@"{""title"":""Structured Content Sample"",""language"":""en-US"",""enable_tagging"":true,""page_setup"":{""size"":""Letter"",""orientation"":""portrait"",""margin"":{""top"":36,""right"":42,""bottom"":36,""left"":42}},""style"":{""font"":""Arial"",""heading_font"":""Arial"",""code_font"":""Courier"",""text_size"":11,""text_color_rgb"":[34,34,34],""heading_scale"":1.35,""table"":{""column_width_weights"":[2,3,2],""keep_header_with_first_row"":true,""repeat_headers_on_overflow"":true,""show_borders"":true,""border_width"":0.75,""border_color_rgb"":[180,188,200],""header_fill_color_rgb"":[33,64,98],""header_text_color_rgb"":[255,255,255],""row_fill_color_rgb"":[250,250,252],""alternate_row_fill_color_rgb"":[235,240,246],""cell_padding"":{""top"":6,""right"":8,""bottom"":6,""left"":8}}},""plain_text"":{""line_handling"":""preserve""}}");
        using var form = new MultipartFormDataContent();
        var inputContent = new ByteArrayContent(await File.ReadAllBytesAsync(inputPath));
        inputContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        form.Add(inputContent, "file", Path.GetFileName(inputPath));
        form.Add(new StringContent(options.ToString()), "structured_text_options");
        var response = await client.PostAsync("pdf", form);
        var result = await response.Content.ReadAsStringAsync();
        Console.WriteLine(result);
        if (!response.IsSuccessStatusCode) Environment.ExitCode = 1;
    }
}

Source: View the sample on GitHub

Breaking Down the Code

The C# Plain Text sample uses the framework HttpClient APIs and Newtonsoft JSON types for structured_text_options. A project adopting this code must retain the Newtonsoft.Json package reference used by the samples repository.

using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Text;
        using var client = new HttpClient { BaseAddress = new Uri(baseUrl) };
        using var form = new MultipartFormDataContent();

The .NET endpoint block shows which regional service receives this Plain Text request:

        if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Missing PDFREST_API_KEY");
        var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";
        using var client = new HttpClient { BaseAddress = new Uri(baseUrl) };
        client.DefaultRequestHeaders.TryAddWithoutValidation("Api-Key", apiKey);

C# turns the .txt source into StreamContent and preserves its filename in the multipart part. That extension directs the shared /pdf endpoint to the Plain Text converter.

    {
        var inputPath = args.Length > 0 ? args[0] : "/path/to/sample.txt";
        var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");

The Newtonsoft JObject represents pdfRest’s structured conversion settings. It defines the output title and language, explicitly enables tags, configures Letter portrait pages and margins, and carries the typography and Plain Text-related style properties used by the renderer.

plain_text
{
  "plain_text": {
    "line_handling": "preserve"
  }
}

preserve keeps every normalized source line and its spacing in a preformatted block. Windows and legacy carriage-return line endings are normalized consistently. The alternative reflow joins consecutive nonblank lines into paragraphs, using blank lines as paragraph boundaries; reflow is the default when the field is omitted. Only those two values are accepted. When horizontal alignment matters, select a monospaced body font because preserve mode retains characters and spacing but does not force a particular font.

The sample also carries style.table because the repository uses one broad structured-text profile. Plain Text does not create a table, so those table colors, borders, widths, and padding have no effect and may be omitted from a text-only integration.

For Plain Text, MultipartFormDataContent owns the source stream, serialized settings, and output field. HttpClient generates the matching multipart boundary and content type when it sends the container.

        var inputContent = new ByteArrayContent(await File.ReadAllBytesAsync(inputPath));
        inputContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        form.Add(inputContent, "file", Path.GetFileName(inputPath));
        form.Add(new StringContent(options.ToString()), "structured_text_options");
        var response = await client.PostAsync("pdf", form);
        var result = await response.Content.ReadAsStringAsync();
        Console.WriteLine(result);
        if (!response.IsSuccessStatusCode) Environment.ExitCode = 1;
    }
}

The C# client authenticates and posts the Plain Text form, then reads the response as text. Reporting both status and payload lets an integration distinguish a generated PDF resource from validation or processing errors.

        var inputContent = new ByteArrayContent(await File.ReadAllBytesAsync(inputPath));
        inputContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        form.Add(inputContent, "file", Path.GetFileName(inputPath));
        form.Add(new StringContent(options.ToString()), "structured_text_options");
        var response = await client.PostAsync("pdf", form);
        var result = await response.Content.ReadAsStringAsync();
        Console.WriteLine(result);
        if (!response.IsSuccessStatusCode) Environment.ExitCode = 1;
    }
}

Beyond the Tutorial

.NET workflows can use the same conversion for operational logs, policy text, or fixed-layout records that need consistent PDF delivery. Enabling tags exposes logical structure to compatible consumers but does not by itself demonstrate accessibility conformance.

A text-only integration may keep just the metadata, page, typography, and line-handling settings it requires. Experiment in API Lab and use the Convert to PDF reference as the authoritative option guide.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.