How to Summarize PDF Text in .NET with C#

Learn how to summarize PDF text with pdfRest Summarize PDF API using C#.
Share this page

Summarize PDF Content with C# and .NET

The pdfRest Summarize PDF API Tool lets a .NET application condense a long PDF, Markdown file, or plain-text file into a shorter, structured result. It handles PDF text extraction, structure-aware conversion, and AI summarization behind one endpoint, reducing the amount of document-processing and model-integration code your team must build and maintain. Common uses include report previews, document-management dashboards, research intake, support knowledge bases, and workflows that need a quick overview before a person opens the source document.

The /summarized-pdf-text endpoint accepts an uploaded file or a pdfRest resource ID. This example uses a multipart upload, which works well when the PDF begins on the local file system. If another pdfRest API Tool produced the input, pass its output ID instead to avoid transferring the intermediate file again.

For example, a .NET document-review portal can generate a short overview when a lengthy vendor proposal is uploaded, allowing a reviewer to identify its main topics before opening the full file. The portal can display the summary beside the source PDF while preserving the original document as the authority for exact requirements and terms.

C# Summarize PDF Code Example

The sample reads the PDF path from the command line and the API key from the PDFREST_API_KEY environment variable. It also supports PDFREST_URL, allowing the application to use the US Cloud API by default or the EU service when required.

/*
 * What this sample does:
 * - Summarizes PDF content via multipart/form-data.
 * - Routed from Program.cs as: `dotnet run -- summarized-pdf-text-multipart `.
 *
 * Setup (environment):
 * - Copy .env.example to .env
 * - Set PDFREST_API_KEY=your_api_key_here
 * - Optional: set PDFREST_URL to override the API region. For EU/GDPR compliance and proximity, use:
 *     PDFREST_URL=https://eu-api.pdfrest.com
 *   For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
 *
 * Usage:
 *   dotnet run -- summarized-pdf-text-multipart /path/to/input.pdf
 *
 * Output:
 * - Prints the JSON response. Validation errors (args/env) exit non-zero.
 */

using System.Text;

namespace Samples.EndpointExamples.MultipartPayload
{
    public static class SummarizedPdfText
    {
        public static async Task Execute(string[] args)
        {
            if (args == null || args.Length < 1)
            {
                Console.Error.WriteLine("summarized-pdf-text-multipart requires ");
                Environment.Exit(1);
                return;
            }
            var inputPath = args[0];
            if (!File.Exists(inputPath))
            {
                Console.Error.WriteLine($"File not found: {inputPath}");
                Environment.Exit(1);
                return;
            }
            var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
            if (string.IsNullOrWhiteSpace(apiKey))
            {
                Console.Error.WriteLine("Missing required environment variable: PDFREST_API_KEY");
                Environment.Exit(1);
                return;
            }
            var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";

            using (var httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) })
            using (var request = new HttpRequestMessage(HttpMethod.Post, "summarized-pdf-text"))
            {
                request.Headers.TryAddWithoutValidation("Api-Key", apiKey);
                request.Headers.Accept.Add(new("application/json"));
                var multipartContent = new MultipartFormDataContent();

                var byteArray = File.ReadAllBytes(inputPath);
                var byteAryContent = new ByteArrayContent(byteArray);
                multipartContent.Add(byteAryContent, "file", Path.GetFileName(inputPath));
                byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/octet-stream");

                var byteArrayOption = new ByteArrayContent(Encoding.UTF8.GetBytes("100"));
                multipartContent.Add(byteArrayOption, "target_word_count");

                request.Content = multipartContent;
                var response = await httpClient.SendAsync(request);
                var apiResult = await response.Content.ReadAsStringAsync();

                Console.WriteLine("API response received.");
                Console.WriteLine(apiResult);
            }
        }
    }
}

Source: pdfRest Summarize PDF multipart C# sample on GitHub

Build and Send the Multipart Request

The code first validates that an input path was supplied, confirms that the file exists, and checks for an API key. It then creates an HttpClient with the selected base URL and an HttpRequestMessage for the summarized-pdf-text route.

MultipartFormDataContent carries both the file and the summarization options. The sample adds the PDF as a ByteArrayContent part named file and sets target_word_count to 100. That count is approximate rather than guaranteed; the default is currently 400 words when the parameter is omitted.

For services that process large files or many concurrent requests, consider streaming the file rather than loading every byte into memory, reuse HttpClient through IHttpClientFactory, and pass a CancellationToken with an application-appropriate timeout. These changes are not necessary to understand the sample, but they are important when adapting it to a production .NET service.

Customize the Summary for the Application

The endpoint offers several controls beyond length, allowing one integration to serve different parts of an application:

  • summary_format can return an overview, highlights, an abstract, bullet points, a numbered list, a table of contents, an outline, questions and answers, or action items.
  • pages limits summarization to selected page ranges.
  • output_format controls whether the returned text uses Markdown or plain text.
  • output_type controls whether the result is included in JSON or provided as an output file.

Add these values as additional multipart fields using the same pattern as target_word_count. Choose them according to how the consuming application will use the output rather than applying one format to every document. Because the API returns application-ready text or a file in the requested structure, you can minimize custom prompt construction and post-processing code.

Validate Successful and Failed Responses

The sample prints the response body for visibility. A production integration should check response.IsSuccessStatusCode before treating the body as a successful result, preserve useful API error details without exposing credentials, and validate that the response contains the field expected for the selected output_type.

AI-generated summaries should be treated as aids to review, not replacements for exact source language in legal, medical, financial, or other high-stakes work. Test different document structures and compare important statements with the original PDF. Your submitted files and data are never used to train AI models.

See the Summarize PDF API reference for the current request and response schemas. A JSON-payload C# example is also available when the input already exists as a server-side resource.

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