G
YouTube TikTok Games
Skip to content

Repository files navigation

ConvertAPI C# SDK for .NET

Convert Word, Excel, PowerPoint and HTML to PDF, turn PDF into Word, JPG or PNG, and extract text from, compress, merge, split or protect PDF files in C# with the ConvertAPI REST API.

NuGet version NuGet downloads Build License: MIT

Free trial: 250 conversions, no credit card. Get your API token

Quick start

Create a console app and add the package:

dotnet new console -o ConvertDemo
cd ConvertDemo
dotnet add package ConvertApi

Set your API token as an environment variable:

export CONVERTAPI_TOKEN=your-api-token      # macOS and Linux
$env:CONVERTAPI_TOKEN = "your-api-token"    # Windows PowerShell

Put a Word file named document.docx in the ConvertDemo folder. No file at hand? Download our sample:

# macOS and Linux
curl -o document.docx https://cdn.convertapi.com/cara/testfiles/document.docx
# Windows PowerShell
Invoke-WebRequest https://cdn.convertapi.com/cara/testfiles/document.docx -OutFile document.docx

Replace Program.cs with this program. It uploads document.docx, converts it to PDF and saves the PDF in the current folder:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("docx", "pdf",
    new ConvertApiFileParam("document.docx"));
var files = await result.SaveFilesAsync(".");
Console.WriteLine($"Saved {files[0].FullName}");

Run dotnet run, and document.pdf appears next to document.docx. If you run it from Visual Studio, see Usage for where to put the file.

To convert a file that is already online, pass its URL as a Uri instead of a file name. ConvertAPI fetches the file itself, so nothing is uploaded from your computer:

var result = await convertApi.ConvertAsync("docx", "pdf",
    new ConvertApiFileParam(new Uri("https://cdn.convertapi.com/cara/testfiles/document.docx")));
  • .NET 10 without a project: save the program as convert.cs in the folder that holds document.docx, add #:package ConvertApi@* as its first line, and run dotnet run convert.cs.
  • .NET Framework 4.6.2 or later: install with Install-Package ConvertApi, add using System; and using System.Threading.Tasks;, and put the other lines inside static async Task Main(), because C# 7.3 has no top-level statements.
  • ASP.NET Core: keep the token in user secrets with dotnet user-secrets init and dotnet user-secrets set ConvertApi:Token your-api-token, then create the client with new ConvertApi(builder.Configuration["ConvertApi:Token"]).

Tasks

Each task links to its C# code in this README and, where there is one, to a complete example project.

Task Example project
Convert Word (DOCX) to PDF ConvertDocxToPdf, ConvertWordToPdfAndPng
Convert HTML to PDF: a file, a string or a web page ConvertHtmlToPdf, FromStreamToStream, ConvertUrlToPdf
Convert Excel (XLSX) to PDF ConvertExcelToPdf
Convert PDF to Word (DOCX) ConvertPdfToDocx
Convert PDF to JPG or PNG CreatePdfThumbnail
Extract text from PDF ExtractTextFromPdf
OCR a scanned PDF to make it searchable OcrPdf
Compress PDF CompressPdf
Convert HTML to Word (DOCX) ConvertHtmlToDocx
Convert PowerPoint (PPTX) to PDF ConvertRemoteFile
Convert an image to PDF
Combine images into one PDF
Convert a text file (TXT) to PDF
Convert HEIC photos to JPG
Take a screenshot of a web page
Convert PDF, Word, PowerPoint, Excel or HTML to Markdown, and Markdown to PDF
Convert PDF to PowerPoint (PPTX) ConvertPdfToPptx
Convert an eBook (EPUB) to PDF
Convert an email (EML, MSG) to PDF
Merge PDF files MergeWordDocsToPdf, SplitAndMergePdf
Split a PDF SplitPDF
Rotate PDF pages
Delete PDF pages
Add a watermark to a PDF WatermarkPdf
Flatten a PDF
Repair a PDF
Rasterize a PDF
Password-protect a PDF
Remove a PDF password
Redact a PDF
Convert PDF to PDF/A ConvertPdfToPdfA
Make a PDF accessible (PDF/UA)
Read PDF metadata
Remove PDF metadata
Extract tables from PDF to Excel ConvertPdfToXlsx
Extract data from invoices and other documents with AI
Extract images from PDF
Extract PDF form data
Read email metadata: sender, recipients, subject and attachments
Extract email attachments
Generate a document from a template
Update a Word table of contents
Compare Word documents
Create a ZIP archive Workflow
Save, stream and delete result files DeleteFiles
Handle errors and retries ExceptionHandling, HandleRetry
Check your remaining conversions RetrieveUserInformation

