What's New in Documents for PDF v6
GcPdf v6.2 - August 9, 2023
GrapeCity Documents for PDF (GcPdf)
Improvements in processing existing PDF documents produced by software other than GcPdf
With the new v6.2 release, GcPdf enhances loading and saving of PDF documents and provides following advantages:
-
GcPdf can now load and save PDF documents that may not be strictly compliant with the PDF specification.
-
GcPdf will now preserve any custom data embedded in PDF documents that is not part of the PDF specification.
-
The average speed of loading PDF documents has been improved.
Due to changes in how GcPdf works with loaded PDFs, some of the lower level GcPdf APIs had to be changed, which may require minor changes in your code if it uses those APIs, please see /documents-api-pdf/docs/online/Version6.2.0.html for the complete list of the affected APIs.
Work with password protected files without specifying the password
GcPdf now allows working with password protected files without specifying the password. After loading a password protected file, you can now perform following, without specifying the password:
-
Read/Write properties which are not based on PDF string objects, for example:
-
you can get/set values of CheckBoxField or RadioButtonField.
-
fetch certain document’s statistics, e.g. get the count of pages, annotations etc.
-
get or change the document metadata, because typically the metadata is not encrypted.
-
change the value of some types of fields: CheckBoxField, RadioButtonField; the values of TextBoxField, CombTextField can be changed but with some limitations
-
-
You can add new objects if they can be defined without using of PDF strings, for example, you can add a SquareAnnotation to a page or all pages.
New DecryptionOptions class has been introduced that represents the decryption options. You can pass it as an (optional) argument to the GcPdfDocument.Load() method when loading an encrypted PDF. In particular, you can set the DecryptionOptions.ThrowExceptionIfInvalidPassword flag to false (it is true by default) to allow loading password-protected PDFs without specifying their passwords. Another related flag is DecryptionOptions.ThrowExceptionIfUnsupportedSecurityOptions. It is also true by default, setting it to false allows GcPdf to load documents with unknown or broken security handlers.
The following code adds an annotation to a password-protected PDF without specifying the password -
New API for working with low-level PDF primitives (GrapeCity.Documents.Pdf.Spec and GrapeCity.Documents.Pdf.Wrappers namespaces)
In this release, GcPdf introduces a new API that allows developers who are familiar with the PDF specification to directly access the primitive PDF objects which are the building blocks of any PDF document. These include:
-
PDF array, see GrapeCity.Documents.Pdf.Spec types PdfArray, PdfArrayObject, IPdfArray, IPdfArrayExt and and GrapeCity.Documents.Pdf.Wrappers.PdfArrayWrapper.
-
PDF bool, see GrapeCity.Documents.Pdf.Spec types PdfBool, PdfBoolObject, IPdfBool and IPdfBoolExt.
-
PDF dictionary, see GrapeCity.Documents.Pdf.Spec types PdfDict, PdfDictObject, IPdfDict, IPdfDictExt, and GrapeCity.Documents.Pdf.Wrappers.PdfDictWrapper.
-
PDF name, see GrapeCity.Documents.Pdf.Spec types PdfName, PdfNameObject, IPdfName and IPdfNameExt.
-
PDF null, see GrapeCity.Documents.Pdf.Spec types PdfNull, PdfNullObject, IPdfNull and IPdfNullExt.
-
PDF number, see GrapeCity.Documents.Pdf.Spec types PdfNumber, PdfNumberObject, IPdfNumber and IPdfNumberExt.
-
PDF reference, see GrapeCity.Documents.Pdf.Spec types PdfRef, PdfRefObject, IPdfRef and IPdfRefExt.
-
PDF stream, see GrapeCity.Documents.Pdf.Spec.PdfStreamObjectBase.
-
PDF string, see GrapeCity.Documents.Pdf.Spec types PdfString, PdfStringObject, IPdfString and IPdfStringExt.
These new APIs can be used, for instance, to access custom properties that are sometimes added by PDF producers but are not described in the PDF spec. For example, the DocumentInfo object is a PDF dictionary. The PDF specification lists the properties which can be present in this dictionary (Creator, Author, etc.), but in many real life PDF files the DocumentInfo dictionary includes a "SourceModified" property which is absent in the PDF spec. The types from the GrapeCity.Documents.Pdf.Spec namespace now allow developers to access/edit such custom items.
Please see the GcPdf reference for more information on the GrapeCity.Documents.Pdf.Spec and GrapeCity.Documents.Pdf.Wrappers namespaces.
Example: Fetch Image properties
Using above new API, many of the PDFs created by image scanners (most of which consist of only one JPEG or G4 TIFF image per page) can now be processed with the images retrieved from the stream. GcPdf includes new PdfImageInfo class which is a descendant of new PdfDictWrapper object. The class includes a lot of methods which allow to get properties/data of underlying PDF stream object. This addition would retrieve stream images and directly decompress or process image.
You can retrieve following image properties -
-
Directly retrieve the stream for each image on each page (retrieved with GetImages()).
-
Retrieve the compression format of the above image stream (Filter)
-
Retrieve black and white information of the above image stream (Decode or BlackIs1)
-
Retrieve information that can identify the color of the above image stream (ColorSpace or BitsPerComponent)
-
Retrieve the stream and each information of each mask (ImageMask)
-
and more..
Following code retrieves image properties from a PDF stream.
Set Format in TextField
GcPdf now allows users to specify date, time, number formats and special formats to TextField in an intuitive way using new direct methods SetPercentFormat, SetNumberFormat, SetDateFormat, SetTimeFormat, SetSpecialFormat methods added to TextField, CombTextField, ComboBoxField classes. The new methods would support setting properties similar to the TextField properties in Acrobat.
New enums SpecialFormat, CurrencySymbolStyle, NumberNegativeStyle and NumberSeparatorStyle have been added. These are used as parameters in above methods.
Following code sets number value on TextField using the new method and parameters.
Helper classes for drawing layouts to GcGraphics
In last release, GcPdf, GcImaging added new layout engine, introducing LayoutRect and other related classes in the GrapeCity.Documents.Layout namespace to implement a layout model based on constraints and a flat hierarchy of elements where multiple elements are drawn on a PDF page or images, without calculating positions of each elements relative to other. The new layout engine thereby adds flexibility to position and size the elements enabling drawing of complex graphic layouts on PDFs and images.
In v6.2 release, GcPdf, GcImaging add additional classes - Surface, Layer, View, Space, and Visual classes in GrapeCity.Documents.Layout.Composition namespace that act as a medium between the layout engine and the drawing surface making it easier to draw even more complex graphics, text and images. Here is a brief about the functions of these classes -
-
Surface is the main class in the Composition engine. It contains a LayoutHost (which is the root object of the layout engine) and one or several views (layers). Layers consist of visuals (drawable elements) and nested layers. The Render method of Surface class calls PerformLayout method of LayoutHost class to calculate the surface layout and then it draws all the layers, including nested ones, from the bottom to the top layer on the specified GcGraphics object.
-
Layers are of two types: Layer and View class objects (derived from Layer objects). The View object encapsulates the LayoutView object, which represents a separate coordinate system with its own transformation matrix. The Layer object functions as a lightweight View with its own list of visuals, nested layers, and possible clipping area.
-
Layers contain Visuals and Spaces. The Space object represents a LayoutRect that may affect the layout of other elements but is never drawn itself. The Visual class derives from the Space class. Visual class represents an element that will be drawn on the target GcGraphics.
Furthermore, these classes also enable you to customize the z-order and clipping of the drawn graphics. For example, it is possible to compose a PDF page from a number of visuals, then further adjust those visuals before rendering to the document. Some visuals or layers can be hidden, other moved in z-order and so on.
Additional API is also introduced to achieve various layouts. To read about the new classes and function of each, refer to documentation.
Here is an example of a really complex layout that can be achieved using these API.
See this online demo for the full source code that is used to produce this layout - Documents for PDF | Text Flow (C#)
GrapeCity Documents PDF Viewer (GcPdfViewer)
Document List panel enhancements
GcPdfViewer now supports enhancing the Document List panel using custom HTML markup. GcPdfViewer provides name, path, title, and previewContent properties in DocumentListItem type that allow the user to specify custom HTML markup to represent the documents' list. Following is a brief description of the properties.
-
name - Display name of the Document list item.
-
path - Absolute or relative URL to a PDF document.
-
title - Item tooltip.
-
previewContent - the HTML content to be used as the preview content in the document list.
The existing client-side properties and methods - documentListUrl option and addDocumentListPanel and loadDocumentList methods have been enhanced to accept DocumentListItem as a parameter to specify a predefined list of document list items.
Following code sets properties to the first tile ‘Finance’ in the Document list panel.
For full code, please have a look on this demo.
Keyboard Shortcuts
GcPdfViewer supports several keyboard shortcuts that can make working with PDF documents in the viewer more efficient. GcPdfViewer also supports redefining, disabling, overriding, and removing the default keyboard shortcuts, as well as binding the default keyboard shortcuts to other keys and creating custom keyboard shortcuts via API using shortcuts option of ViewerOptions class.
GcPdfViewer also supports redefining, disabling, overriding, and removing the default keyboard shortcuts, as well as binding the default keyboard shortcuts to other keys and creating custom keyboard shortcuts via API using shortcuts option of ViewerOptions class.
Following code helps to bind holdToPan action to 'P' key.
GcPdf v6.1 - April 19, 2023
GrapeCity Documents for PDF (GcPdf)
New ClonePage method
Merging PDF documents has been possible before using GcPdf API - GcPdfDocument.MergeWithDocument method. With v6.1 release, it will also be possible to clone a page within a PDF document. Use the new PageCollection.ClonePage(..) method to duplicate a page of a PDF at a certain index, and place it at another index within the same PDF. You can also control whether to include annotations or form fields in the cloned page.
Following code can be used to clone pages. The first parameter specifies index of page that needs to be cloned, while the next one is the target index at which the cloned page will be inserted. The optional parameters cloneAnnotations and cloneFields are omitted here. They are true by default, so any annotations and fields will also be cloned.
GcPdfDocument doc = new GcPdfDocument();
using (var fs = new FileStream("realestate-lease-pdf.pdf", FileMode.Open, FileAccess.Read))
{
doc.Load(fs);
doc.Pages.ClonePage(0, 1);
doc.Save("ClonedDoc.pdf");
}
InterpolationMode moved to GcGraphics
InterpolationMode property can now be set using GcGraphics object. The property is also added to SaveAsImageOptions class when saving PDF to images. The property now allows you to control interpolation mode in a common way for all implementations of GcGraphics i.e. format-specific types of graphics such as GcPdfGraphics, GcBitmapGraphics, GcSvgGraphics, GcSkiaGraphics, GcWicBitmapGraphics, GcD2DBitmapGraphics.
GcPdf supports InterpolationMode property in the SaveAsImageOptions class, which will be utilized to set interpolation mode while drawing images in PDF files or saving the PDF files as images. The default value of SaveAsImageOptions.InterpolationMode is InterpolationMode.Downscale.
Note: The interpolation mode only affects the way raster images are drawn on a graphic, i.e., the result of DrawImage method and raster image resizing.
Following code helps to set interpolation mode while saving GcPdfDocument object to image.
// set the interpolation mode when saving a PDF document to the image
SaveAsImageOptions opts = new SaveAsImageOptions();
opts.InterpolationMode = InterpolationMode.Linear;
doc.SaveAsPng("doc.png", null, opts);
Draw Table using new TableRenderer class
New TableRenderer class is added to render table layout on PDF and images. With this class, you won’t need to know the size of table columns, merged cells or the layout of rotated text. All complex details of table resizing are automatically adjusted by the layout engine. You would just need to provide information about the desired layout, style, and content.
TableRenderer class is built on top of new layout engine describe in the topic before. LayoutHost, LayoutView and LayoutRect provide the initial space for the TableRenderer. All table rows, columns, vertical and horizontal grid lines, and cells have the associated LayoutRect objects.
A TableRenderer instance takes multiple parameters. Please refer to the API<to link> for details of each parameter.
Following is basic definition of defining a table using TableRendererAPI class.
var ta = new TableRenderer(
page.Graphics,
tableRect, FixedTableSides.TopLeftRight,
rowCount: 5,
columnCount: 4,
gridLineColor: Color.Coral,
gridLineWidth: 3,
rowMinHeight: 30);
You can also add cells to the table and add text to it using AddCells(..) method that accepts data as parameter. Also included is AddMissingCells(..) method that ensures there is no gaps around the cells and also accepts data as a parameter.
Overall, with the various options in the new API, you can create a table with many complex layouts, one like below -
Following are certain scenarios you can cover with TableRenderer API -
-
Draw simple tables or tables with complex layout
-
Merge table cells
-
Rotate or set flow direction of text in cells
-
Draw custom content in cell.
Have a look on detailed demos to check various codes on how to draw tables with different layouts.
GrapeCity Documents PDF Viewer (GcPdfViewer)
Introducing 'PDF organizer'
GcPdfViewer introduces new 'PDF Organizer' dialog to help you organise PDF pages in the viewer. The tool can help -
-
Reorder individual pages or page ranges of a PDF
-
Duplicate or remove individual pages or page ranges
-
Rotate all or some pages of a PDF
-
Merge external PDFs into the current document
-
Split the current document into several PDFs
-
Download the modified PDF to your local file system, or apply changes and continue editing the document
The PDF Organizer also provides an API that allows you to access all of its functionality programmatically from code.
Following code splits a PDF into two.
// Split PDF into two documents:
viewer.save("test_part1.pdf", { pages: "0-3" });
viewer.save("test_part2.pdf", { pages: "4-8" });
Note: PDF Organizer is available in Quick Edit Page tools, Annotation and Form Editor. This tool is available only in Professional Version. In order to add this tool to the viewer, you need to configure Support API.
Support range of magnifications for optional content group (layers)
PDF documents can contain content in different layers (also known as optional content) and a particular layer can be made visible or invisible as required. GcPdf allows you to work with layers and set their properties, refer to Layers for more information. In GcPdf Viewer, you can examine these layers and show or hide content associated with each layer by using the 'Layers' panel, provided in its sidebar.
According to the PDF 2.0 spec, groups of optional content layers in a PDF can be associated with specific ranges of magnifications (zoom values) at which they should be made visible in a compliant viewer. This is now supported by GcPdfViewer, so if a PDF that has such zoom-dependent layers is loaded into the viewer, the layers will be automatically shown or hidden depending on the current zoom factor.
Display PDF with Initial View settings
GcPdfViewer supports display of PDF documents with initial view settings. Additionally, the viewer provides viewerPreferences client-side API to get information about the initial PDF view settings set by a user, and opens the PDF document in those settings similar to Acrobat. You can use following settings through code -
-
viewerPreferences: Gets the initial viewer preferences information set by a user.
-
openAction: Gets the initial open action information set by a user.
-
pageMode: Gets the initial page mode information set by a user.
-
pageLayout: Gets the initial page layout information set by a user.
-
hideToolbar: A flag specifying whether to hide the tool bars when the document is active.
-
hideMenubar: A flag specifying whether to hide the menu bar when the document is active.
-
nonFullScreenPageMode: Used to specify full screen mode.
-
Digital Signature API
Support for document signing API
You can now sign PDF documents using new Client-side document signing API. New ‘SignatureInfo’ class is introduced to specify signature information needed to sign the document. You can specify contact info, location, signer name, reason and signature field to sign a document. The client-side ‘viewer.save’ method includes an optional SaveSettings parameter that can be used to specify signature settings or 'SignatureInfo' for saving a document with a signature.
The following client-side code causes the current PDF to be electronically signed using the new API (note though that the actual signing takes place on the server, the client code tells the server to sign the PDF, and reloads the signed document):
function configureViewerUI(viewer) {
viewer.toggleSidebar(false);
viewer.toolbar.addItem({ text: "Apply employee signature", key: 'employee-signature',
title: 'Apply employee signature',enabled: false,
action: function() {
const locationName = location.hostname || "Unknown";
viewer.save(undefined, { sign: { signatureField: "Employee", signerName: "Employee Name", location: locationName }, reload: true } );
},
onUpdate: function() {
return {
enabled: viewer.hasDocument,
title: 'Apply employee signature'
};
}
});
You can also find server-side implementation of applying .pfx certificate on the signature in the resources below.
Check if document is signed
GcPdfViewer allows you to check whether the current PDF is signed, and if so, which field was used to sign the document. New asynchronous client side method getSignatureInfo has been added for getting information about all signature fields available in a document. With the new method, you can -
-
Get signature information using signatureInfo object
-
Test if the document is signed or not using signed property
-
Get array of signature fields used to sign the document
-
Get array of all signature fields in the document
-
Get Signature values using signatureValue property like - signerName, location and signedDate.
Following code displays information about all signatures used in the document.
var viewer = GcPdfViewer.findControl("#root");
const signatureInfo = await viewer.getSignatureInfo();
if(signatureInfo.signed) {
let s = "";
for(let i = 0; i < signatureInfo.signedByFields.length; i++) {
const signedField = signatureInfo.signedByFields[i], signatureValue = signedField.signatureValue;
const signerName = signatureValue.name, location = signatureValue.location,
signDate = viewer.pdfStringToDate(signatureValue.modificationDate).toDateString();
s += `${i + 1}. Signed by field: ${signedField.fieldName}, signer name: ${signerName}, location: ${location}, sign date: ${signDate}\n`;
}
alert("The document was signed using digital signature:\n" + s);
} else {
alert("The document is not signed.");
}
See complete usage of signatureInfo method below.
Save PDF options
When saving a PDF, the GcPdfViewer’s save() method now allows you to save the document using incremental update (needed when signing an already signed PDF), or to save it as a linearized PDF file (optimized for fast internet viewing). The ‘viewer.save’ method has been enhanced with added optional SaveSettings class.
The SaveSettings class includes saveMode enum that can take in various save modes like ‘Default’, ‘Linearized’ and ‘IncrementalUpdate’.
viewer.save("test.pdf", { saveMode: "IncrementalUpdate" });
GcPdf v6 - December 15, 2022
GrapeCity Documents for PDF (GcPdf)
Rendering HTML to PDF and Raster Images
GcPdf v6 release has updated the existing GrapeCity.Documents.Html (GcHtml) package with new API for converting HTML markup to PDF. The new package does not depend on a custom build of Chromium and does not include any GPL or LGPL licensed code. Also, GcHtml no longer requires any platform dependent packages specific to Windows, macOS and Linux, as required by the previous version of GcHtml. The package introduces GcHtmlBrowser class - the main licensed class which represents a browser process, such as Chrome, Edge, or Chromium browser, and BrowserFetcher class that helps with discovering the path to the browser or downloading the Chromium browser from the public server. An instance of GcHtmlBrowser has two important methods: NewPage(Uri uri) and NewPage(string html). Both methods return an instance of HtmlPage class which represents a browser tab after navigating to the specified web address, file, or the arbitrary HTML content.
-
No dependencies on custom Chromium build.
-
No dependency on GPL/LGPL licensed software
-
Use the same browser instance to render multiple pages
-
Modify/replace the HTML page content
There is a lot more to the introduction of the new GcHtml package. Have a look on following resources to read more on how to use this package.
- Steps to migrate old project to use new packages
- Steps from scratch to convert HTML to PDF/Images
- GrapeCity Documents for HTML Product Architecture
- View full blog: Import HTML to PDF documents
- Demo
Support for Appearance streams for all annotations
To render annotations with the same display in all viewers, Appearance streams are associated with annotations - these are optional settings part of the PDF specification. GcPdf now supports an appearance stream for all annotations it supports, thereby rendering the annotations exactly with the same appearance in any viewer. Please note - In this version, GcPdf cannot generate correct appearance streams for rich text.
Additionally, in the v6 release, GcPdf adds GcPdfDocument.BuildRichTextAppearanceStreams boolean property, which generates content streams for annotations having rich text. This property is false by default, so the content streams with rich text are not generated, and viewers supporting rich text can render these annotations the same as before. If set to true, GcPdf will generate the content streams using plain text so that the rich text will be lost, but the annotation will look the same in all viewers. In the snapshot below, this property is set to false, so the free text annotation with rich text is shown correctly. The appearance of annotations is the same as rendered in Acrobat.
View Help
GrapeCity Documents PDF Viewer (GcPdfViewer)
Support for Text Markup Annotations
Now highlight, strikeout, underline text or add squiggly line with new set of annotations in GcPdfViewer. Following options are added -
- New toolbar for Highlight, Underline, Squiggly and StrikeOut annotations in Quick edit tools and Annotation Editor.
-
Text markup context menu with new options visible when the text is selected. The options are also added to the default context menu
-
Button keys for new annotations to add in the toolbar -'edit-highlight', 'edit-underline', 'edit-squiggly', 'edit-strike-out'.
-
Enable or disable Text markup context menu.
- Change list of colors available in context menu through code.
Save PDF pages as Images
You can now save PDF pages as images from the viewer. GcPdfViewer client API adds a new saveAsImages method - to save pages of the current PDF document as PNG images. The option zips the resultant images and downloads the result zip archive on the client side. The ‘Save as images’ button can be added to ‘Annotation Editor' or ‘Form Editor’ with the button key - "save-images".
The following code can be used to save the images and specify resultant zip file name programmatically:
// Save the pages of the current PDF document as PNG images and specify destination zip file name
viewer.saveAsImages('images.zip');
Updates
- Improvements in processing existing PDF documents
- Work with password protected files without specifying the password
- New API for working with low-level PDF primitives
- Set Format in TextField
- Helper classes for drawing layouts to GcGraphics
- GrapeCity Documents PDF Viewer (GcPdfViewer)
- New ClonePage method
- InterpolationMode moved to GcGraphics
- Draw Table using new TableRenderer class
- GrapeCity's Documents PDF Viewer (GcPdfViewer)
Related Links