What SoftZenPdf can do today
Each capability below comes with a code example that is compiled and run against the library, and the limits you should know before relying on it.
PDF generation and vector graphics
Create documents page by page and draw on them with a fluent API. High-level helpers keep colours and line widths from leaking between calls; the low-level operators are there when you need exact control.
- Page sizes: ISO A0 to A6, Letter and Legal, or any custom size from 3 to 14,400 points, portrait or landscape, with a document-wide default.
- Shapes: lines, rectangles, ellipses, circles and cubic Bézier paths, filled, stroked or both.
- Colour and opacity: RGB from hex, 0–255 or 0–1 values, with separate fill and stroke opacity.
- Transforms: translate, scale and rotate with
Transform, scoped bySaveState/RestoreState. - Compact output: content streams are Flate-compressed; turn it off to read them while debugging.
Limits: Colours are DeviceRGB only: no CMYK, spot colours, gradients or patterns. Dash patterns, line caps and line joins have no API yet.
using SoftZenPdf;
var document = new PdfDocument();
var content = document.AddPage().Content;
content
.DrawLine(72, 780, 520, 780, PdfColor.Gray, lineWidth: 0.5)
.DrawRectangle(72, 620, 180, 120, fill: PdfColor.FromHex("#864FFE"))
.DrawEllipse(390, 680, 110, 60, fill: PdfColor.FromHex("#E8FBC6"), stroke: PdfColor.Black, lineWidth: 2);
// Low-level path operators, with 50% opacity limited by SaveState/RestoreState.
content
.SaveState()
.SetOpacity(0.5)
.SetFillColor(PdfColor.Blue)
.MoveTo(72, 560).CurveTo(160, 640, 280, 480, 360, 560).LineTo(360, 480).LineTo(72, 480).ClosePath()
.Fill()
.RestoreState();
document.Save("shapes.pdf");
Standard 14 fonts
Helvetica, Times and Courier in four styles each, plus Symbol and ZapfDingbats. Every PDF viewer provides them, so nothing is embedded and files stay tiny.
- Accurate measuring: widths come from Adobe's AFM metrics, so
MeasureTextcentres and right-aligns text precisely. - Western European text: WinAnsiEncoding covers accented Latin letters, €, £, curly quotes and dashes.
- No files to ship: fonts are referenced by name, not embedded.
Limits: Only WinAnsiEncoding characters: Greek, Cyrillic, CJK and other scripts need an embedded TrueType font. PDF/A forbids non-embedded fonts, so these cannot be used in PDF/A mode.
using SoftZenPdf;
var document = new PdfDocument();
var page = document.AddPage(PageSize.Letter);
const string title = "Quarterly report";
var width = StandardFont.HelveticaBold.MeasureText(title, 28);
page.Content
.DrawText(title, (page.Width - width) / 2, 720, StandardFont.HelveticaBold, 28)
.DrawText("Helvetica, Times and Courier need no embedding.", 72, 680, StandardFont.TimesRoman, 14)
.DrawText("Accents and symbols such as é, ü, € and £ are in WinAnsi.", 72, 660, StandardFont.Courier, 11);
document.Save("standard-fonts.pdf");
Embedded TrueType fonts with subsetting
Load any TrueType font and draw Unicode text with it. Only the glyphs you use are embedded, and a ToUnicode map keeps the text searchable and copyable.
- Automatic subsetting: a page of text embeds kilobytes, not the whole font file.
- Unicode: Type0/CIDFontType2 fonts with Identity-H encoding, so any character the font has can be drawn.
- Copy and search: a ToUnicode CMap maps glyphs back to text in every viewer.
- Licence-aware: the font's embedding permissions (OS/2
fsType) are respected. - Kerning and ligatures: pair kerning from
GPOSorkern, and standard ligatures such as fi and ffi, each of which can be turned off. - Right-to-left text: Hebrew, Arabic and mixed-direction lines are ordered with the Unicode Bidirectional Algorithm, with mirrored brackets, and still copy in reading order.
- Arabic shaping: joined letter forms, required ligatures such as lam-alef, and dots and vowel marks placed with the font's anchors.
Limits: TrueType outlines only: CFF-based OpenType fonts and .ttc collections are rejected. Indic scripts are not shaped yet, and Nastaliq fonts that rely on cursive attachment are not connected.
using SoftZenPdf;
var font = TrueTypeFont.FromFile("NotoSans-Regular.ttf");
var document = new PdfDocument();
document.AddPage().Content
.DrawText("Ελληνικά, Кириллица, Latin: one embedded font", 72, 770, font, 16)
.DrawText($"{font.FamilyName}, subset to the glyphs this page uses", 72, 745, font, 11, PdfColor.Gray);
document.Save("truetype-font.pdf");
Images and image-to-PDF conversion
Place photos and graphics in a box or at a width with the height following the aspect ratio, or turn images and scans into PDF pages. Each image is stored once, however many times you draw it.
- JPEG: baseline and progressive, greyscale, RGB or CMYK, embedded unchanged; EXIF orientation is applied so photos appear upright.
- PNG: every colour type and bit depth, palettes and interlacing, decoded by SoftZenPdf's own decoder.
- GIF, BMP and TIFF: including multi-page TIFFs, CCITT fax compression, LZW, Deflate, PackBits, tiles and CMYK.
- Transparency: alpha channels and transparent colours become soft masks.
- Images to PDF: a page per image or TIFF page, sized to the image at its resolution or fitted to a page size with margins.
Limits: No WebP, HEIC, JPEG 2000 or SVG; only the first frame of a GIF. 16-bit images are stored at 8 bits per component. Lossless, arithmetic-coded and 12-bit JPEGs are not supported, and CMYK JPEGs are refused in PDF/A mode.
using SoftZenPdf;
// One page per image, and one per page of a multi-page TIFF, each on A4 with a half-inch margin.
var options = new ImagePageOptions { PageSize = PageSize.A4, Margin = 36 };
var document = PdfDocument.FromImages(["color-chart.jpg", "pages.tif", "fax.tif"], options);
document.Save("images-to-pdf.pdf");
Console.WriteLine($"{document.Pages.Count} pages");
HTML to PDF
Convert HTML and CSS templates to PDF with SoftZenPdf's own HTML parser, CSS engine and layout engine, with no browser behind it.
- CSS cascade: style sheets, selectors, specificity and inheritance,
@pageand@font-face. - Documents: paragraphs, lists, tables with repeated header rows, images, links and bookmarks.
- Safe by default: files are read only from the folder you choose, and nothing from the network unless you allow it.
Limits: No JavaScript, flexbox, grid, floats or positioning (they are laid out as ordinary blocks), and no SVG, gradients or WOFF fonts.
using SoftZenPdf;
using SoftZenPdf.Html;
var html = """
<html>
<head>
<title>Invoice 1042</title>
<style>
@page { size: A4; margin: 2cm }
body { font-family: Helvetica, sans-serif; font-size: 11pt }
h1 { color: #1a3c7a }
table { width: 100%; border-collapse: collapse }
th { background: #1a3c7a; color: white; text-align: left; padding: 4px }
td { border-bottom: 1px solid #ccc; padding: 4px }
.amount { text-align: right }
</style>
</head>
<body>
<h1>Invoice 1042</h1>
<p>Thank you for your order. <a href="https://example.com/terms">Payment terms</a> apply.</p>
<table>
<thead><tr><th>Item</th><th class="amount">Price</th></tr></thead>
<tr><td>Consulting</td><td class="amount">1,200.00</td></tr>
<tr><td>Support</td><td class="amount">300.00</td></tr>
</table>
</body>
</html>
""";
var converter = new HtmlConverter();
var pdf = converter.Convert(html);
pdf.Save("invoice.pdf");
Console.WriteLine($"{pdf.Info.Title}: {pdf.Pages.Count} page(s), {converter.Warnings.Count} warning(s)");
Flowing layout
Describe paragraphs, lists and tables and let SoftZenPdf break them into lines and pages, with headers, footers and page numbers.
- Text: wrapping, justification, indents, line spacing, keep-with-next and widow control, right-to-left lines.
- Tables: automatic or fixed column widths, spans, header rows repeated on each page, rows split across pages.
- Fonts: font families, fallback for missing characters, system fonts and
.ttccollections.
Limits: No floating images or text wrapping around objects, no hyphenation dictionary, and no multi-column pages.
using SoftZenPdf;
using SoftZenPdf.Layout;
var flow = new FlowDocument();
var heading = new TextStyle { FontSize = 18, Bold = true };
var small = new TextStyle { FontSize = 9 };
// A footer on every page: "Page 3 of 7".
var footer = new Paragraph { Style = new ParagraphStyle { Alignment = ParagraphAlignment.Center } };
footer.Add("Page ", small).Add(new Field(FieldKind.PageNumber, small)).Add(" of ", small).Add(new Field(FieldKind.PageCount, small));
flow.PageSetup.Footer.Add(footer);
flow.Add(new Paragraph("Project status", heading) { OutlineLevel = 1, Style = new ParagraphStyle { SpaceAfter = 6, KeepWithNext = true } });
flow.Add(new Paragraph("Text wraps to the width of the page and continues on as many pages as it needs. ")
.Add("Runs can be bold, ", new TextStyle { Bold = true })
.Add("coloured", new TextStyle { Color = PdfColor.Blue })
.Add(" or ")
.Add("links", new TextStyle { Link = "https://example.com/", Underline = true })
.Add("."));
foreach (var (item, i) in new[] { "Design approved", "Build in progress", "Launch in May" }.Select((t, i) => (t, i)))
flow.Add(new Paragraph(item) { Marker = $"{i + 1}.", Style = new ParagraphStyle { LeftIndent = 24, FirstLineIndent = -18 } });
var table = new Table { Width = ColumnWidth.Percent(100), CellBorders = Borders.All(BorderLine.Thin) };
table.AddRow("Task", "Owner", "Due").IsHeader = true; // repeated on every page the table continues on
table.AddRow("Wireframes", "Ana", "3 March");
table.AddRow("API", "Ben", "17 March");
flow.Add(table);
flow.ToPdf().Save("flow.pdf");
Bookmarks
Build a nested outline that appears in the viewer's navigation pane, and read the bookmarks of existing documents.
- Nested tree: chapters, sections and subsections to any depth.
- Precise targets: jump to a page, optionally scrolled to a given position.
- Open or closed: choose which branches start expanded; the viewer opens with the bookmarks pane shown.
- Reading:
PdfReader.ReadOutlinereturns titles, target pages and children, resolving named destinations.
Limits: Bookmarks of source documents are not carried over when pages are merged or extracted.
using SoftZenPdf;
var document = new PdfDocument();
var intro = document.AddPage();
var details = document.AddPage();
intro.Content.DrawText("1. Introduction", 72, 770, StandardFont.HelveticaBold, 20);
details.Content.DrawText("2. Details", 72, 770, StandardFont.HelveticaBold, 20);
var chapter = document.Outline.Add("1. Introduction", intro);
chapter.Add("1.1 Background", intro, top: 500);
chapter.IsOpen = true;
document.Outline.Add("2. Details", details);
document.Save("bookmarks.pdf");
Links
Make any area of a page clickable: a web address, or another page of the same document.
- Link text in one call:
DrawLinkdraws underlined link text and makes it clickable. - Web and email links: any absolute URI, such as
https:ormailto:. - Internal links: jump to a page, optionally to a position on it.
- Any clickable area:
AddLinkmakes any rectangle a link, with an optional coloured border. - Reading:
PdfReader.GetLinkslists link areas with their URI or target page.
Limits: Links target URIs or pages of the same document: not named destinations, other PDF files or applications. Link borders are 1 point and solid.
using SoftZenPdf;
var document = new PdfDocument();
var first = document.AddPage();
var second = document.AddPage();
var font = StandardFont.Helvetica;
// DrawLink draws the text, underlines it and makes it clickable.
first.DrawLink("Jump to page 2", 72, 770, font, 14, second);
first.DrawLink("Visit example.com", 72, 745, font, 14, new Uri("https://example.com/"));
// It returns the text width, so a sentence can continue after an inline link.
var x = 72.0;
first.Content.DrawText("Questions? ", x, 715, font, 12);
x += font.MeasureText("Questions? ", 12);
x += first.DrawLink("Email us", x, 715, font, 12, new Uri("mailto:hello@example.com"));
first.Content.DrawText(" any time.", x, 715, font, 12);
// AddLink makes any area clickable, here with a red border.
first.Content.DrawRectangle(72, 620, 200, 60, fill: PdfColor.FromHex("#F4F2FE"));
first.AddLink(72, 620, 200, 60, new Uri("https://example.com/offer"), borderColor: PdfColor.Red);
document.Save("links.pdf");
Document metadata
Set the title, author and other properties shown in a viewer's document properties and used by search engines and archives.
- Standard properties: title, author, subject, keywords, creator, producer, creation and modification dates.
- Info and XMP: written to the Info dictionary and mirrored in an XMP metadata stream, kept consistent.
- Reading:
PdfReader.Inforeturns the properties of existing files.
Limits: Only the standard properties: no custom Info keys or custom XMP schemas.
using SoftZenPdf;
var document = new PdfDocument();
document.Info.Title = "Annual report 2026";
document.Info.Author = "Finance team";
document.Info.Subject = "Results for the year";
document.Info.Keywords = "report, finance";
document.Info.CreationDate = DateTimeOffset.Now;
document.AddPage();
document.Save("metadata.pdf");
var info = PdfReader.Open("metadata.pdf").Info;
Console.WriteLine($"{info.Title} by {info.Author}");
Watermarks
Stamp text or an image across every page, rotated and semi-transparent, when the document is saved.
- Text or image: any font, colour and size, or a logo scaled to the page.
- Angle and opacity: real transparency through an ExtGState, not a pale colour.
- Every page: centred on each page's crop box, including pages imported from other PDFs.
Limits: One watermark per document, drawn on top of the page content.
using SoftZenPdf;
var document = new PdfDocument();
document.AddPage().Content.DrawText("Contract", 72, 770, StandardFont.HelveticaBold, 20);
document.AddPage().Content.DrawText("Terms", 72, 770, StandardFont.HelveticaBold, 20);
document.Watermark = Watermark.Text("DRAFT", StandardFont.HelveticaBold, 120, PdfColor.Red, angle: 45, opacity: 0.15);
document.Save("watermark.pdf");
Merge, split, reorder and rotate
Open existing PDFs and recombine their pages: merge files, pull out a range, change the order, rotate pages, or draw on top of them.
- Robust reading: classic cross-reference tables, cross-reference streams, object streams and incremental updates, with basic repair of damaged files.
- Merge and extract:
Mergecombines documents;Extractcopies any pages in any order, repeats allowed. - Reorder and rotate:
MovePageandPdfPage.Rotation. - Annotate imported pages: anything you draw is added on top of the original content.
Limits: Bookmarks, the form structure, named destinations and metadata of source documents are not carried over. There is no page-deletion method: build a new document with Extract. Output uses classic cross-reference tables, so it is not as compact as object-stream output.
using SoftZenPdf;
var report = PdfReader.Open("report.pdf");
var appendix = PdfReader.Open("appendix.pdf");
var combined = PdfDocument.Merge(report, appendix);
combined.Pages[^1].Rotation = 90;
combined.MovePage(combined.Pages.Count - 1, 0);
combined.Save("combined.pdf");
PdfDocument.Extract(report, [2, 0]).Save("pages-3-and-1.pdf");
Encryption and permissions
Protect documents with passwords and permissions using the Standard Security Handler, and open encrypted files.
- AES-256 by default (revision 6), with AES-128 and RC4 for old viewers.
- User and owner passwords: omit the owner password and a random one is generated, so the user password never grants owner rights.
- Permissions: printing, copying, editing, annotating, form filling and assembly.
- Decryption: open files with either password; tested against files encrypted by qpdf.
Limits: Password security only, no certificate (public-key) encryption. Files using Adobe's deprecated AES-256 revision 5 cannot be opened. Permissions are advisory: viewers enforce them, but anyone with the user password can decrypt.
using SoftZenPdf;
var document = new PdfDocument();
document.AddPage().Content.DrawText("Confidential", 72, 770, StandardFont.HelveticaBold, 24);
document.Encrypt(userPassword: "user123", ownerPassword: "owner456",
permissions: PdfPermissions.All & ~PdfPermissions.CopyContent);
document.Save("secret.pdf");
var reader = PdfReader.Open("secret.pdf", "user123");
Console.WriteLine(reader.EncryptionAlgorithm); // Aes256
Interactive forms
Create fillable forms whose fields look the same in every viewer, read form fields, and fill existing forms without rewriting the original file.
- Field types: text (single- or multi-line, maximum length, comb), check boxes, radio groups, dropdowns, list boxes (single or multi-select), push buttons and signature placeholders.
- Real appearances: every field gets appearance streams, so values show even in viewers that do not regenerate them.
- Reading:
ReadFormFieldsreturns names, types, values and options. - Filling:
PdfFormFillersets values and appends an incremental update, keeping the original bytes.
Limits: Field text uses the standard fonts, so Latin characters only. Signature fields are not signed and forms cannot be flattened. No JavaScript or XFA (so no date pickers or calculated fields), and no form fields in PDF/A mode yet.
using SoftZenPdf;
var document = new PdfDocument();
var page = document.AddPage();
page.AddTextField("Name", 200, 690, 260, 22).MaxLength = 50;
page.AddCheckBox("Subscribe", 200, 652, 16, isChecked: true);
page.AddRadioGroup("Plan", 16, ("Basic", 200, 612), ("Pro", 300, 612)).Value = "Pro";
page.AddDropdown("Country", 200, 570, 260, 22, ["Pakistan", "Germany", "Japan"]);
page.AddSignatureField("Signature", 200, 500, 260, 50);
document.Save("form-fields.pdf");
foreach (var field in PdfReader.Open("form-fields.pdf").ReadFormFields())
Console.WriteLine($"{field.Name}: {field.Kind} = {field.Value ?? "(empty)"}");
Text extraction
Get the text of any page the reader can open, as plain text or as runs with positions, font and size.
- Complete decoding: ToUnicode maps, standard encodings, embedded font encodings and the Adobe Glyph List.
- Everything on the page: text inside form XObjects and annotation appearances such as filled form fields.
- Positions: each run's bounding box, font size, font name and angle.
- Two orders: content-stream order, or
TextOrder.Visualfor line-by-line reading of forms and simple layouts.
Limits: Scanned pages yield no text unless you recognise them with SoftZenPdf.Ocr. Multi-column reading order is not reconstructed. Characters without a Unicode mapping come out as U+FFFD, with a warning.
using SoftZenPdf;
var reader = PdfReader.Open("hello.pdf");
Console.WriteLine(reader.ExtractText(0));
foreach (var run in reader.ExtractTextWithPositions(0))
Console.WriteLine($"{run.Text} at ({run.X1:0}, {run.Y1:0}), {run.FontSize}pt {run.FontName}");
PDF/A-2b archiving
Create documents for long-term archiving that are PDF/A-2b compliant by construction, and check existing files.
- Guard rails: PDF/A mode refuses non-embedded fonts, encryption and other forbidden features as you build.
- Required structure: an sRGB ICC output intent and PDF/A XMP identification are added automatically.
- Validated on save: saving throws
PdfAExceptionlisting every violation, each citing its ISO 19005-2 clause. - Check any file:
PdfReader.ValidatePdfA2bruns the same checks on existing PDFs.
Limits: PDF/A-2b only. The built-in validator is a practical subset of ISO 19005-2, not a replacement for veraPDF, and a veraPDF cross-check of SoftZenPdf's output is still pending. Form fields are not supported in PDF/A mode yet.
using SoftZenPdf;
var document = PdfDocument.CreateForPdfA();
document.Info.Title = "Annual report";
var font = TrueTypeFont.FromFile("NotoSans-Regular.ttf");
document.AddPage().Content.DrawText("Archived", 72, 770, font, 14);
document.Save("report-pdfa.pdf"); // throws PdfAException if a check fails
OCR and searchable PDFs
Recognise the text in scans with the SoftZenPdf.Ocr add-on and Tesseract 5, and turn scanned images and PDFs into searchable documents.
- Words with positions: paragraphs, lines and words with pixel boxes, baselines and confidence, in 100+ languages.
- Searchable PDFs: an invisible text layer placed word by word over the scan, in any script, so search, selection and copy match what you see.
- Existing scans: makes scanner and copier PDFs searchable in place with an incremental update; sideways and rotated scans are read upright.
- PDF/A-2b: searchable archives that pass veraPDF, and a PDF/A source stays PDF/A.
Limits: a separate package with native Tesseract libraries (Windows x64/x86 included; Linux needs the system libraries; no macOS) and downloaded language data. JBIG2 and JPEG 2000 images in existing PDFs are skipped.
using SoftZenPdf;
using SoftZenPdf.Ocr;
var options = new TesseractOcrOptions { TessDataPath = "tessdata" };
using var engine = new TesseractOcrEngine(options);
var creator = new OcrPdfCreator(engine);
// Scanned images to a searchable PDF
creator.CreatePdf(["invoice.png", "shipping.tif"], "scans-searchable.pdf");
// An existing scanned PDF, made searchable in place
PdfDocument.FromImages(["invoice.png"]).Save("copier-scan.pdf");
creator.AddTextLayer("copier-scan.pdf", "copier-searchable.pdf");
Console.WriteLine(PdfReader.Open("copier-searchable.pdf").ExtractText(0));
Redaction
Remove sensitive information for good with the SoftZenPdf.Redact add-on: what is under the black bar is gone from the file, not just hidden.
- By pattern or area: regular expressions over the page text (OCR layers included), or rectangles you mark; preview matches first.
- Everything underneath: covered text glyphs, the covered parts of vector shapes and the covered pixels of images (JPEG included) are removed from the page content.
- Around the page: annotations and form fields in the areas; matching text in metadata, bookmarks, notes, form values and the structure tree.
- Nothing to recover: the output is a new file without earlier revisions, and is searched again to confirm the patterns are gone.
Limits: partly covered JBIG2 and JPEG 2000 images are removed whole; redacted JPEGs are stored losslessly and grow; embedded fonts are kept.
using SoftZenPdf;
using SoftZenPdf.Redact;
var redactor = PdfRedactor.Open("record.pdf");
redactor.RedactText(@"\d{3}-\d{2}-\d{4}"); // social security numbers
redactor.RedactText(@"[\w.+-]+@[\w-]+\.[\w.]+"); // email addresses
redactor.RedactArea(pageIndex: 0, 72, 640, 320, 700); // an area, in points
var result = redactor.Save("record-redacted.pdf");
Console.WriteLine($"{result.RemovedCharacters} characters removed, {result.RemainingMatches.Count} matches left");
Optimizing file size
Make PDFs smaller with the SoftZenPdf.Optimizer add-on, choosing exactly which optimizations run.
- Compression: strongest Deflate for every stream, plus compressed object and cross-reference streams.
- Duplicates: one copy of fonts, images and other resources stored more than once, as after merging.
- Images: JPEG recompression, lossless palettes and bit-depth reduction, photos to JPEG, downsampling to a target resolution, and CMYK to RGB.
- Fast web view: linearized output, so the first page shows before the whole file has downloaded.
- Safe: every object is replaced only when smaller, encryption and permissions are kept, and each image's outcome is reported.
Limits: JBIG2 and JPEG 2000 images are left as they are; CMYK conversion does not use colour profiles; linearized files do not use object streams.
using SoftZenPdf;
using SoftZenPdf.Optimizer;
var optimizer = new PdfOptimizer();
optimizer.AddOptimizationHandler(new CompressionOptimizer()); // streams and object streams
optimizer.AddOptimizationHandler(new DuplicateResourceOptimizer()); // one copy of repeated fonts and images
optimizer.AddOptimizationHandler(new ImageResolutionOptimizer(150)); // downsample images above 225 ppi
optimizer.AddOptimizationHandler(new ImageQualityOptimizer
{
JpegProcessor = new JpegCompressor(0.75f),
BitmapProcessor = new BitmapCompressor()
});
var result = optimizer.Optimize("merged.pdf", "merged-optimized.pdf");
Console.WriteLine($"{result.OriginalSize:N0} → {result.OptimizedSize:N0} bytes, {result.Reduction:P0} smaller");
Try it in a console app
The getting started guide walks you from an empty project to your first PDF.