Document, Page, and Rendering Fundamentals

Document, Page, and Rendering Fundamentals

Document, Page, and Rendering Fundamentals

Aspose::Pdf::Document is the entry point for nearly every operation in Aspose.PDF FOSS for C++: opening and saving files, walking the page collection, reading and writing metadata, rendering pages to raster images, and applying encryption. This page covers the core Document-centered API surface in depth; more specialized areas — page-level graphics primitives, annotations and interactive forms, and the facade helper classes — have their own developer-guide pages.


Document Loading, Saving, and Optimization

Construct a Document from a file path to open an existing PDF, or use the default constructor to start a new, empty document. Save() writes changes either back to the original path or to a new file. Optimize() and OptimizeResources() remove unused or duplicated resources to shrink the output file.

#include <aspose/pdf/document.hpp>

int main() {
    // Open an existing document.
    Aspose::Pdf::Document doc("input.pdf");

    // ... make edits ...

    doc.Optimize();
    doc.OptimizeResources();
    doc.Save("output.pdf");

    // Start a brand-new, empty document.
    Aspose::Pdf::Document blank;
    blank.Pages().Add();
    blank.Save("new.pdf");
}

Page Management

Document::Pages() returns a PageCollection. Pages are 1-indexed — Pages()[1] is the first page. Add() appends a blank page and returns it, Insert(pageNumber) inserts one at a specific position, and Delete() removes pages by index or in bulk. Each Page exposes MediaBox(), CropBox(), and Rotate() for its geometry and orientation.

#include <aspose/pdf/document.hpp>
#include <aspose/pdf/rotation.hpp>

int main() {
    Aspose::Pdf::Document doc("input.pdf");
    auto& pages = doc.Pages();

    std::cout << "Page count: " << pages.Count() << "\n";

    auto newPage = pages.Add();          // append
    pages.Insert(1);                     // insert a blank page at position 1
    pages.Delete(pages.Count());         // remove the last page

    doc.Pages()[1].Rotate(Aspose::Pdf::Rotation::on90);
    doc.Save("output.pdf");
}

Document Metadata

Document::Info() returns a DocumentInfo object with read/write access to standard /Info dictionary entries: Title, Author, Creator, Subject, Keywords, Producer, and Trapped. Document::Metadata() returns the XMP Metadata dictionary for custom, namespaced key/value pairs.

#include <aspose/pdf/document.hpp>
#include <iostream>

int main() {
    Aspose::Pdf::Document doc("input.pdf");

    auto& info = doc.Info();
    std::cout << "Title: " << info.Title() << "\n";
    std::cout << "Author: " << info.Author() << "\n";

    info.Title("Quarterly Report");
    info.Author("Finance Team");

    doc.Save("output.pdf");
}

Rendering to Raster Images

Page-rendering devices convert a single Page into a raster image. BmpDevice, PngDevice, JpegDevice, and TiffDevice all expose Process(page, output) and are constructed with a Resolution controlling output DPI. TiffDevice additionally accepts TiffSettings (compression, color depth) and can render a page range in one call via Process(document, fromPage, toPage, output).

#include <aspose/pdf/document.hpp>
#include <aspose/pdf/bmp_device.hpp>
#include <aspose/pdf/resolution.hpp>
#include <sstream>

int main() {
    Aspose::Pdf::Document doc("report.pdf");
    auto page = doc.Pages()[1];

    Aspose::Pdf::Devices::BmpDevice device(Aspose::Pdf::Devices::Resolution(150));
    std::stringstream sink(std::ios::binary | std::ios::out | std::ios::in);
    device.Process(page, sink);

    std::cout << "Rendered " << sink.str().size() << " bytes\n";
}

RenderingOptions, accepted by several devices, controls font handling and image interpolation during rasterization — for example SystemFontsNativeRendering() and InterpolationHighQuality().


Encryption and Access Permissions

Document::Encrypt(userPassword, ownerPassword, permissions, cryptoAlgorithm) protects a document. The user password is required to open the file; the owner password is required to change permissions or remove protection. CryptoAlgorithm selects the cipher (RC4x40, RC4x128, AESx128, AESx256); Permissions flags such as PrintDocument, ModifyContent, and ExtractContent control what a viewer without the owner password may do. IsEncrypted() checks the current state, and Decrypt() removes protection from an already-open document.

#include <aspose/pdf/document.hpp>