For every supported format and conversion, see the ConvertAPI API reference.

Usage

The conversion snippets below are complete programs: paste one into Program.cs, put the input file in the project folder, and run dotnet run. Results are saved in the output folder. Visual Studio runs the program in the working directory set in the project's debug launch profile; by default that is the build output folder, such as bin\Debug\net8.0. Put the input file there, or use its full path. The output folder is created there too.

Set the API token

Every request needs an API token. Get your API token: new users start a free trial, and existing customers who sign in land on their API tokens.

Keep the token out of your source code. The snippets read it from the CONVERTAPI_TOKEN environment variable:

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));

From version 3.3.0, new ConvertApi() reads CONVERTAPI_TOKEN by itself. A token you pass in code always comes first. If neither is set, the first request throws a ConvertApiException with status 401 before anything is uploaded.

Set the conversion location (optional)

By default, each request goes to the nearest ConvertAPI server. To keep files in one region, for example in the EU, set the API address once, before the first conversion. All addresses are listed in server locations.

ConvertApi.ApiBaseUri = "https://eu-v2.convertapi.com";

Convert Word (DOCX) to PDF in C#

Convert a Word document to PDF. For a DOC file, keep "docx" and pass the DOC file name.

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("docx", "pdf",
    new ConvertApiFileParam("document.docx"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

The PDF is saved as output/document.pdf. For plain text or HTML, use "txt" or "html" in place of "pdf".

Example project: ConvertDocxToPdf

Convert HTML to PDF in C#

Convert an HTML file to PDF. Only the HTML file is uploaded, so link images and stylesheets by absolute URL or put them inline.

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("html", "pdf",
    new ConvertApiFileParam("page.html"),
    new ConvertApiParam("PageSize", "a4"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Convert an HTML string, such as an invoice your app builds, to PDF:

using System.Text;
using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var html = "<h1>Invoice 1001</h1><p>Total: 99.00 USD</p>";
var result = await convertApi.ConvertAsync("html", "pdf",
    new ConvertApiFileParam(new MemoryStream(Encoding.UTF8.GetBytes(html)), "invoice.html"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Convert a web page to PDF by its URL:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("html", "pdf",
    new ConvertApiParam("Url", "https://www.example.com"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Example projects: ConvertHtmlToPdf for an HTML file and an HTML string, ConvertUrlToPdf for a web page

Convert Excel to PDF in C#

Convert an Excel workbook (XLSX or XLS) to PDF:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("xlsx", "pdf",
    new ConvertApiFileParam("spreadsheet.xlsx"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

To save each worksheet as a CSV file, use "csv" in place of "pdf".

Example project: ConvertExcelToPdf

Convert PDF to Word in C#

Convert a PDF to an editable Word document (DOCX):

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "docx",
    new ConvertApiFileParam("document.pdf"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Convert PDF to JPG or PNG in C#

Convert every page of a PDF to a JPG image. For PNG images, use "png" in place of "jpg".

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "jpg",
    new ConvertApiFileParam("document.pdf"),
    new ConvertApiParam("ImageResolution", 150));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Each page becomes one image: document.jpg for the first page, then document-2.jpg, document-3.jpg and so on. To make a thumbnail of the first page, see additional conversion parameters.

Extract text from PDF in C#

Extract the text of a PDF into a string. Scanned pages are read with OCR when needed.

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "txt",
    new ConvertApiFileParam("document.pdf"));
using var reader = new StreamReader(await result.Files[0].FileStreamAsync());
var text = await reader.ReadToEndAsync();
Console.WriteLine(text);

Example project: ExtractTextFromPdf

OCR a scanned PDF in C#

Make a scanned PDF searchable. OCR adds an invisible text layer, so the text can be found, selected and copied; pages that already have text are skipped. OcrLanguage is the language of the text, such as de or es. The PDF OCR page lists all languages.

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "ocr",
    new ConvertApiFileParam("scanned.pdf"),
    new ConvertApiParam("OcrLanguage", "en"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

The searchable PDF is saved as output/scanned.pdf. If text is missed, for example in tables, low-quality scans, photos or small print, add new ConvertApiParam("OcrQuality", "enhanced"): it is slower but reads more.

Example project: OcrPdf

Compress PDF in C#

Make a PDF smaller. The Preset parameter accepts lossless, text, archive, web, ebook and printer.

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "compress",
    new ConvertApiFileParam("document.pdf"),
    new ConvertApiParam("Preset", "web"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Example project: CompressPdf

Convert HTML to DOCX in C#

Convert an HTML file to an editable Word document:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("html", "docx",
    new ConvertApiFileParam("page.html"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Example project: ConvertHtmlToDocx

More conversions and PDF tools

Every other format pair works the same way: pass its source and target format to ConvertAsync. All formats and conversions are listed in the API reference.

PowerPoint to PDF

Convert a PowerPoint presentation (PPTX or PPT) to PDF:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pptx", "pdf",
    new ConvertApiFileParam("presentation.pptx"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Image to PDF

Convert a JPG image to PDF:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("jpg", "pdf",
    new ConvertApiFileParam("image.jpg"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

PNG, TIFF, GIF, HEIC and WEBP images work the same way with "png", "tiff", "gif", "heic" or "webp" in place of "jpg"; "tiff" also takes TIF files.

Combine images into one PDF

Combine several images, such as scanned pages or photos, into one PDF with one page per image, in the order you pass them. Here every page is A4:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("images", "pdf",
    new ConvertApiFileParam("Files", "page1.jpg"),
    new ConvertApiFileParam("Files", "page2.jpg"),
    new ConvertApiParam("PageSize", "a4"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

The PDF takes the name of the first image: output/page1.pdf. All pages get the same size and orientation; PageOrientation sets portrait or landscape.

Text to PDF

Convert a plain text file to PDF. FontName, FontSize and PageSize change the layout.

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("txt", "pdf",
    new ConvertApiFileParam("notes.txt"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

HEIC to JPG

Convert a HEIC photo, the format iPhones save, to JPG. For PNG, use "png" in place of "jpg".

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("heic", "jpg",
    new ConvertApiFileParam("photo.heic"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Web page screenshot

Take a screenshot of a whole web page as a PNG image. For JPG, use "jpg" in place of "png".

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("html", "png",
    new ConvertApiParam("Url", "https://cdn.convertapi.com/public/files/demo"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

The image is named after the site: output/cdn_convertapi_com.png.

Markdown conversion

Convert a PDF to Markdown, for example to feed it to an LLM or a search index. Word, PowerPoint, Excel and HTML files work the same way with "docx", "pptx", "xlsx" or "html" in place of "pdf".

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "md",
    new ConvertApiFileParam("document.pdf"),
    new ConvertApiParam("Images", "remove"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Images set to remove keeps the Markdown compact by replacing images with their alt text. Without it, images are embedded as base64 data; describe replaces each image with a description written by AI.

Convert a Markdown file to PDF:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("md", "pdf",
    new ConvertApiFileParam("document.md"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

PDF to PowerPoint

Convert a PDF to a PowerPoint presentation (PPTX):

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "pptx",
    new ConvertApiFileParam("document.pdf"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

eBook conversion

Convert an EPUB eBook to PDF:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("epub", "pdf",
    new ConvertApiFileParam("book.epub"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Email conversion

Convert an EML email to PDF. For an Outlook MSG file, keep "eml" and pass the MSG file name.

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("eml", "pdf",
    new ConvertApiFileParam("email.eml"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Merge documents

Merge several PDF files into one PDF:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "merge",
    new ConvertApiFileParam("first.pdf"),
    new ConvertApiFileParam("second.pdf"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Split PDF

Split a PDF into one file per page:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "split",
    new ConvertApiFileParam("document.pdf"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Rotate pages

Rotate the pages of a PDF by 90 degrees:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "rotate",
    new ConvertApiFileParam("document.pdf"),
    new ConvertApiParam("Angle", 90));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Delete pages

Delete pages 2 and 4 from a PDF:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "delete-pages",
    new ConvertApiFileParam("document.pdf"),
    new ConvertApiParam("PageRange", "2,4"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Add watermark

Add a text watermark to a PDF:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "text-watermark",
    new ConvertApiFileParam("document.pdf"),
    new ConvertApiParam("Text", "Confidential"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Flatten PDF

Flatten a PDF and its form fields, so they can no longer be edited:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "flatten",
    new ConvertApiFileParam("form.pdf"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Repair PDF

Repair a damaged PDF:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "repair",
    new ConvertApiFileParam("damaged.pdf"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Rasterize PDF

Convert a vector PDF into a raster PDF, with every page stored as an image:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "rasterize",
    new ConvertApiFileParam("document.pdf"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Password protect PDF

Protect a PDF with a password that is needed to open it:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "protect",
    new ConvertApiFileParam("document.pdf"),
    new ConvertApiParam("UserPassword", "secure123"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Remove PDF password

Remove the password from a protected PDF:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "unprotect",
    new ConvertApiFileParam("protected.pdf"),
    new ConvertApiParam("Password", "secure123"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Redact PDF

Find and redact sensitive data in a PDF with AI, here with the gdpr preset:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "redact",
    new ConvertApiFileParam("document.pdf"),
    new ConvertApiParam("Preset", "gdpr"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Convert to PDF/A

Convert a PDF to PDF/A-2b for long-term archiving:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "pdfa",
    new ConvertApiFileParam("document.pdf"),
    new ConvertApiParam("PdfaVersion", "pdfA2b"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Make a PDF accessible (PDF/UA)

Convert a PDF to PDF/UA, the standard for accessible PDF files that screen readers can navigate. The result is a tagged PDF marked as PDF/UA:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "pdfua",
    new ConvertApiFileParam("document.pdf"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Read PDF metadata

Read the title, subject, author, keywords, producer, creation and modification dates and page count of a PDF as JSON:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "meta",
    new ConvertApiFileParam("document.pdf"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

The JSON is saved as output/document.json.

Remove metadata

Remove the title, subject, author, creator and keywords from a PDF. A space in single quotes clears a field.

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "pdf",
    new ConvertApiFileParam("document.pdf"),
    new ConvertApiParam("PdfTitle", "' '"),
    new ConvertApiParam("PdfSubject", "' '"),
    new ConvertApiParam("PdfAuthor", "' '"),
    new ConvertApiParam("PdfCreator", "' '"),
    new ConvertApiParam("PdfKeywords", "' '"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Extract tables from PDF

Extract the tables of a PDF into an Excel workbook (XLSX):

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "xlsx",
    new ConvertApiFileParam("document.pdf"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Extract data with AI

Extract structured data from a PDF with AI, such as the number, dates, totals and line items of an invoice. Besides invoice, DocumentType takes receipt, contract, identification, financial, form and manual, or auto to let the AI decide.

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "extract",
    new ConvertApiFileParam("invoice.pdf"),
    new ConvertApiParam("DocumentType", "invoice"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

The result, output/invoice.json, lists each field with its name, value and a confidence score. To choose the fields yourself, see CustomExtractionData on the AI data extraction page.

Extract images from PDF

Save the images inside a PDF as PNG files:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "extract-images",
    new ConvertApiFileParam("document.pdf"),
    new ConvertApiParam("ImageOutputFormat", "png"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Extract form data

Export the form field values of a PDF to an FDF file:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "fdf-extract",
    new ConvertApiFileParam("form.pdf"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Read email metadata

Read the sender, recipients, subject, sent time, text and HTML body, and attachment list of an EML or MSG email as JSON:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("email", "metadata",
    new ConvertApiFileParam("email.eml"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

The JSON is saved as output/email.json. To leave inline images, such as a logo in the signature, out of the attachment list, add new ConvertApiParam("IgnoreInlineAttachments", "true").

Extract email attachments

Save the attachments of an EML or MSG email:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("email", "extract",
    new ConvertApiFileParam("email.eml"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Generate document from template

Fill a Word template with JSON data and save the result as PDF. Here template.docx contains the placeholder {{name}}.

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("template", "pdf",
    new ConvertApiFileParam("template.docx"),
    new ConvertApiParam("BindingMethod", "placeholders"),
    new ConvertApiParam("JsonPayload", "[{\"Name\": \"name\", \"Value\": \"John\", \"Type\": \"string\"}]"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Update a Word table of contents

Update the table of contents, its page numbers and the cross-references of a Word document, for example after your code has filled in a template:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("docx", "docx",
    new ConvertApiFileParam("report.docx"),
    new ConvertApiParam("UpdateTableOfContents", "true"),
    new ConvertApiParam("UpdateReferences", "true"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Compare documents

Compare two Word documents. The result is a DOCX that marks the differences as tracked changes.

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("docx", "compare",
    new ConvertApiFileParam("original.docx"),
    new ConvertApiFileParam("CompareFile", "revised.docx"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Create ZIP archive

Put several files into one ZIP archive:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("file", "zip",
    new ConvertApiFileParam("document.pdf"),
    new ConvertApiFileParam("document.docx"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Also available

These converters are documented, with their parameters, on their own pages:

Work with the result

ConvertAsync returns the conversion cost and the result files. Each file is a ConvertApiFile with a name, a size and a download URL. Save the files, read them as streams, and delete them from the server when you are done:

using ConvertApiDotNet;
using ConvertApiDotNet.Model;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "jpg",
    new ConvertApiFileParam("document.pdf"));

Console.WriteLine($"Conversion cost: {result.ConversionCost}");
ConvertApiFile[] files = result.Files;
foreach (var file in files)
    Console.WriteLine($"{file.FileName}: {file.FileSize} bytes");

// Save every file to a folder, or one file under a name you choose
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");
await files[0].SaveFileAsync(Path.Combine("output", "first-page.jpg"));

// Read a file as a stream, for example to upload it elsewhere
using var stream = await files[0].FileStreamAsync();

// Delete the uploaded and the result files from the server now, not after 3 hours
await result.DeleteFilesAsync();

Convert a file from a URL

Pass a Uri to convert a file that is already online, without downloading it first:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pptx", "pdf",
    new ConvertApiFileParam(new Uri("https://cdn.convertapi.com/cara/testfiles/presentation.pptx")));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Additional conversion parameters

Each conversion accepts extra parameters, listed on its page in the API reference, for example PDF to JPG. This program makes a thumbnail of the first page of a PDF that fits in 300 by 300 pixels:

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var result = await convertApi.ConvertAsync("pdf", "jpg",
    new ConvertApiFileParam("document.pdf"),
    new ConvertApiParam("PageRange", "1"),
    new ConvertApiParam("ImageWidth", 300),
    new ConvertApiParam("ImageHeight", 300),
    new ConvertApiParam("FitToSize", "true"));
Directory.CreateDirectory("output");
await result.SaveFilesAsync("output");

Handle errors

When the API returns an error, the SDK throws a ConvertApiException. Its StatusCode says what went wrong:

  • 401 Unauthorized: the API token is missing or invalid. Check CONVERTAPI_TOKEN, or get your token.
  • 403 Forbidden: the account has no conversions left, or it is suspended.
  • 503 Service Unavailable: the service is temporarily unavailable. Wait a few seconds and retry, as the HandleRetry example does.

For other codes, Response holds the error message from the API. If CONVERTAPI_TOKEN is not set, new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN")) throws an ArgumentNullException before any request is sent.

From version 3.3.0, the message of a 401 or 403 also says what to do and links to the page that helps, and SaveFileAsync, SaveFilesAsync and FileStreamAsync throw a ConvertApiException when a result cannot be downloaded, instead of saving the error page as the file.

using ConvertApiDotNet;
using ConvertApiDotNet.Exceptions;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
try
{
    var result = await convertApi.ConvertAsync("docx", "pdf",
        new ConvertApiFileParam("document.docx"));
    Directory.CreateDirectory("output");
    await result.SaveFilesAsync("output");
}
catch (ConvertApiException e)
{
    Console.WriteLine($"ConvertAPI returned {(int)e.StatusCode} {e.StatusCode}: {e.Response}");
}

User information

Check how many conversions your account has used. See user information for all fields.

using ConvertApiDotNet;

var convertApi = new ConvertApi(Environment.GetEnvironmentVariable("CONVERTAPI_TOKEN"));
var user = await convertApi.GetUserAsync();
Console.WriteLine($"Conversions used: {user.ConversionsConsumed} of {user.ConversionsTotal}");

More examples

Each example is a complete console project in the Examples folder of this repository. To run one, set the CONVERTAPI_TOKEN environment variable and follow the steps in Examples/README.md.

Compatibility

The package targets .NET Standard 2.0, so it runs on:

  • .NET 5 to .NET 10 and later, and .NET Core 2.0 or later
  • .NET Framework 4.6.2 or later (4.7.2 or later is recommended, because older versions cannot use .NET Standard 2.0 packages reliably)
  • Libraries that target .NET Standard 2.0 or later
  • Windows, Linux and macOS, including Azure App Service and Azure Functions
  • Console, web and desktop applications

Security, data and support

License

The ConvertAPI .NET library is licensed under the MIT license. See the LICENSE file for more information.