PDF Document Processor: Updates to PDF creation API (Coming soon in v15.2)

Paul Usher's Blog
10 November 2015

In our previous major release we introduced the Document Creation API that is used to generate a document layout from scratch as well as create your own graphics on the PDF page using a rectangle, a path, an ellipse, a polygon and other graphic elements.

v15.2 extends the PDF creation API and provides the document generation for PDF, PDF-A-2b and PDF-A-3b file formats as well as adding the capability to add a link to a page or URI, attach a file and create or modify bookmarks.

Let’s take a look at what is involved…

Creating PDF with Graphics

After creating a new instance of the PdfDocumentProcessor object, you can call one of the CreateEmptyDocument overload methods. These methods have been introduced to reduce memory consumption and improve performance.

For example, here we can see the CreateEmptyDocument method is called with some PdfCreationOptions.

            using (PdfDocumentProcessor processor = new PdfDocumentProcessor())
            {
                processor.CreateEmptyDocument("..\\..\\Document.pdf", new PdfCreationOptions()
                {
                    Compatibility = PdfCompatibility.PdfA2b,
                    DisableEmbeddingAllFonts = false
                });
            }

The document creation options are represented by an instance of the PdfCreationOptions class and contains the following settings:

  • Compatibility property - specifies PDF compatibility. This property returns one of the three enumeration values: Pdf, PdfA2b, and PdfA3b. The Pdf compatibility allows you to perform most operations with a document (e.g., document merging, page insertion and deletion), while the PdfA2b, and PdfA3b compatibility can be used only for document creation.
  • DisableEmbeddingAllFonts property - specifies whether to prohibit embedding all fonts in a PDF document. You can set this property to true if you wish to not embed all fonts in a PDF document (e.g, the font could not be embedded due to licensing).
  • NotEmbeddedFontFamilies property- specifies font families list that should not be embedded to a PDF document.

The CreateEmptyDocument method can be called using save options represented by an instance of the PdfSaveOptions class. This class contains encryption options and PDF signature specified using the PdfSaveOptions.Signature property. The encryption options are used to protect a document with a password and permissions. These options can be accessed via the PdfSaveOptions.EncryptionOptions property.

Once the document has been created you can add graphics to it.

        void doSomething()
        {
            // PdfDocumentProcessor
            using (PdfDocumentProcessor processor = new PdfDocumentProcessor())
            {
                processor.CreateEmptyDocument("..\\..\\Document.pdf", new PdfCreationOptions()
                {
                    Compatibility = PdfCompatibility.PdfA2b,
                    DisableEmbeddingAllFonts = false
                });

                using (PdfGraphics graph = processor.CreateGraphics())
                {
                    DrawGraphics(graph);
                    processor.RenderNewPage(PdfPaperSize.Letter, graph);
                }
            }
        }

        private void DrawGraphics(PdfGraphics graph)
        {
            SolidBrush black = (SolidBrush)Brushes.Black;
            using (Font font = new Font("Times New Roman", 32, FontStyle.Bold))
            {
                graph.DrawString("PDF Document Processor", font, black, 180, 150);
            }
        }

Drawing any type of graphic content on a document requires an instance of the PdfGraphics class, so you will need to reference the DevExpress.Pdf.Drawing assembly. To draw graphics, create a PdfGraphics object using the PdfDocumentProcessor.CreateGraphics method and call the Draw method for corresponding elements (e.g., the DrawString method at the specified location with the specified SolidBrush and Font objects).

To render a page with created graphics, call the PdfDocumentProcessor.RenderNewPage method, this optimizes memory usage (the resources that belong to the different pages are not doubled).

Adding Hyperlinks

The PdfGraphics class also contain methods that allow you to add links to a page or URI using either the corresponding PdfGraphics.AddLinkToPage or PdfGraphics.AddLinkToUri method. To add a link to a page, you need to supply an area, page number, and, if necessary, zoom factor and link destination to one of the AddLinkToPage overload methods. The link to URI is created using URI and link area as arguments of the AddLinkToUri method.

        private void AddHyperlinks(PdfGraphics graph)
        {
            // Create a link to a page specifying link area, the page number and X, Y destinations.
            graph.AddLinkToPage(new RectangleF(180, 160, 480, 30), 1, 168, 230);
            // Create a link to URI specifying link area and URI.
            graph.AddLinkToUri(new RectangleF(110, 350, 180, 15), new Uri("https://www.devexpress.com"));
        }

Bookmarks Creation