int main() {
    Aspose::Pdf::Document doc("input.pdf");

    doc.Encrypt("user-password", "owner-password",
                Aspose::Pdf::Permissions::PrintDocument,
                Aspose::Pdf::CryptoAlgorithm::AESx256);
    doc.Save("encrypted.pdf");

    Aspose::Pdf::Document secured("encrypted.pdf");
    std::cout << std::boolalpha << secured.IsEncrypted() << "\n";
}

Text Extraction and Layout

Aspose::Pdf::Text::TextAbsorber walks a document or page and accumulates plain text, retrieved with Text(). TextFragmentAbsorber returns positioned TextFragment objects instead, each exposing Rectangle() and TextState(). For adding text, TextBuilder::AppendParagraph() writes a TextParagraph onto a page, and paragraph objects are grouped in a page’s Paragraphs() collection.

#include <aspose/pdf/document.hpp>
#include <aspose/pdf/text_absorber.hpp>
#include <iostream>

int main() {
    Aspose::Pdf::Document doc("report.pdf");

    Aspose::Pdf::Text::TextAbsorber absorber;
    absorber.Visit(doc);
    std::cout << absorber.Text() << "\n";

    Aspose::Pdf::Text::TextFragmentAbsorber fragmentAbsorber;
    fragmentAbsorber.Visit(doc.Pages()[1]);
    std::cout << "Fragments on page 1: "
              << fragmentAbsorber.TextFragments().Count() << "\n";
}

Tables

Row and Rows build tabular layouts placed onto a page through the Paragraphs() collection. Each Row owns a Cells collection; Cell supports text, a background image (BackgroundImage() / BackgroundImageFile()), and per-cell borders via BorderInfo. BorderInfo combines a GraphInfo per side, and BorderSide selects which sides a border style applies to.

#include <aspose/pdf/document.hpp>
#include <aspose/pdf/border_info.hpp>

int main() {
    Aspose::Pdf::Document doc("input.pdf");

    Aspose::Pdf::Table table;
    table.Left(72.0f);
    table.Top(700.0f);
    table.ColumnWidths("120 120");
    table.DefaultCellBorder(
        Aspose::Pdf::BorderInfo(Aspose::Pdf::BorderSide::All, 1.0f));

    auto& rows = table.Rows();
    auto& row = rows.Add();
    row.Cells().Add("Item");
    row.Cells().Add("Qty");

    doc.Pages()[1].Paragraphs().Add(table);
    doc.Save("output.pdf");
}

Bookmarks and Navigation

Document::Outlines() returns the top-level Outlines collection (bookmark tree). Each entry is an OutlineItemCollection, which itself holds child entries and exposes Title(), Bold(), Italic(), and Destination() (an IAppointment, such as a page-fit target). NamedDestinationCollection provides reusable, named page targets.

#include <aspose/pdf/document.hpp>
#include <aspose/pdf/outline_item_collection.hpp>

int main() {
    Aspose::Pdf::Document doc("input.pdf");

    auto item = std::make_shared<Aspose::Pdf::OutlineItemCollection>(doc.Outlines());
    item->Title("Chapter 1");
    item->Bold(true);
    doc.Outlines().Add(item);

    doc.Save("output.pdf");
}

Images and Resources

Each Page exposes a Resources() object, and Resources::Images() returns the page’s XImageCollection. XImage exposes Width(), Height(), and GetRawImageData() for an embedded raster image. XImageCollection::Add() embeds a new image and returns its resource name.

#include <aspose/pdf/document.hpp>
#include <iostream>

int main() {
    Aspose::Pdf::Document doc("input.pdf");

    auto& images = doc.Pages()[1].Resources().Images();
    std::cout << "Images on page 1: " << images.Count() << "\n";

    for (const auto& name : images.Names()) {
        std::cout << " - " << name << "\n";
    }
}

Fonts

Aspose::Pdf::Text::Font describes a font used in text content: FontName(), BaseFont(), IsEmbedded(), and IsSubset(). FontRepository::FindFont(fontName) resolves a font by name, and FontRepository::OpenFont(fontFilePath) loads one directly from a file.

#include <aspose/pdf/font_repository.hpp>
#include <iostream>

int main() {
    auto font = Aspose::Pdf::Text::FontRepository::FindFont("Helvetica");
    std::cout << "Font: " << font.FontName()
              << " embedded=" << std::boolalpha << font.IsEmbedded() << "\n";
}

