PDF Creation and Conversion
In a WPF application, the document in the TextControl of a window becomes a PDF with one call of Save and the value StreamType.AdobePDF, and a ServerTextControl does the same for documents the user never sees. TX Text Control writes the PDF with its own filter, so Adobe Acrobat isn't needed on the user's machine. What follows covers what a PDF takes over from the document, the options of the save, accessible PDF documents and conversions into another page format.
Step by step, Create a PDF in Getting Started saves a first PDF with document properties, opens the Save As dialog box and creates PDF/A and password-protected files. PDF is part of the Professional and Enterprise editions, and PDF/A and PDF/UA of the Enterprise edition; see Editions and Feature Availability.
What a PDF Keeps From the Document
Before the PDF is written, TX Text Control lays out the pages, so page breaks, headers, footers and repeated table header rows are the same as in the editor. These elements become interactive parts of the PDF:
| In the document | In the PDF |
|---|---|
| Hypertext links and document links | Links to websites and to targets within the document, as Insert Hyperlinks and Bookmarks in Code describes |
| Form fields | Fillable PDF form fields with their names and values, as PDF Forms describes |
| Signature fields | Signature fields that can be signed with a certificate when the document is saved, as Signature Fields and Signature Appearance describes |
| SVG images | Vector graphics |
| Headings, tables, text frames, tables of contents and footnotes | The tagged structure of an accessible PDF, since version 34.0 |
Only complete documents can be saved as PDF, not a selection.
Choose What the PDF Contains
SaveSettings holds the options you pass to Save. For PDF, these properties matter:
| Property | What it does | Described in |
|---|---|---|
DocumentTitle, Author, DocumentSubject, DocumentKeywords and more | Document properties of the PDF | Document Metadata |
UserPassword, MasterPassword, DocumentAccessPermissions | Encryption and what readers may do | Passwords and Access Permissions |
ImageCompressionQuality, ImageMaxResolution | Smaller files through compressed images | Reduce the Size of PDF Files |
| DocumentLevelJavaScriptActions | Scripts that run when the PDF is opened | Run JavaScript When the PDF Opens |
EmbeddedFiles | Files attached to the PDF, such as invoice XML | Attachments |
DigitalSignature, SignatureFields | A digital signature applied while saving | Digital Signatures |
OmittedContent can't be used with PDF and PDF/A.
Run JavaScript When the PDF Opens
The scripts in DocumentLevelJavaScriptActions are embedded at document level, and the PDF reader runs them when it opens the document. Add a button to the DockPanel of MainWindow.xaml, as in Getting Started:
<Button x:Name="pdfWithScriptButton" DockPanel.Dock="Top" Content="PDF With Script"
Click="PdfWithScriptButton_Click" />
The handler in MainWindow.xaml.cs saves the document of textControl1 with a script that shows a notice:
private void PdfWithScriptButton_Click(object sender, RoutedEventArgs e)
{
SaveSettings saveSettings = new SaveSettings()
{
DocumentTitle = "Quarterly Report",
// Runs in the PDF reader when the document is opened
DocumentLevelJavaScriptActions = new string[]
{
"app.alert('This report is confidential. Do not forward it.');"
}
};
textControl1.Save("report-with-script.pdf", StreamType.AdobePDF, saveSettings);
}
app.alert is part of the JavaScript API of PDF readers such as Adobe Acrobat Reader, which Adobe documents. The property takes an array, so a document can contain several scripts. PDF/A doesn't allow scripts, so they aren't embedded when the document is saved as PDF/A. The blog article Add JavaScript to PDFs with TX Text Control in C# .NET: Time-Based Alerts Made Easy shows expiration notices built this way.
Create an Accessible PDF (PDF/UA)
Screen readers and other assistive technologies need to know which text is a heading, what an image shows and which cells head a table. PDF/UA (ISO 14289) is the standard that puts this information into the file. Since version 34.0, every PDF of TX Text Control contains a logical structure beside its visible content, with chapters, headings, paragraphs and sections, text frames, tables, tables of contents and footnotes. Your document supplies the rest:
| Element | What you set |
|---|---|
| Document | A title in DocumentSettings.DocumentTitle |
| Headings | A structure level in ParagraphFormat.StructureLevel, usually through a paragraph style |
| Images, text frames and other frames | FrameBase.DescriptiveText |
| Tables | Header rows with TableRow.IsHeader and a summary in Table.DescriptiveText |
| Links | HypertextLink.DescriptiveText and DocumentLink.DescriptiveText |
| Form fields | FormField.DescriptiveText |
The following handler sets the title, turns the first paragraph into a heading and refuses to save while an image, table or form field has no description:
private void AccessiblePdfButton_Click(object sender, RoutedEventArgs e)
{
// The title that screen readers announce
textControl1.DocumentSettings.DocumentTitle = "Quarterly Report";
// The first paragraph becomes a level 1 heading
textControl1.Select(0, 0);
textControl1.Selection.ParagraphFormat.StructureLevel = 1;
// Collect the elements that have no description yet
List<string> missing = new List<string>();
foreach (TXTextControl.Image image in textControl1.Images)
{
if (string.IsNullOrEmpty(image.DescriptiveText))
{
missing.Add("Image " + image.ID);
}
}
foreach (TXTextControl.Table table in textControl1.Tables)
{
if (string.IsNullOrEmpty(table.DescriptiveText))
{
missing.Add("Table " + table.ID);
}
}
foreach (FormField formField in textControl1.FormFields)
{
if (string.IsNullOrEmpty(formField.DescriptiveText))
{
missing.Add("Form field " + formField.Name);
}
}
if (missing.Count > 0)
{
MessageBox.Show(this, "Add a description to:\n" + string.Join("\n", missing), "Accessible PDF");
return;
}
textControl1.Save("report-accessible.pdf", StreamType.AdobePDF);
}
The code works as follows:
TXTextControl.Imageis written in full, because the code-behind of a window usually importsSystem.Windows.Controls, which has anImageclass, too.StructureLevel1 is a first-level heading and 0 body text. In real documents, the paragraph styles of the headings carry it.ImagesandTablescontain the images and tables of the text part with the input focus, here the main text, whileFormFieldscontains the form fields of the whole document. Headers, footers and text frames are text parts of their own, as Find the Fields of All Text Parts explains.
With StreamType.AdobePDFA, the same document becomes a PDF/A-3a document that can conform to PDF/UA as well, as PDF/A describes.
Validate the Accessible PDF
The handler above checks the document before it's saved. To check the saved PDF itself against PDF/UA, Text Control offers TXTextControl.PDF.Validation, a .NET library that reads a PDF file or its bytes and reports its findings. It comes from nuget.org rather than the Text Control Private NuGet Feed and works without a TextControl or ServerTextControl:
- .NET 10. Version 34.1.0 targets .NET 10, so the WPF project must target .NET 10 (
net10.0-windows). It can't be used in .NET Framework projects. - License. It's free of charge for individuals and organizations that own a valid TX Text Control license, and its license is accepted when the package is installed.
Add it with Project > Manage NuGet Packages... and the source nuget.org, or in the folder of the project:
dotnet add package TXTextControl.PDF.Validation 34.1.0
The following handler saves the document of textControl1 as PDF into memory, validates the bytes and writes the file only when the report has no blocking error. MainWindow.xaml.cs needs using System.IO;, using TXTextControl.PDF.Validation; and using TXTextControl.PDF.Validation.Model;, and using System.Collections.Generic; and using System.Linq; if implicit usings are off:
private void ValidatePdfButton_Click(object sender, RoutedEventArgs e)
{
// Save the PDF into memory, so it can be checked before it's written
textControl1.Save(out byte[] pdf, BinaryStreamType.AdobePDF);
Report report = PdfUaValidator.Validate(pdf);
if (report.Status == ValidationStatus.Failed || report.Status == ValidationStatus.Blocked)
{
// The findings that didn't pass, with their rule and message
IEnumerable<string> problems = report.Findings
.Where(finding => !finding.Passed)
.Select(finding => $"{finding.Severity} {finding.RuleId}: {finding.Message}");
MessageBox.Show(this, "The PDF isn't accessible yet:\n" + string.Join("\n", problems), "PDF/UA");
return;
}
File.WriteAllBytes("report-accessible.pdf", pdf);
MessageBox.Show(this, "Saved with the result " + report.Status + ".", "PDF/UA");
}
The code works as follows:
PdfUaValidator.Validateaccepts the path of a PDF file or the PDF as a byte array and returns aReportof theTXTextControl.PDF.Validation.Modelnamespace.StatusisPassed,CompletedWithWarnings,FailedorBlocked. A report isFailedonly when a finding of the severityErrorfailed.Blockedmeans the validation stopped early, for example at an encrypted PDF, so validate a document before you give it a password.- A
Findingcarries aRuleIdsuch asUA-TITLEfor the document title orUA-FIG-ALTfor image descriptions, aSeverityofInfo,WarningorError,Passedand aMessage.
PdfUaValidator.ToJson(report, true) writes the report as indented JSON, for example to keep it with the document or to compare two versions of a template. A validator can tell that an image has a description, not whether the description fits, so people still review the result. PDF/A conformance isn't validated: the PDFA-CONFORMANCE finding only says whether the file declares it. The blog article Validating PDF/UA Documents in .NET C#: A Practical Guide builds on this, and Verify the Signatures in Code uses the same package for digital signatures.
Convert a Document to Another Page Format
A document keeps its page format in the PDF. For a PDF with other pages, leave the editor alone and change a copy in a ServerTextControl:
private void LetterPdfButton_Click(object sender, RoutedEventArgs e)
{
// A copy of the document in the editor
byte[] document;
textControl1.Save(out document, BinaryStreamType.InternalUnicodeFormat);
using (ServerTextControl tx = new ServerTextControl())
{
// Initialize the new instance before using it
tx.Create();
tx.Load(document, BinaryStreamType.InternalUnicodeFormat);
// Page sizes and margins in 1/100 inch
tx.PageUnit = MeasuringUnit.CentiInch;
// US letter pages with margins of 0.75 inch in every section
foreach (TXTextControl.Section section in tx.Sections)
{
section.Format.PageSize = new PageSize();
section.Format.PageMargins = new PageMargins(75, 75, 75, 75);
}
tx.Save("report-letter.pdf", StreamType.AdobePDF);
}
}
The code works as follows:
- The copy in
BinaryStreamType.InternalUnicodeFormat, the format of TX Text Control, keeps everything the document contains, and the user's document stays as it is. - ServerTextControl is the document engine without a user interface. Create must be called before any other member.
- PageUnit sets the unit of page sizes and margins. The reference names its type
PageUnit; the enumeration in code isMeasuringUnit. - Each Section has its own format. The PageSize constructor without parameters creates a US letter page, 8.5 x 11 inches, and SectionFormat.PageMargins takes the margins.
The number of pages can change, because text and images flow onto the new pages. Files that aren't open in the window are converted the same way, as Convert a Folder of Documents shows. The opposite direction, from PDF to an editable document, is the subject of PDF Import and Its Limitations.
Add a Watermark to Every Page
A watermark such as "DRAFT" or "CONFIDENTIAL" shows the status of a PDF on every page. It is an image in the header of each section, fixed on the page and placed below the text; Add a Watermark to Every Page in Images, Text Frames, and Shapes explains the method AddWatermark and how it centers the image. So that the document in the window stays without a watermark, call the method for a copy:
private void DraftPdfButton_Click(object sender, RoutedEventArgs e)
{
// A copy of the document in the editor
byte[] document;
textControl1.Save(out document, BinaryStreamType.InternalUnicodeFormat);
using (ServerTextControl tx = new ServerTextControl())
{
// Initialize the new instance before using it
tx.Create();
tx.Load(document, BinaryStreamType.InternalUnicodeFormat);
// Page sizes, margins and image locations in twips
tx.PageUnit = MeasuringUnit.Twips;
AddWatermark(tx.Sections, "draft.svg");
tx.Save("report-draft.pdf", StreamType.AdobePDF);
}
}
The copy lives in a ServerTextControl, as in Convert a Document to Another Page Format, and PageUnit gives its page sizes and margins the unit of the image. ServerTextControl.Sections is the same kind of collection as the sections of the WPF TextControl, so AddWatermark takes it unchanged. Adobe Acrobat shows the watermark in the middle of every page:

The blog article Adding Watermarks to PDF Documents in .NET C# adds the watermark the same way before it saves the PDF.
Next Steps
- PDF/A: save documents for long-term archiving.
- Font Embedding and Substitution: control which fonts end up in the PDF.
- PDF Forms: create PDF documents that users fill in.
- Passwords and Access Permissions: protect the PDF.