The Document Creation API provides properties and methods to generate bookmarks via code.

A PDF bookmark is represented by an instance of the PdfBookmark class. It can be accessed as an item of the PdfBookmark objects list returned by the PdfDocument.Bookmarks property. The PdfBookmark class contains the following properties to customize bookmarks:

 

 

Action

Provides access to the bookmark action being executed.

 

Children

Specifies the collection of bookmark children for a document with a tree-structured hierarchy.

 

Destination

Gets or sets a destination (a particular view of a document) to which a bookmark is referred to

 

IsBold

Gets or sets the value indicating whether the bookmark text is formatted as bold.

 

IsInitiallyClosed

Gets or sets a value that indicates whether bookmarks are initially closed (bookmark children are hidden) in the navigation panel after a document is loaded.

 

IsItalic

Gets or sets the value indicating whether the bookmark text is formatted as italic.

 

TextColor

Gets or sets the color for a bookmark’s text in the navigation pane.

 

Title

Gets or sets the text that is displayed for a bookmark on the navigation pane.

Below you can see an example of creating bookmarks via code using one of the PdfDocumentProcessor.CreateDestination overload methods, passing in a page number and page coordinates.

        private void AddBookmarks(PdfDocumentProcessor processor)
        {
            PdfDestination destination1 = processor.CreateDestination(1, 180, 150);
            PdfDestination destination2 = processor.CreateDestination(1, 168, 230);
            PdfDestination destination3 = processor.CreateDestination(1, 20, 350);
            processor.Document.Bookmarks.Add(new PdfBookmark()
            {
                Title = "PDF Document Processor",
                Destination = destination1
            });
            processor.Document.Bookmarks.Add(new PdfBookmark()
            {
                Title = "Display, Print and Export PDF Documents",
                Destination = destination2
            });
            processor.Document.Bookmarks.Add(new PdfBookmark()
            {
                Title = "Learn More",
                Destination = destination3
            });
        }

File Attachments

You can attach a file to PDF by calling the PdfDocumentProcessor.AttachFile method as shown below.

        private void AttachFile(PdfDocumentProcessor processor)
        {
            processor.AttachFile(new PdfFileAttachment()
            {
                CreationDate = DateTime.Now,
                Description = "This is a sample attached file.",
                MimeType = "text/plain",
                FileName = "MyAttachment.txt",
                Data = GetData()
            });
            processor.SaveDocument("..\\..\\Result.pdf");
        }

        private byte[] GetData()
        {
            string s = "sample text inside my attached document.";
            byte[] data = Encoding.ASCII.GetBytes(s);
            return data;
        }

The file attachments is represented by an instance of the PdfFileAttachment class. You can specify the attachment creation date, description, mime type, file name, and relationship using PdfFileAttachment.CreationDate, PdfFileAttachment.Description, PdfFileAttachment.MimeType, PdfFileAttachment.FileName, and PdfFileAttachment.Relationship properties. A data source must be specified by using the PdfFileAttachment.Data property.

Inversely, you can get access to an existing attachments via the PdfDocument.FileAttachments property.

To delete an attachment, call the PdfDocumentProcessor.DeleteAttachment method.

=========================

We'd love to hear your thoughts on these new enhancements. Let us know what you think.

6 comment(s)
John01
John01

What about AcroForm fields and tables?

11 November, 2015
Paul Usher (DevExpress)
Paul Usher (DevExpress)

Hi John, AcroForm fields were added in 15.1 earlier in the year, please check out: community.devexpress.com/.../filling-the-forms-programmatically.aspx

11 November, 2015
Brendon Muck [DevExpress MVP]
Brendon Muck [DevExpress MVP]

Are we able to draw polygons onto an existing PDF file (like placing a stamp onto an invoice PDF) or do we have to start with a blank PDF created by the document processor?

11 November, 2015
Paul Usher (DevExpress)
Paul Usher (DevExpress)

Hi Brendon, you have been able to place polygon objects on a page since 15.1, so no, you don't need a blank PDF to achieve this.  This is different to an 'annotation' though, you are just drawing a graphic at a set place. Hope this helps.

11 November, 2015
Roy Eriksson
Roy Eriksson

Will there still be overloads added to DrawString for alignment or word wrapping?

www.devexpress.com/.../T258414

Thanks,

Frank

24 November, 2015
Paul Usher (DevExpress)
Paul Usher (DevExpress)

Yes Frank, you can still use the new overloads.

24 November, 2015

Please login or register to post comments.