Facades API
Facades API
A facade is a simplified, task-oriented wrapper over the core Document /
Page / Annotation object model. Instead of walking the page tree yourself,
you bind a facade to a source PDF, call a small set of high-level methods, and
save the result. Every facade in Aspose::Pdf::Facades implements the same
minimal contract defined by IFacade (BindPdf, Close) and, where the
facade produces output, ISaveableFacade (Save). The abstract Facade and
SaveableFacade base classes provide the default bind/close/save
implementation that the concrete editors below build on: PdfAnnotationEditor,
PdfBookmarkEditor, PdfContentEditor, PdfConverter, PdfExtractor,
PdfFileEditor, PdfFileInfo, PdfFileSecurity, PdfFileSignature,
PdfFileStamp, PdfPageEditor, PdfXmpMetadata, and the form-focused
FormEditor / FormFieldFacade pair.
Facade base classes and the bind/save lifecycle
IFacade declares BindPdf(srcFile) (also overloaded to accept an in-memory
Document) and Close(). ISaveableFacade adds Save(destFile) for facades
that write output. Facade implements IFacade and exposes the bound
Document() so you can drop back into the core object model when a facade
method doesn’t cover what you need; SaveableFacade extends Facade with the
Save implementation. Every concrete editor below inherits this shape, so the
same bind → operate → save pattern applies across the whole Facades API.
Filling and editing AcroForm fields
FormEditor adds, removes, renames, and repositions AcroForm fields on an
already-bound document. AddField(fieldType, fieldName, pageNum, llx, lly, urx, ury) creates a new field of the given FieldType (Text, CheckBox,
Radio, ComboBox, ListBox, PushButton, MultiLineText, Barcode,
Signature, Image, Numeric, DateTime) at the specified page
coordinates. RemoveField, RenameField, MoveField, and SetFieldAttribute
manage existing fields, and SetFieldScript / AddFieldScript attach
JavaScript actions. SubmitFlag (a SubmitFormFlag value — Fdf, Html,
Xfdf, FdfWithComments, XfdfWithComments, or Pdf) controls how a submit
button posts form data, and SetSubmitUrl sets the target endpoint.
The visual appearance each new field gets is controlled through
FormEditor.Facade(), which returns a FormFieldFacade. Its Font property
takes a FontStyle value (Helvetica, HelveticaBold, Courier,
TimesRoman, Symbol, and related variants), TextEncoding takes an
EncodingType (Winansi, Macroman, Identity_h, Identity_v, Cp1250,
Cp1252, Cp1257), and BorderStyle / BorderWidth set the field’s border.
FormEditor editor;
editor.SrcFileName("template.pdf");
editor.DestFileName("output.pdf");
editor.AddField(FieldType::Text, "FirstName", 1, 100, 700, 300, 720);
editor.SetFieldAttribute("FirstName", AnnotationFlags::Print);
editor.Save();Managing outlines with PdfBookmarkEditor
PdfBookmarkEditor creates, extracts, modifies, and removes PDF outline
entries. CreateBookmarks() writes a Bookmarks collection (each entry a
Bookmark with Title, PageNumber, Action, Level, Open, and
ChildItems for nested outlines) into the bound document. ExtractBookmarks()
reads the existing outline back out as a Bookmarks collection, and
DeleteBookmarks() — with an optional title filter — removes entries.
ExportBookmarksToXML / ImportBookmarksWithXML round-trip an outline through
an XML file, and ExtractBookmarksToHTML / ExportBookmarksToHtml render the
outline as an HTML page.
PdfBookmarkEditor editor;
editor.BindPdf("input.pdf");
Bookmarks bookmarks = editor.ExtractBookmarks();
editor.DeleteBookmarks("Draft");
editor.Save("output.pdf");Editing annotations with PdfAnnotationEditor
PdfAnnotationEditor flattens and imports annotations across the whole
document. FlatteningAnnotations() merges annotations into the page content
stream so they render as static content instead of interactive objects; the
overload taking a start/end page range and an annotation type limits the
operation. ImportAnnotationsFromXfdf / ImportAnnotationsFromFdf bring
annotations in from external FDF/XFDF files, and DeleteAnnotations() (or
DeleteAnnotations(annotType) for a single type) removes them.
PdfAnnotationEditor editor;
editor.BindPdf("commented.pdf");
editor.FlatteningAnnotations();
editor.Save("flattened.pdf");Rewriting page content with PdfContentEditor
PdfContentEditor edits an already-generated page’s content stream instead of
rebuilding the page. ReplaceText(srcText, destText) finds and replaces
matching text across the document, with overloads that scope the replacement
to a single page. ReplaceImage(pageNum, imageNum, fileName) and
DeleteImage(pageNum, imageNum) swap or remove an existing image XObject.
DeleteStampById / HideStampById / ShowStampById / MoveStampById manage
stamp objects on a page (a stamp’s underlying content is either Form or
Image, per the StampType enum), and AddDocumentAdditionalAction /
AddDocumentAttachment attach document-level JavaScript actions and file
attachments.
PdfContentEditor editor;
editor.BindPdf("template.pdf");
editor.ReplaceText("{{CustomerName}}", "Jane Doe");
editor.Save("output.pdf");Extracting text and attachments with PdfExtractor
PdfExtractor can be bound either with BindPdf or constructed directly from
an already-open Document. ExtractText() followed by HasNextPageText() /
GetNextPageText(outputFile) walks the document page by page. For embedded
files, GetAttachNames() lists the attachments present and GetAttachment( outputPath) writes the next one to disk:
#include <aspose/pdf/document.hpp>
#include <aspose/pdf/facades/pdf_extractor.hpp>
#include <iostream>
int main() {
Aspose::Pdf::Document doc("attachments.pdf");
Aspose::Pdf::Facades::PdfExtractor extractor(doc);
auto names = extractor.GetAttachNames();
std::cout << "Attachments found: " << names.size() << "\n";
if (!names.empty()) {
extractor.GetAttachment("extracted-attachment.bin");
}
}ExtractImage() / HasNextImage() / GetNextImage(outputFile) extract
embedded raster images the same way GetNextPageText walks pages.
Assembling and splitting files with PdfFileEditor
PdfFileEditor operates on file paths rather than a bound Document, so
every method takes input/output filenames directly. Concatenate (and the
non-throwing TryConcatenate) merges two or more files; Append inserts a
page range from one file into another; Extract pulls a page range or single
page into a new file; Delete removes a page; and SplitFromFirst /
SplitToEnd / SplitToPages / SplitToBulks divide a document at a page, by
page, or into fixed-size chunks. MakeBooklet and MakeNUp rearrange pages
for booklet or N-up printing, and ResizeContents / AddMargins /
AddPageBreak adjust page geometry across a file. Most operations have a
Try-prefixed counterpart that returns false instead of throwing on
failure.
PdfFileEditor editor;
editor.Concatenate("part1.pdf", "part2.pdf", "merged.pdf");
editor.Extract("merged.pdf", 1, 3, "first-three-pages.pdf");Rendering pages to images with PdfConverter
PdfConverter renders bound document pages to raster formats. DoConvert()
prepares the page range (StartPage / EndPage) for iteration; HasNextImage () / GetNextImage(outputFile) then step through the pages one at a time.
SaveAsTIFF writes the whole range to a single multi-page TIFF, with overloads
for resolution, compression, and TiffSettings. RenderingOptions and
Resolution control rasterization quality, and ImageMergeMode
(Vertical, Horizontal, Center) governs how multiple rendered page images
are combined when a caller merges them into one image.
PdfConverter converter;
converter.BindPdf("report.pdf");
converter.Resolution(Aspose::Pdf::Devices::Resolution(150));
converter.DoConvert();
while (converter.HasNextImage()) {
converter.GetNextImage("page.png");
}Encrypting documents with PdfFileSecurity
PdfFileSecurity binds a source file and applies or removes encryption.
EncryptFile(userPassword, ownerPassword, privilege, keySize) encrypts with a
DocumentPrivilege (built with the default constructor and boolean setters
such as AllowPrint, AllowCopy, AllowModifyContents) and a KeySize
(x40, x128, or x256); the overload taking a fifth cipher argument
selects the Algorithm (RC4 or AES) explicitly. DecryptFile( ownerPassword), ChangePassword, and SetPrivilege cover the remaining
password-management cases, each with a non-throwing Try-prefixed variant.
PdfFileSecurity security;
security.BindPdf("input.pdf");
DocumentPrivilege privilege;
privilege.AllowPrint(true);
privilege.AllowModifyContents(false);
security.EncryptFile("user-pass", "owner-pass", privilege, KeySize::x256);Signing and verifying with PdfFileSignature
PdfFileSignature signs, certifies, and inspects digital signatures on a
bound document. Sign(sigName, reason, contact, location, signature) applies
a new signature to an existing signature field; Certify applies a
certifying signature. GetSignatureNames(onlyEmpty) and
GetBlankSignatureNames() return the document’s signature fields as
SignatureName values, and VerifySignature(sigName) / IsCoversWholeDocument (sigName) check validity and coverage. RemoveSignature and
RemoveSignatures() strip existing signatures, and SetCertificate(pfxFile, password) supplies the signing credential before calling Sign.
PdfFileSignature signature;
signature.BindPdf("contract.pdf");
signature.SetCertificate("signing-cert.pfx", "cert-password");
bool signed_ok = signature.ContainsSignature();
signature.Save();Stamping headers, footers, and page numbers with PdfFileStamp
PdfFileStamp overlays repeating content on every page of a bound file.
AddPageNumber(format) stamps a page-number label using a starting number and
optional explicit coordinates; AddHeader(text, topMargin) and
AddFooter(text, bottomMargin) add recurring header/footer text at a given
margin, with overloads for left/right margins. KeepSecurity preserves any
existing encryption on the output file, and Close() finalizes and releases
the bound document.
PdfFileStamp stamp;
stamp.InputFile("input.pdf");
stamp.OutputFile("stamped.pdf");
stamp.AddPageNumber("Page # of #", 1);
stamp.Close();Reading and writing document info with PdfFileInfo
PdfFileInfo reads and rewrites the classic PDF /Info dictionary and basic
per-page geometry without opening the full object model. Author, Title,
Subject, Keywords, CreationDate, and ModDate are read/write
properties; Producer and GetPdfVersion() are read-only. GetPageWidth,
GetPageHeight, and GetPageRotation return per-page geometry by page
number, and IsEncrypted() / HasOpenPassword() / HasEditPassword() report
the document’s protection state. SaveNewInfo(outputFile) writes the changes
back out.
PdfFileInfo info;
info.BindPdf(document);
info.Title("Updated Report Title");
info.SaveNewInfo("output.pdf");Repositioning pages with PdfPageEditor
PdfPageEditor moves, resizes, and rotates page content as a block.
MovePosition(offsetX, offsetY) shifts content on the pages selected by
ProcessPages; Zoom scales it. Alignment (an AlignmentType — Left,
Center, or Right, each obtained from the matching static method) and
VerticalAlignment (a VerticalAlignmentType — Top, Center, Bottom)
control how content is positioned within the target PageSize once
ApplyChanges() runs. GetPageRotation reads a page’s current rotation in
degrees.
PdfPageEditor editor;
editor.BindPdf("input.pdf");
editor.Alignment(AlignmentType::Center());
editor.MovePosition(0, -20);
editor.ApplyChanges();Managing XMP metadata with PdfXmpMetadata
PdfXmpMetadata is a map-like facade over a document’s XMP packet.
Add(key, value), Remove(key), Contains(key) / ContainsKey(key), and
TryGetValue(key, value) manage individual entries; Keys() and Values()
enumerate the whole packet. RegisterNamespaceURI(prefix, namespaceURI)
declares a custom XMP namespace before you add properties in it. Well-known
property names are listed in DefaultMetadataProperties (CreateDate,
CreatorTool, Identifier, ModifyDate, Nickname, Thumbnails, and
others), and PropertyFlag (ReadOnly, Required, NoExport) describes a
registered property’s schema constraints.
PdfXmpMetadata xmp;
xmp.BindPdf(document);
xmp.Add("dc:creator", "Report Generator");
xmp.Save("output.pdf");Tips and Best Practices
- Every facade follows the same
BindPdf(or a filename-taking constructor) → operate →Save/Closesequence — learning one facade transfers directly to the next. - Prefer the
Try-prefixed methods onPdfFileEditorandPdfFileSecuritywhen processing files from an untrusted or unpredictable source — they returnfalseon failure instead of throwing. PdfFileEditormethods take file paths, not a boundDocument— you don’t need to open the source file yourself before callingConcatenate,Extract, orSplitFromFirst.- Facades wrap the core object model rather than replacing it:
Facadeexposes the underlyingDocument()for cases a facade method doesn’t cover. - Call
Close()(or let the facade go out of scope, where supported) once you’re done with a bound document to release the underlying file handle.
Common Issues
| Issue | Cause | Fix |
|---|---|---|
Save()/SaveNewInfo() writes an unchanged file | BindPdf was never called, or was called after the edits | Always bind the source document before making any facade calls |
EncryptFile succeeds but the document opens without a password prompt | userPassword was left empty | Pass both a user and owner password, or leave user password empty intentionally for owner-only restrictions |
PdfFileEditor.Concatenate throws on a malformed input file | AllowConcatenateExceptions is left at its default | Use TryConcatenate and check the returned bool, or inspect CorruptedItems() |
Field added with FormEditor.AddField renders with the wrong font | FormFieldFacade.Font / TextEncoding were not set before AddField | Configure editor.Facade() (the FormFieldFacade) before adding fields |
PdfFileSignature.Sign fails silently | No certificate was supplied via SetCertificate before signing | Call SetCertificate(pfxFile, password) before Sign or Certify |
FAQ
What is the difference between a facade and the core Document API?
Facades provide a small, task-oriented method surface for one job — filling a
form, merging files, stamping pages. The core API (Document, Page,
Annotation) gives full access to every PDF object. Facades that expose
Document() (via the Facade base class) let you drop back into the core
model for anything a facade method doesn’t cover.
Do I need to call BindPdf before every facade method?
Yes, for facades that implement IFacade — BindPdf (or an equivalent
constructor overload, as with PdfExtractor(doc)) must run before any
operation that reads or modifies the bound document.
Can PdfFileEditor operations be chained?
Each PdfFileEditor method reads its own input file and writes its own
output file, so you chain operations by feeding one method’s output file into
the next call’s input file — for example, Concatenate into merged.pdf,
then Extract from merged.pdf.
Which facades support a non-throwing error mode?
PdfFileEditor (TryConcatenate, TryAppend, TryExtract, TrySplitFromFirst,
and related Try* methods) and PdfFileSecurity (TryEncryptFile,
TryDecryptFile, TrySetPrivilege, TryChangePassword) both offer
Try-prefixed alternatives that return bool instead of throwing.
API Reference Summary
| Class / Method | Description |
|---|---|
IFacade | Base interface: BindPdf, Close |
ISaveableFacade | Adds Save(destFile) to IFacade |
Facade | Default IFacade implementation; exposes the bound Document() |
SaveableFacade | Facade plus the default Save implementation |
FormEditor | Add, remove, rename, and script AcroForm fields |
FormFieldFacade | Font, encoding, border, and alignment for fields added by FormEditor |
FieldType | AcroForm field kind: Text, CheckBox, Radio, ComboBox, ListBox, PushButton, MultiLineText, Barcode, Signature, Image, Numeric, DateTime |
SubmitFormFlag | Submit-button data format: Fdf, Html, Xfdf, FdfWithComments, XfdfWithComments, Pdf |
DataType | External data-source format for form data (FDF, XML, XFDF, PDF, OLEDB, ODBC) |
WordWrapMode | Field text wrapping: Default, ByWords |
PdfBookmarkEditor | Create, extract, modify, and delete PDF outline entries |
Bookmark / Bookmarks | Single outline entry / outline collection, with Title, PageNumber, Action, ChildItems |
PdfAnnotationEditor | Flatten and import annotations across a document |
PdfContentEditor | Replace text/images and manage stamps in existing page content |
StampType | Stamp content kind: Form, Image |
PdfExtractor | Extract page text, images, and file attachments |
PdfFileEditor | Concatenate, split, extract, resize, and rearrange pages across files |
PdfConverter | Render bound-document pages to TIFF/raster image output |
ImageMergeMode | How multiple rendered page images are combined: Vertical, Horizontal, Center |
PdfFileSecurity | Encrypt, decrypt, and change passwords/privileges on a file |
Algorithm | Encryption cipher: RC4, AES |
KeySize | Encryption key length: x40, x128, x256 |
PdfFileSignature | Sign, certify, verify, and remove digital signatures |
SignatureName | Name/full-name pair identifying a signature field |
PdfFileStamp | Add page numbers, headers, and footers to every page |
PdfFileInfo | Read/write /Info metadata and per-page geometry |
PdfPageEditor | Move, resize, rotate, and align page content |
AlignmentType | Horizontal alignment: Left, Center, Right |
VerticalAlignmentType | Vertical alignment: Top, Center, Bottom |
AutoRotateMode | Automatic page rotation: None, ClockWise, AntiClockWise |
PositioningMode | Layout positioning mode: Legacy, ModernLineSpacing, Current |
PdfXmpMetadata | Read, write, and enumerate a document’s XMP packet |
DefaultMetadataProperties | Well-known XMP property names (CreateDate, Identifier, ModifyDate, …) |
PropertyFlag | XMP schema property constraint: ReadOnly, Required, NoExport |
FontStyle | Standard font used by FormFieldFacade: Helvetica, Courier, TimesRoman, Symbol, and bold/italic variants |
EncodingType | Text encoding used by FormFieldFacade: Winansi, Macroman, Identity_h, Identity_v, Cp1250, Cp1252, Cp1257 |