Embedded Files

Document::EmbeddedFiles() returns an EmbeddedFileCollection of FileSpecification attachments. Add() embeds a new file, FindByName() looks one up, and Delete() removes attachments individually or all at once. Each FileSpecification carries a Name(), Description(), and an AFRelationship classifying the attachment’s purpose.

#include <aspose/pdf/document.hpp>
#include <iostream>

int main() {
    Aspose::Pdf::Document doc("input.pdf");

    std::cout << "Attachments: " << doc.EmbeddedFiles().Count() << "\n";

    doc.EmbeddedFiles().Delete();   // remove all attachments
    doc.Save("output.pdf");
}

Tips and Best Practices

  • Remember that PageCollection is 1-indexed: doc.Pages()[1] is the first page, not doc.Pages()[0].
  • Call Optimize() before Save() on documents that have gone through multiple rounds of page insertion or deletion — it clears resources that are no longer referenced.
  • Reuse a single rendering device instance (BmpDevice, PngDevice, and so on) across multiple pages instead of constructing a new one per page; only the Resolution needs to be fixed up front.
  • Always supply both a user password and an owner password to Encrypt() — an empty user password permits open access regardless of the algorithm chosen.
  • Read DocumentInfo fields before overwriting them if you only intend to update one property (for example, Title) — setters replace the field value outright.

Common Issues

IssueCauseFix
IndexOutOfRange-style failure when accessing a pageCode assumed 0-based indexingPageCollection is 1-indexed; use Pages()[1] for the first page
Rendered raster image is unexpectedly small or blankResolution too low, or the wrong page passed to Process()Increase the Resolution DPI value and confirm the page index
Save() after Encrypt() still opens without a password in some viewersSome viewers cache an unencrypted copy from an earlier openSave to a new file path and re-open it to confirm encryption
DocumentInfo fields appear empty after opening a generated PDFThe producing tool never wrote /Info entriesCheck Producer() and Creator() for blank strings before assuming a bug
Table added via Paragraphs().Add(table) disappears after Save()The Table object went out of scope before Save() ranKeep the Table alive until after Save() returns

FAQ

Is page indexing zero-based or one-based?

One-based. doc.Pages()[1] is the first page in the document.

Which document properties does DocumentInfo expose?

Title, Author, Creator, Subject, Keywords, Producer, and Trapped, plus generic key/value access via Add() and Remove().

Can I render a range of pages to a single TIFF?

Yes. TiffDevice::Process(document, fromPage, toPage, output) renders a page range into one multi-page TIFF output stream.

How do I remove password protection from a document?

Open it with Document, then call Decrypt() and Save() to a new path.

Can I add a custom XMP metadata field?

Yes, through Document::Metadata(), which supports Add(key, value) for namespaced key/value pairs beyond the standard /Info dictionary.


API Reference Summary

Class/MethodDescription
DocumentRoot object — open, create, save, optimize
Document.Pages()Returns the PageCollection
Document.Info()Returns DocumentInfo (standard metadata)
Document.Metadata()Returns the XMP Metadata dictionary
Document.Outlines()Returns the bookmark tree (Outlines)
Document.EmbeddedFiles()Returns attached-file collection
Document.Encrypt() / Decrypt()Apply or remove password protection
PageCollection1-indexed page container — Add, Insert, Delete
DocumentInfoStandard /Info dictionary fields
MetadataXMP metadata dictionary
CryptoAlgorithmRC4/AES cipher selection for Encrypt()
PermissionsAccess-control flags for Encrypt()
BmpDevice / PngDevice / JpegDevice / TiffDeviceRender a page to a raster format
ResolutionDPI setting for rendering devices
RenderingOptionsFont and interpolation controls for rendering
TextAbsorberExtracts plain text
TextFragmentAbsorber / TextFragmentExtracts positioned text fragments
TextBuilder / TextParagraphWrites text content onto a page
Outlines / OutlineItemCollectionBookmark tree and individual entries
NamedDestinationCollectionReusable named page targets
Row / Rows / Cell / CellsTable layout building blocks
BorderInfo / GraphInfoBorder and line styling for table cells
Resources / XImage / XImageCollectionPage resource and embedded-image access
Font / FontRepositoryFont metadata and lookup
EmbeddedFileCollection / FileSpecificationFile attachment management

See Also

 English