TX Text Control .NET for WPF

Create a PDF

Topic

Saving the document of a WPF TextControl as PDF takes a single call of Save with the PDF format. What else the file carries, from its title and author to passwords, permissions and PDF/A conformance for archiving, is set in a SaveSettings object. Working in the editor window of your first WPF application, the following sections create each kind of PDF from a button and open the result in the PDF reader of Windows.

Prerequisites

For each section, add a button to the DockPanel of MainWindow.xaml, before the TextControl element, and name its Click handler after the button:

<Button x:Name="createPdfButton" DockPanel.Dock="Top" Content="Create PDF"
        Click="createPdfButton_Click" />

The handlers go into MainWindow.xaml.cs, which needs these using directives:

using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using TXTextControl;

Save the Document as PDF

The following handler saves the document of textControl1 as report.pdf in the user's Documents folder, with a few document properties, and opens the file:

private void createPdfButton_Click(object sender, RoutedEventArgs e)
{
    SaveSettings saveSettings = new SaveSettings()
    {
        Author = "Tim Typer",
        DocumentTitle = "Quarterly Report",
        DocumentSubject = "Finance",
        DocumentKeywords = new string[] { "report", "Q2", "finance" },
        CreatorApplication = "My WPF Application",
        CreationDate = DateTime.Now,
        LastModificationDate = DateTime.Now
    };

    string path = System.IO.Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
        "report.pdf");

    textControl1.Save(path, StreamType.AdobePDF, saveSettings);

    // Open the PDF in the default PDF reader
    Process.Start(new ProcessStartInfo(path) { UseShellExecute = true });
}

The code works as follows:

Run the application, type a few lines and click Create PDF. The PDF reader opens report.pdf with your text.

Its document properties, which PDF readers show in their Document Properties dialog box, contain the title, author, subject and keywords of the SaveSettings:

The Document Properties dialog box of Adobe Acrobat for a PDF created with TX Text Control, showing its title, author, subject, keywords, creation and modification dates and the application.

Let the User Choose the File

Called with StreamType.AdobePDF, a SaveSettings object and no file name, Save opens a Save As dialog with the PDF file filter, and SaveSettings.SavedFile then holds the path the user chose. Load and Save Documents shows this overload and its dialog result. Another overload takes SaveSettings.DialogSettings and adds options to the dialog.

Create a PDF/A Document

PDF/A is the standard for long-term archiving, and StreamType.AdobePDFA saves a document as PDF/A-3a. Because a PDF/A file embeds its fonts, the document may use only fonts whose license allows embedding:

private void createPdfAButton_Click(object sender, RoutedEventArgs e)
{
    // Use only fonts that can be embedded in the PDF
    textControl1.FontSettings.EmbeddableFontsOnly = true;

    textControl1.Save("archive.pdf", StreamType.AdobePDFA);
}

FontSettings.EmbeddableFontsOnly restricts the document to embeddable fonts and must be true before a document is saved as PDF/A. Its default is false, and the setting stays in effect for the editor after the save.

To leave the settings of the editor unchanged, create the PDF/A file from a copy of its document in a ServerTextControl:

private void archiveButton_Click(object sender, RoutedEventArgs e)
{
    // Take a copy of the editor's document in the TX Text Control format
    byte[] document;
    textControl1.Save(out document, BinaryStreamType.InternalUnicodeFormat);

    using (ServerTextControl tx = new ServerTextControl())
    {
        tx.Create();

        // PDF/A embeds all fonts of the document
        tx.FontSettings.EmbeddableFontsOnly = true;

        tx.Load(document, BinaryStreamType.InternalUnicodeFormat);
        tx.Save("archive.pdf", StreamType.AdobePDFA,
            new SaveSettings() { DocumentTitle = "Archived Document" });
    }
}

BinaryStreamType.InternalUnicodeFormat is the format of TX Text Control itself, so the copy loses nothing of the editor's document. PDF/A covers the format in detail.

Protect the PDF With Passwords

A PDF can have two passwords. The user password must be entered to open the document. The master password, also called owner password, protects the permissions, such as printing or copying text:

private void protectedPdfButton_Click(object sender, RoutedEventArgs e)
{
    SaveSettings saveSettings = new SaveSettings()
    {
        UserPassword = "user1234",
        MasterPassword = "owner1234",
        DocumentAccessPermissions = DocumentAccessPermissions.AllowLowLevelPrinting |
                                    DocumentAccessPermissions.AllowExtractContents
    };

    textControl1.Save("protected.pdf", StreamType.AdobePDF, saveSettings);
}
  • UserPassword and MasterPassword set the two passwords.
  • DocumentAccessPermissions lists what users may do without the master password, here printing and copying content. Combine the values with |. The permissions take effect only when a master password is set.

When the file is opened, the PDF reader asks for the user password:

The Password dialog box of a PDF reader, stating that the file is protected and asking for the Document Open Password.

PDF readers enforce the permissions, but other programs can ignore them. Passwords and Access Permissions explains what they protect.

Create a PDF Without the Editor

For a PDF of a document that the user doesn't see, use a ServerTextControl, as in the example above. It has the same Load and Save methods and takes the same SaveSettings; Save as DOCX and PDF converts files with it.

Next Steps

  • Create a PDF Form: add fields to the PDF that users fill out.
  • Digitally Sign a PDF: sign the PDF with a certificate.
  • PDF Processing: PDF creation, import, fonts, attachments and metadata in detail.
  • The blog article PDF Security Explained: Passwords, Permissions, Encryption, and Digital Signatures in C# .NET: what passwords, permissions and signatures protect.