Skip to main content

PDF conversion

Twip converts DOCX to PDF without an editor: no session, no window, and no engine thread. Each conversion runs on the thread that starts it, and any number run at once, so a service can convert as many documents in parallel as it has cores. The PDF draws what the screen draws, vectors and effects included, except the page background and colour, which Word's own PDF leaves out. It shows the final document, without revision marks or comments, laid out exactly as the editor's PDF export lays it out.

.NET​

PdfConverter is in Twip.Core. Build a PdfFontSet once and share it: it is fixed once created and safe to use from any thread.

// One font set for every conversion, on any thread. Build it once; it never changes.
using var fonts = PdfFontSet.Create(new PdfFontSetOptions
{
IncludeSystemFonts = true,
FontFiles = ["fonts/Carlito-Regular.ttf", "fonts/Tinos-Regular.ttf"],
Aliases = [new Alias("Calibri", "Carlito"), new Alias("Times New Roman", "Tinos")],
GenericDefaults = new GenericDefaults(Serif: "Tinos", SansSerif: "Carlito"),
Fallback = "Carlito",
});

// Each conversion runs on a thread pool thread; none waits on another.
var warnings = await Task.WhenAll(files.Select(f => PdfConverter.ConvertAsync(f, Path.ChangeExtension(f, ".pdf"), fonts)));
foreach (var w in warnings.SelectMany(w => w)) Console.WriteLine($"{w.Code}: {w.Message}");
// A conversion's result also lists, per family and style, what it couldn't draw and what drew it.
var one = await PdfConverter.ConvertAsync(await File.ReadAllBytesAsync(files[0]), fonts);
foreach (var m in one.Fonts.Missing) Console.WriteLine($"{m.Family}: drawn with {m.DrawnWith} ({m.By})");

Convert runs on the calling thread. The ConvertAsync overloads take bytes, streams or paths and run on a thread pool thread. A path overload writes to a temporary file beside the PDF and moves it into place, so a failed or cancelled conversion leaves an existing file as it was. Streams you pass stay open. With no font set, PdfFontSet.System (the installed fonts) is used.

Disposing a font set while conversions use it is safe: each running conversion holds its own reference, and later ones throw ObjectDisposedException. A font set is not a FontLibrary. A FontLibrary belongs to editor sessions and changes over time (resolvers, added faces, new settings); a font set never changes.

Failures throw EditorException: ImportFailed for bytes that aren't a readable DOCX, Unsupported for an encrypted or binary document, and ExportFailed for a font set with no faces. Cancellation throws OperationCanceledException.

Rust​

The converter is twip::pdf in the twip crate.

use twip::pdf::{FontSet, PdfOptions, convert};

let fonts = FontSet::system();
let documents: Vec<Vec<u8>> = vec![std::fs::read("a.docx")?, std::fs::read("b.docx")?];
let pdfs: Vec<_> = std::thread::scope(|s| {
let jobs: Vec<_> = documents.iter().map(|d| s.spawn(|| convert(d, &fonts, &PdfOptions::default()))).collect();
jobs.into_iter().map(|j| j.join().expect("a conversion doesn't panic")).collect()
});
for pdf in pdfs {
let pdf = pdf?;
println!("{} bytes, {} warnings", pdf.bytes.len(), pdf.warnings.len());
}

FontSet::builder() adds font files and bytes, and takes the same settings as a FontLibrary: replacements, aliases, generic_defaults, classification, fallback, character_fallback and symbol_fallback. convert_cancellable takes an AtomicBool and stops with Aborted soon after it is set. Errors are twip::api::error::Error, with the codes above.

Passwords and keywords​

PdfOptions sets an open password and keywords. It works the same on a conversion and on the editor's PDF export, in every SDK.

var options = new PdfOptions { OpenPassword = "s3cret", Keywords = ["2026-CV-1042", "notice"] };

// Headless, from bytes, cancellable.
PdfConversion pdf = await PdfConverter.ConvertAsync(docx, options: options, ct: ct);
await File.WriteAllBytesAsync("notice.pdf", pdf.Bytes, ct);

// The same options on an editor session's export.
await session.ExportPdfAsync("notice-edited.pdf", options, ct);
// An open password encrypts the PDF (AES-256); keywords go to its metadata.
const pdf = await editor.export({ format: 'pdf', openPassword: 's3cret', keywords: ['2026-CV-1042', 'notice'] });
// A protected PDF can't claim PDF/A conformance, so the export says it left the claim out.
console.log(pdf.warnings.some((w) => w.code === 'pdf-archival-claim-dropped')); // true
  • Open password. The PDF is encrypted with AES-256 (the PDF 2.0 standard security handler, revision 6). Readers ask for the password before showing anything, and text extraction, the bookmarks outline and the accessibility tags work as usual once it is entered. An empty password is rejected. A PDF/A file can't be encrypted, so a protected PDF leaves out the conformance claim Twip's PDFs otherwise carry, and the export warns with pdf-archival-claim-dropped. Owner passwords and permission restrictions aren't supported.
  • Keywords. They go to the document properties readers show (the Info dictionary) and to the XMP metadata, in order, joined with commas. Blank entries are dropped.

Pictures​

EMF, WMF and EMF+ pictures export as vector drawing, not a raster; JPEG XR (.wdp) pictures export as images. Double-byte text in metafiles isn't drawn.

Accessibility​

PDFs are tagged for PDF/UA-1: headings (with their numbers), lists with their labels, tables with their header cells, links (linked pictures too), notes, text boxes, figures with their alternative text, and text in another language (Lang). Hyperlinks and cross-references are link annotations, and the headings make the outline. The output is checked with veraPDF. Headers, footers and decorative pictures are artifacts. A picture with no alternative text that isn't marked decorative is still a figure, without a description: the PDF keeps its tags but doesn't claim PDF/UA, and the export warns with pdf-figure-without-alt. Give it alternative text, or mark it decorative, for a conformant PDF. The title, outline and link descriptions come from the text as exported, so tracked deletions a conversion hides don't reach them.

Fonts on a server​

Twip draws with the fonts you give it, makes no font choices of its own, and doesn't download any. A font set takes the settings a FontLibrary does, resolved in the same order (see How a family resolves):

.NET (PdfFontSetOptions)Rust (FontSetBuilder)
Replacementsreplacementsdraw-time replacements
Aliasesaliasesaliases, for families the set doesn't have
GenericDefaults, ClassifyFromDocumentgeneric_defaults, classificationgeneric defaults
Fallbackfallbackthe general fallback
CharacterFallback, SymbolFallbackcharacter_fallback, symbol_fallbackcharacter fallback

A conversion has no resolver, so every family the set can't draw is missing. The result's Fonts (fonts in Rust) lists them, per family and style, with what drew them and why, and the characters no font had, the same report an editor session gives. Each also warns with pdf-font-fallback. On a server, install the fonts your documents use or pass their files to the font set, and alias the families you can't ship to metric-compatible ones (Calibri to Carlito, Cambria to Caladea): see A recommended setup.

Alpine and other containers​

Twip.Core ships native libraries for Linux musl (Alpine) on x64 and arm64, beside Windows x64 and Linux glibc x64 and arm64. On Linux the library needs only the C runtime (glibc, or musl on Alpine) and fonts to draw with:

FROM mcr.microsoft.com/dotnet/runtime:10.0-alpine
RUN apk add --no-cache font-liberation
COPY app/ /app/
ENTRYPOINT ["dotnet", "/app/MyService.dll"]

On Debian and Ubuntu images, install a font package such as fonts-liberation. When the C runtime is missing, loading Twip.Core fails with a DllNotFoundException that names the missing file.