C# SDK
The official C# SDK for PDFik enables you to integrate PDF generation into your .NET applications with minimal effort.
It targets netstandard2.0 (covers .NET Framework 4.6.2+, .NET Core 2.0+, Mono) and net8.0, with System.Text.Json as its only dependency. Every method exists as a Task-based ...Async variant and a blocking twin; one PdfikClient instance is thread-safe and meant to be reused.
Installation
dotnet add package Pdfik
Or in your project file:
<PackageReference Include="Pdfik" Version="0.3.0" />
Quick Start
One call, one file
Every creation method has a …File sibling (plus a …FileAsync twin) that
sends wait: true and returns the finished bytes — no polling, no download step:
using Pdfik;
using var client = new PdfikClient("sk_live_...");
byte[] pdf = client.UrlToPdfFile("https://example.com");
File.WriteAllBytes("page.pdf", pdf);
The request is held for up to 45 seconds. Past that the job is cancelled and
not charged (PdfikException with code SYNC_TIMEOUT — the SDK never
resends it); a failed render throws with the job's own error code. For long
renders and batches, use the asynchronous flow below.
Convert Public URL to PDF
using Pdfik;
using Pdfik.Models;
using var client = new PdfikClient("sk_live_..."); // Retrieve from your dashboard
// Configure PDF styling and margins
var options = new PdfOptions
{
Format = PaperFormat.A4,
Landscape = false,
PrintBackground = true,
Margin = new MarginOptions { Top = "10mm", Right = "10mm", Bottom = "10mm", Left = "10mm" },
};
// 1. Submit the URL to be rendered
JobCreatedResponse job = await client.UrlToPdfAsync("https://example.com", options);
Console.WriteLine($"Job created: {job.JobId}. Processing...");
// 2. Poll until the job completes
JobStatusResponse result = await client.WaitForJobAsync(job.JobId);
Console.WriteLine($"Job finished! Pages: {result.PagesCount}");
// 3. Download the PDF bytes
byte[] pdfBytes = await client.DownloadAsync(job.JobId);
File.WriteAllBytes("output.pdf", pdfBytes);
Console.WriteLine("PDF saved to output.pdf");
Convert HTML to PDF
using Pdfik;
using var client = new PdfikClient("sk_live_...");
var job = await client.HtmlToPdfAsync("<h1>Hello World</h1><p>Sent from the C# SDK</p>");
Console.WriteLine($"Job created: {job.JobId}");
await client.WaitForJobAsync(job.JobId);
byte[] pdfBytes = await client.DownloadAsync(job.JobId);
Console.WriteLine($"Downloaded {pdfBytes.Length} bytes.");
Blocking twins exist for every call (client.UrlToPdf(...), client.WaitForJob(...), client.Download(...)), so the SDK fits codebases without async plumbing too.
Get the direct download URL
Get the direct API download URL for the generated PDF (requires the "X-API-Key" header to download):
JobFileResponse fileInfo = client.GetFileUrl(job.JobId);
Console.WriteLine($"Direct Download URL: {fileInfo.DownloadUrl}");
Check your key and usage
GetAccountAsync() / GetAccount() returns the plan, the current quota window, what has been used in it and the
limits (GET /account) — without creating a job or charging anything:
var account = await client.GetAccountAsync();
Console.WriteLine($"{account.Plan} {account.Usage.Documents} of {account.Limits.Documents}, resets {account.Window.End}");
Every request the SDK sends carries X-PDFik-Client: sdk-csharp/<version>. Needs Pdfik 0.3.0 or newer.
E-invoicing (Factur-X)
EinvoiceToPdf turns a UN/CEFACT Cross-Industry Invoice XML (the Factur-X payload, UTF-8, up to 1 MB) into a Factur-X / ZUGFeRD hybrid e-invoice: a PDF/A-3 file with the XML embedded as factur-x.xml. It returns the same JobCreatedResponse as the other methods, so the job continues through WaitForJob and Download. Available on every plan, Free included — the output is the same clean PDF/A-3. Endpoint reference: E-Invoicing.
using Pdfik;
using Pdfik.Models;
string xml = File.ReadAllText("invoice.xml");
var request = new EInvoiceToPdfRequest(xml, "en16931") // minimum | basicwl | basic | en16931 (default) | extended
{
WebhookUrl = "https://yourserver.com/webhooks/pdf", // optional
};
// Second argument: optional Idempotency-Key (omit it to let the SDK generate one)
JobCreatedResponse job = await client.EinvoiceToPdfAsync(request, "invoice-2026-001");
await client.WaitForJobAsync(job.JobId); // polls until done (throws on failure)
File.WriteAllBytes("invoice.pdf", await client.DownloadAsync(job.JobId));
The shortest forms are client.EinvoiceToPdfAsync(xml) (default template, profile en16931) and client.EinvoiceToPdfAsync(xml, "extended").
Templates: TemplateId or Template
The visual invoice is built from a block template. TemplateId (a template saved under Dashboard → E-Invoice) and Template (an inline block-template definition — the same JSON the dashboard editor produces, as a Dictionary<string, object>) are mutually exclusive; set neither to use your account's default template.
var request = new EInvoiceToPdfRequest(xml, "en16931")
{
TemplateId = "550e8400-e29b-41d4-a716-446655440000",
};
JobCreatedResponse job = await client.EinvoiceToPdfAsync(request);
Keep your own design (the Einvoice option)
If you already render the invoice page yourself, pass an EInvoiceOptions to UrlToPdf / HtmlToPdf: the rendered page becomes the visual half, the output is normalized to PDF/A-3 and the XML is embedded as factur-x.xml. It cannot be combined with PdfOptions.UserPassword (PDF/A forbids encryption) — see Using Your Own Design.
var einvoice = new EInvoiceOptions(xml, "en16931");
JobCreatedResponse job = await client.HtmlToPdfAsync(invoiceHtml, einvoice: einvoice);
JobCreatedResponse job2 = await client.UrlToPdfAsync("https://example.com", einvoice: einvoice);
Error handling
A rejected request throws PdfikException before any quota is spent — check StatusCode and ErrorCode (ResponseBody holds the raw RFC 7807 body):
StatusCode | ErrorCode | When |
|---|---|---|
422 | EINVOICE_XML_INVALID | The XML failed parsing, the profile check or the XSD — einvoice-xml-invalid |
422 | EINVOICE_OPTIONS_CONFLICT | TemplateId together with Template, or Einvoice together with PdfOptions.UserPassword — einvoice-options-conflict |
404 | EINVOICE_TEMPLATE_NOT_FOUND | the template id does not exist on this account — einvoice-template-not-found |
503 | NETWORK_ERROR | Thrown by the client itself, so ResponseBody is null: the request got no HTTP response, or the connection broke while the body was being read (DNS failure, refused or reset connection, TLS error, the request timeout). Unlike the rows above it is not a rejection — the job may already exist (a create whose answer broke off) and a …File render may already be charged. Every other method retries it with backoff (a resent create keeps its Idempotency-Key); the …File methods never resend. Version 0.2.0 or newer; older versions throw the same 503 with a null ErrorCode. |
try
{
await client.EinvoiceToPdfAsync(xml, "en16931");
}
catch (PdfikException e) when (e.ErrorCode == "EINVOICE_XML_INVALID")
{
Console.Error.WriteLine($"Invoice XML rejected: {e.Message}");
}
A job that fails after it was queued carries EINVOICE_FAILED in its status ErrorCode; WaitForJob throws a PdfikException with that error code. See einvoice-failed.
Markdown to PDF
MarkdownToPdf converts Markdown (CommonMark + GFM tables and strikethrough) to a PDF with a built-in print stylesheet. Raw HTML inside the Markdown is escaped, not rendered — use HtmlToPdf for full HTML control. MarkdownToPdfRequest carries the same PdfOptions (paper format, margins, header/footer, watermark, ...) plus Render, WebhookUrl, Delivery and Test, and the job continues through WaitForJob and Download. The input is limited to 100,000 characters (422); Markdown whose converted document is too large for the processing queue is rejected with 413 payload-too-large-for-queue. Available on every plan. Endpoint reference: Markdown to PDF.
// Simplest form
var job = await client.MarkdownToPdfAsync("# Report\n\n| Item | Price |\n| --- | --- |\n| Render | $0.01 |");
// Full control via the request object (+ optional Idempotency-Key)
var request = new MarkdownToPdfRequest("# Report\n\nHello **world**")
{
Options = new PdfOptions { Format = PaperFormat.A4 },
};
job = await client.MarkdownToPdfAsync(request, "report-2026-001");
await client.WaitForJobAsync(job.JobId);
byte[] pdfBytes = await client.DownloadAsync(job.JobId);
Screenshots
UrlToImage and HtmlToImage capture a page as a PNG (default) or JPEG instead of a PDF. The request objects UrlToImageRequest / HtmlToImageRequest take an ImageOptions:
| Property | Type | Default | Meaning |
|---|---|---|---|
Format | ImageFormat? | Png | ImageFormat.Png or ImageFormat.Jpeg. |
FullPage | bool? | false | Capture the whole scrollable page instead of just the visible area. With true the height follows the real page and is clipped at 8,192 px — a ceiling, not a target, so a 2,000 px page still gives a 2,000 px image. Horizontal overflow beyond the viewport width is never captured. |
Quality | int? | — | JPEG quality 1-100; sending it with PNG is rejected with 422. |
Viewport | ImageViewport | 1024x768 | new ImageViewport(width, height) — the browser window the page opens in. You pick the size and the API captures exactly that; nothing is scaled or fitted. width 320-1920, height 320-8192; outside that range the API answers 422. Sets the image width; with FullPage = false (the default) also its height. |
Polling is identical to the PDF methods, and Download returns the raw image bytes (image/png or image/jpeg). UrlToImageRequest also accepts the Auth option (basic/bearer), exactly as UrlToPdf. Available on every plan. Endpoint reference: Screenshots.
var request = new UrlToImageRequest("https://example.com")
{
Options = new ImageOptions
{
Format = ImageFormat.Jpeg,
Quality = 80,
FullPage = true,
Viewport = new ImageViewport(1280, 720),
},
};
JobCreatedResponse job = await client.UrlToImageAsync(request);
await client.WaitForJobAsync(job.JobId);
File.WriteAllBytes("example.jpg", await client.DownloadAsync(job.JobId)); // JPEG bytes
var shot = await client.HtmlToImageAsync("<h1 style=\"color: #1e3a8a;\">Hello</h1>"); // 1024x768 PNG
Deliver to Your Own Bucket (BYOB)
Set Delivery (every plan) on any request object — UrlToPdfRequest, HtmlToPdfRequest, MarkdownToPdfRequest, UrlToImageRequest, HtmlToImageRequest, EInvoiceToPdfRequest — and the output is uploaded straight to your own bucket via a presigned PUT URL; nothing is stored on PDFik's side. The URL must be https on the standard port 443 (any other port is rejected with 422). Presign it for at least 15 minutes and without a Content-Type condition. Full rules: Delivery to Your Own Bucket.
var request = new UrlToPdfRequest("https://example.com")
{
Delivery = new DeliveryOptions(presignedPutUrl), // mode "presigned_put" is the only mode
};
JobCreatedResponse job = await client.UrlToPdfAsync(request);
await client.WaitForJobAsync(job.JobId); // "done" means the PUT to your bucket succeeded
Once such a job is done, the job.finished webhook reports the outcome only — no file_url and no expires_at, because PDFik keeps no copy and never records where the file went (the presigned URL is a credential). You already know the destination: you signed it. Download answers 404 (output-delivered-externally), because the file exists only in your bucket. Delivery cannot be combined with test mode (400). An upload the storage refuses fails the job at once as DELIVERY_REJECTED; an unreachable storage ends it as DELIVERY_FAILED after the retry.
Method Overview
| Method | What it does |
|---|---|
UrlToPdf(...) / HtmlToPdf(...) | Submit a URL or HTML render; the shortest forms take the URL/HTML plus optional named arguments, the full control goes through UrlToPdfRequest / HtmlToPdfRequest. |
MarkdownToPdf(string) / MarkdownToPdf(MarkdownToPdfRequest[, idempotencyKey]) | Submit a Markdown-to-PDF job. See Markdown to PDF. |
UrlToImage(string) / UrlToImage(UrlToImageRequest[, idempotencyKey]) | Submit a URL screenshot job (PNG/JPEG). See Screenshots. |
HtmlToImage(string) / HtmlToImage(HtmlToImageRequest[, idempotencyKey]) | Submit an HTML screenshot job (PNG/JPEG). |
EinvoiceToPdf(...) | Submit a Factur-X e-invoice job. See E-invoicing. |
UrlToPdfFile / HtmlToPdfFile / MarkdownToPdfFile / UrlToImageFile / HtmlToImageFile / EinvoiceToPdfFile | One-call synchronous mode (wait: true): the finished file's bytes come back on the same request. SYNC_TIMEOUT (503) is never resent; Delivery is rejected before any HTTP. |
GetJob(jobId) / WaitForJob(jobId[, timeout, pollInterval]) | Read the job status, or poll until it is done or failed (throws PdfikException on failure). |
GetFileUrl(jobId) | The direct download URL for the output file (requires the X-API-Key header). |
Download(jobId) | The output file as byte[] — the PDF, or for image jobs the raw PNG/JPEG bytes. Answers 404 for jobs submitted with Delivery. |
Each of these methods also has an …Async variant that returns a Task, including the overloads that take an Idempotency-Key.
Every create call is sent with an Idempotency-Key: yours if you pass one, otherwise a random one generated once per call and repeated each time that call is sent again, so a retried create cannot produce a second job. Download waits out a busy download (download-busy) by itself.
Best Practices
Dispose the client: PdfikClient implements IDisposable. Wrap it in a using statement or register it as a singleton in your DI container — one instance is thread-safe and meant to be reused.
Rate Limiting & Retries: The SDK automatically handles the rate-limit and concurrency 429s and 5xx server errors with an exponential backoff retry mechanism; the one-call *File methods deliberately never resend beyond those throttle waits.