How to Work with Content Stream Operators in Java
This guide shows how to parse and build page content streams in Aspose.PDF FOSS
for Java. You will learn to read raw page bytes, parse them with ContentStreamParser,
and use ContentStreamBuilder to create new content.
Access the Content Stream
Each Page in a Document holds its graphical content in a content stream. The stream
contains a sequence of PDF operators that define text positioning, drawing commands, and
resource references. Read the raw content stream bytes from a page:
try (Document doc = new Document("input.pdf")) {
PageCollection pages = doc.getPages();
Page page = pages.get(1);
byte[] contentBytes = page.getContents().toByteArray();
System.out.println("Content stream size: " + contentBytes.length + " bytes");
}Parse with ContentStreamParser
ContentStreamParser tokenizes and parses a content stream into operator objects,
making it possible to inspect each drawing command in the stream:
try (Document doc = new Document("input.pdf")) {
PageCollection pages = doc.getPages();
Page page = pages.get(1);
byte[] contentBytes = page.getContents().toByteArray();
ContentStreamParser parser = new ContentStreamParser(contentBytes);
// Iterate over parsed operators
}Build with ContentStreamBuilder
ContentStreamBuilder creates new content streams for embedding in a Page.
Use ContentStreamBuilder when constructing page content programmatically rather
than modifying an existing stream. After building the stream, assign it back to the
page and save the document.
Operator Reference
PDF content stream operators are defined in ISO 32000-1:2008, Table A.1. Common operators include:
- Text operators:
BT,ET,Tf,Tj - Graphics state operators:
q,Q,cm - Path operators:
m,l,h,f,S