Skip to main content

PdfDocument Class

A PDF document.

Declaration

public class PdfDocument extends JavaObject implements IDisposable

Remarks

Use the PdfDocument class to create or load a document, manage its pages and content, and save the result as a PDF file.

Refer to the following help topic for additional information: Create PDF Documents.

Implements

com.devexpress.system.IDisposable

Inherited Members

com.devexpress.system.JavaObject.clone()
com.devexpress.system.JavaObject.equals(java.lang.Object)
com.devexpress.system.JavaObject.hashCode()
com.devexpress.system.JavaObject.initFields()
com.devexpress.system.JavaObject.memberwiseClone()
com.devexpress.system.JavaObject.toString()
java.lang.Object.finalize()
java.lang.Object.getClass()
java.lang.Object.notify()
java.lang.Object.notifyAll()
java.lang.Object.wait()
java.lang.Object.wait(long)
java.lang.Object.wait(long,int)

Inheritance

Object
com.devexpress.system.JavaObject
PdfDocument

Constructors

PdfDocument() Constructor

Initializes a new instance of the PdfDocument class.

Declaration

public PdfDocument()

PdfDocument(FileVersion version) Constructor

Initializes a new instance of the PdfDocument class with the specified PDF version.

Declaration

public PdfDocument(FileVersion version)

Parameters

Name Type Description
version FileVersion

The PDF version for the new document.

PdfDocument(InputStream stream, LoadOptions loadOptions) Constructor

Initializes a new instance of the PdfDocument class with specified settings.

Declaration

public PdfDocument(InputStream stream, LoadOptions loadOptions)

Parameters

Name Type Description
stream InputStream

The stream that contains the PDF content.

loadOptions LoadOptions

Options used to load the document.

PdfDocument(InputStream stream, String password, boolean detachStreamAfterLoadComplete) Constructor

Initializes a new instance of the PdfDocument class with specified settings.

Declaration

public PdfDocument(InputStream stream, String password, boolean detachStreamAfterLoadComplete)

Parameters

Name Type Description
stream InputStream

The stream that contains the PDF content.

password String

The password.

detachStreamAfterLoadComplete boolean

true to detach the source stream after the document is loaded; otherwise, false.

PdfDocument(InputStream stream, String password) Constructor

Initializes a new instance of the PdfDocument class with specified settings.

Declaration

public PdfDocument(InputStream stream, String password)

Parameters

Name Type Description
stream InputStream

The stream that contains the PDF content.

password String

The password.

PdfDocument(InputStream stream) Constructor

Initializes a new instance of the PdfDocument class with specified settings.

Declaration

public PdfDocument(InputStream stream)

Parameters

Name Type Description
stream InputStream

The stream that contains the PDF content.

PdfDocument(ReadableByteChannel channel, LoadOptions loadOptions) Constructor

Initializes a new instance of the PdfDocument class with specified settings.

Declaration

public PdfDocument(ReadableByteChannel channel, LoadOptions loadOptions)

Parameters

Name Type Description
channel ReadableByteChannel

The channel that contains the PDF content.

loadOptions LoadOptions

Options used to load the document.

PdfDocument(ReadableByteChannel channel, String password, boolean detachStreamAfterLoadComplete) Constructor

Initializes a new instance of the PdfDocument class with specified settings.

Declaration

public PdfDocument(ReadableByteChannel channel, String password, boolean detachStreamAfterLoadComplete)

Parameters

Name Type Description
channel ReadableByteChannel

The channel that contains the PDF content.

password String

The password.

detachStreamAfterLoadComplete boolean

true to detach the source stream after the document is loaded; otherwise, false.

PdfDocument(ReadableByteChannel channel, String password) Constructor

Initializes a new instance of the PdfDocument class with specified settings.

Declaration

public PdfDocument(ReadableByteChannel channel, String password)

Parameters

Name Type Description
channel ReadableByteChannel

The channel that contains the PDF content.

password String

The password.

PdfDocument(ReadableByteChannel channel) Constructor

Initializes a new instance of the PdfDocument class with specified settings.

Declaration

public PdfDocument(ReadableByteChannel channel)

Parameters

Name Type Description
channel ReadableByteChannel

The channel that contains the PDF content.

Methods

appendDocument(InputStream stream, LoadOptions loadOptions) Method

Appends a PDF document from a stream using the specified load options.

Declaration

public AppendDocumentResult appendDocument(InputStream stream, LoadOptions loadOptions)

Parameters

Name Type Description
stream InputStream

The stream that contains the PDF content to append.

loadOptions LoadOptions

Options that control how the appended document is loaded.

Returns

Type Description
AppendDocumentResult

The result of a document append operation, including information about resolved form field name conflicts.

Remarks

The following code snippet appends a PDF document from a stream using load options:

// Configure load options for the appended document.
LoadOptions options = new LoadOptions();
options.setDetachStreamAfterLoadComplete(true);
options.setMetadataSyncMode(MetadataSyncMode.AUTO);
options.setSyncMetadata(true);

// Append a PDF document with custom load options.
try (InputStream stream = Files.newInputStream(Path.of("Source.pdf"))) {
    pdfDocument.appendDocument(stream, options);
}

Refer to the following help topic: Append a Document from a Stream with Load Options.

appendDocument(InputStream stream) Method

Appends a PDF document from a stream.

Declaration

public AppendDocumentResult appendDocument(InputStream stream)

Parameters

Name Type Description
stream InputStream

The stream that contains the PDF content to append.

Returns

Type Description
AppendDocumentResult

The result of a document append operation, including information about resolved form field name conflicts.

appendDocument(PdfDocument document) Method

Appends the specified PDF document.

Declaration

public AppendDocumentResult appendDocument(PdfDocument document)

Parameters

Name Type Description
document PdfDocument

The document to append.

Returns

Type Description
AppendDocumentResult

The result of a document append operation, including information about resolved form field name conflicts.

Remarks

The following code snippet appends an existing PDF document:

// Open a document to append.
try (PdfDocument source = new PdfDocument(
        FileChannel.open(Path.of("Source.pdf")))) {

    // Append the document to the current document.
    pdfDocument.appendDocument(source);
}

Refer to the following help topic: Append an Existing PDF Document.

appendDocument(ReadableByteChannel channel, LoadOptions loadOptions) Method

Appends a PDF document from a channel using the specified load options.

Declaration

public AppendDocumentResult appendDocument(ReadableByteChannel channel, LoadOptions loadOptions)

Parameters

Name Type Description
channel ReadableByteChannel

The channel that contains the PDF content to append.

loadOptions LoadOptions

Options used to load the appended document.

Returns

Type Description
AppendDocumentResult

The result of a document append operation, including information about resolved form field name conflicts.

Remarks

The following code snippet appends a PDF document from a channel using load options:

// Configure load options for the appended document.
LoadOptions options = new LoadOptions();
options.setMetadataSyncMode(MetadataSyncMode.AUTO);
options.setSyncMetadata(true);
options.setPassword("USER_PASSWORD");

// Append a PDF document from a channel with custom load options.
try (ReadableByteChannel channel =
         FileChannel.open(Path.of("Source.pdf"))) {

    pdfDocument.appendDocument(channel, options);
}

Refer to the following help topic: Append a Document from a Channel with Load Options.

appendDocument(ReadableByteChannel channel) Method

Appends a PDF document from a channel.

Declaration

public AppendDocumentResult appendDocument(ReadableByteChannel channel)

Parameters

Name Type Description
channel ReadableByteChannel

The channel that contains the PDF content to append.

Returns

Type Description
AppendDocumentResult

The result of a document append operation, including information about resolved form field name conflicts.

applyRedaction(int pageIndex, RedactionAnnotation[] annotations) Method

Applies redaction annotations to the specified page.

Declaration

public void applyRedaction(int pageIndex, RedactionAnnotation[] annotations)

Parameters

Name Type Description
pageIndex int

The zero-based index of the page to redact.

annotations RedactionAnnotation[]

Redaction annotations to apply.

Remarks

Refer to the following help topic for additional information: Redaction Annotations.

attachZugferdInvoice(byte[] invoiceData, ZugferdVersion version, ZugferdConformanceLevel conformanceLevel) Method

Embeds a ZUGFerD invoice in the document from a byte array using the specified version and conformance level.

Declaration

public void attachZugferdInvoice(byte[] invoiceData, ZugferdVersion version, ZugferdConformanceLevel conformanceLevel)

Parameters

Name Type Description
invoiceData byte[]

The ZUGFeRD invoice data.

version ZugferdVersion

The ZUGFeRD version to use.

conformanceLevel ZugferdConformanceLevel

The ZUGFeRD conformance level to apply.

Remarks

Refer to the following help topic for additional information: Generate ZUGFeRD-Compliant PDF Invoices.

attachZugferdInvoice(byte[] invoiceData) Method

Embeds a ZUGFeRD invoice in the document from a byte array.

Declaration

public void attachZugferdInvoice(byte[] invoiceData)

Parameters

Name Type Description
invoiceData byte[]

The ZUGFeRD invoice data.

Remarks

Refer to the following help topic for additional information: Generate ZUGFeRD-Compliant PDF Invoices.

attachZugferdInvoice(InputStream invoiceStream, ZugferdVersion version, ZugferdConformanceLevel conformanceLevel) Method

Embeds a ZUGFerD invoice in the document from a stream using the specified version and conformance level.

Declaration

public void attachZugferdInvoice(InputStream invoiceStream, ZugferdVersion version, ZugferdConformanceLevel conformanceLevel)

Parameters

Name Type Description
invoiceStream InputStream

The stream that contains the ZUGFeRD invoice data.

version ZugferdVersion

The ZUGFeRD version to use.

conformanceLevel ZugferdConformanceLevel

The ZUGFeRD conformance level to apply.

Remarks

Refer to the following help topic for additional information: Generate ZUGFeRD-Compliant PDF Invoices.

attachZugferdInvoice(InputStream invoiceStream) Method

Embeds a ZUGFeRD invoice in the document from a stream.

Declaration

public void attachZugferdInvoice(InputStream invoiceStream)

Parameters

Name Type Description
invoiceStream InputStream

The stream that contains the ZUGFeRD invoice data.

Remarks

Refer to the following help topic for additional information: Generate ZUGFeRD-Compliant PDF Invoices.

attachZugferdInvoice(ReadableByteChannel invoiceStream, ZugferdVersion version, ZugferdConformanceLevel conformanceLevel) Method

Embeds a ZUGFeRD invoice in the document from a channel using the specified version and conformance level.

Declaration

public void attachZugferdInvoice(ReadableByteChannel invoiceStream, ZugferdVersion version, ZugferdConformanceLevel conformanceLevel)

Parameters

Name Type Description
invoiceStream ReadableByteChannel

The channel that contains the ZUGFeRD invoice data.

version ZugferdVersion

The ZUGFeRD version to use.

conformanceLevel ZugferdConformanceLevel

The ZUGFeRD conformance level to apply.

Remarks

Refer to the following help topic for additional information: Generate ZUGFeRD-Compliant PDF Invoices.

attachZugferdInvoice(ReadableByteChannel invoiceStream) Method

Embeds a ZUGFeRD invoice in the document from a channel.

Declaration

public void attachZugferdInvoice(ReadableByteChannel invoiceStream)

Parameters

Name Type Description
invoiceStream ReadableByteChannel

The channel that contains the ZUGFeRD invoice data.

Remarks

Refer to the following help topic for additional information: Generate ZUGFeRD-Compliant PDF Invoices.

clearContent(int pageIndex, List<OrientedRectangle> regions, boolean clearText, boolean clearImages, boolean clearGraphics, boolean clearAnnotations) Method

Clears text, images, graphics, and annotations from the specified page regions.

Declaration

public void clearContent(int pageIndex, List<OrientedRectangle> regions, boolean clearText, boolean clearImages, boolean clearGraphics, boolean clearAnnotations)

Parameters

Name Type Description
pageIndex int

The zero-based index of the page to modify.

regions java.util.List<OrientedRectangle>

Page regions to clear.

clearText boolean

true to clear text content; otherwise, false.

clearImages boolean

true to clear images; otherwise, false.

clearGraphics boolean

true to clear graphics content; otherwise, false.

clearAnnotations boolean

true to clear annotations; otherwise, false.

clearContent(int pageIndex, List<OrientedRectangle> regions, boolean clearText, boolean clearImages, boolean clearGraphics) Method

Clears text, images, and graphics from the specified page regions.

Declaration

public void clearContent(int pageIndex, List<OrientedRectangle> regions, boolean clearText, boolean clearImages, boolean clearGraphics)

Parameters

Name Type Description
pageIndex int

The zero-based index of the page to modify.

regions java.util.List<OrientedRectangle>

The page regions to clear.

clearText boolean

true to clear text content; otherwise, false.

clearImages boolean

true to clear images; otherwise, false.

clearGraphics boolean

true to clear graphics content; otherwise, false.

clearContent(int pageIndex, List<OrientedRectangle> regions, boolean clearText, boolean clearImages) Method

Clears text and images from the specified page regions.

Declaration

public void clearContent(int pageIndex, List<OrientedRectangle> regions, boolean clearText, boolean clearImages)

Parameters

Name Type Description
pageIndex int

The zero-based index of the page to modify.

regions java.util.List<OrientedRectangle>

Page regions to clear.

clearText boolean

true to clear text content; otherwise, false.

clearImages boolean

true to clear images; otherwise, false.

clearContent(int pageIndex, List<OrientedRectangle> regions, boolean clearText) Method

Clears text from the specified page regions.

Declaration

public void clearContent(int pageIndex, List<OrientedRectangle> regions, boolean clearText)

Parameters

Name Type Description
pageIndex int

The zero-based index of the page to modify.

regions java.util.List<OrientedRectangle>

Page regions to clear.

clearText boolean

true to clear text content; otherwise, false.

clearContent(int pageIndex, List<OrientedRectangle> regions) Method

Clears all content types from the specified page regions.

Declaration

public void clearContent(int pageIndex, List<OrientedRectangle> regions)

Parameters

Name Type Description
pageIndex int

The zero-based index of the page to modify.

regions java.util.List<OrientedRectangle>

Page regions to clear.

close() Method

Closes the document and releases associated resources.

Declaration

public void close()

compressImages(ImageCompressionOptions options) Method

Compresses images in a PDF document.

Declaration

public boolean compressImages(ImageCompressionOptions options)

Parameters

Name Type Description
options ImageCompressionOptions

Image compression options.

Returns

Type Description
boolean

true if embedded images were optimized; otherwise, false.

Remarks

The PdfDocument.compressImages() method optimizes images in a PDF document. Create an ImageCompressionOptions object and configure image compression settings.

The following code snippet optimizes images with different compression settings:

package pdf;

import com.devexpress.docs.pdf.*;

import java.nio.channels.*;
import java.nio.file.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (FileChannel channel = FileChannel.open(Path.of("Document.pdf"));
             PdfDocument pdfDocument = new PdfDocument(channel)) {

            // Configure image compression options.
            ImageCompressionOptions imageCompressionOptions = new ImageCompressionOptions();

            // Configure general compression settings.
            imageCompressionOptions.setCompressionType(ImageCompressionType.JPEG);
            imageCompressionOptions.setJpegQuality(75);
            imageCompressionOptions.setDownsamplingResolution(150);

            // Convert color images to grayscale.
            imageCompressionOptions.setConvertGrayscale(true);

            // Configure compression for grayscale images.
            imageCompressionOptions.setGrayscaleCompressionType(GrayscaleImageCompressionType.JPEG);

            // Configure compression for bitonal images.
            imageCompressionOptions.setBitonalCompressionType(BitonalImageCompressionType.CCITT_GROUP_4);

            // Compress images.
            pdfDocument.compressImages(imageCompressionOptions);

            try (WritableByteChannel writableByteChannel =
                    FileChannel.open(Path.of("Document_Optimized.pdf"),
                        StandardOpenOption.CREATE,
                        StandardOpenOption.WRITE,
                        StandardOpenOption.TRUNCATE_EXISTING)) {

                pdfDocument.save(writableByteChannel);
            }
        }
    }
}

Refer to the following help topic for additional information: Compress Images.

encrypt(EncryptionOptions options) Method

Encrypts the document with the specified options.

Declaration

public void encrypt(EncryptionOptions options)

Parameters

Name Type Description
options EncryptionOptions

Encryption settings.

Remarks

The following code snippet loads a PDF document, encrypts it, restricts specific operations, and saves the result:

import com.devexpress.docs.pdf.*;

import java.nio.file.*;
import java.nio.channels.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (FileChannel channel = FileChannel.open(Path.of("Document.pdf"));
             PdfDocument pdfDocument = new PdfDocument(channel)) {

            EncryptionOptions encryptionOptions = new EncryptionOptions(
                    "ownerPassword", 
                    "userPassword"
            ) {{

                    setDataExtractionPermissions(DocumentDataExtractionPermissions.NOT_ALLOWED);
                    setPrintPermissions(DocumentPrintPermissions.LOW_QUALITY);
                    setModificationPermissions(DocumentModificationPermissions.NOT_ALLOWED);
                    setAlgorithm(EncryptionAlgorithm.AES_256);
                }};

            pdfDocument.encrypt(encryptionOptions);

            // Save the encrypted document.
            try (WritableByteChannel writableByteChannel =
                 FileChannel.open(Path.of("Document_encrypted.pdf"),
                     StandardOpenOption.CREATE,
                     StandardOpenOption.WRITE,
                     StandardOpenOption.TRUNCATE_EXISTING)) {

                pdfDocument.save(writableByteChannel);
            }
        }
    }
}

Refer to the following help topic for additional information: Encrypt PDF Documents.

exportFormData(OutputStream stream, ExportDataFormat format) Method

Exports form data from the document.

Declaration

public void exportFormData(OutputStream stream, ExportDataFormat format)

Parameters

Name Type Description
stream OutputStream

The stream that receives the exported form data.

format ExportDataFormat

The format of the exported form data.

Remarks

Refer to the following help topic for additional information: Work with PDF Forms (AcroForms).

exportFormData(WritableByteChannel channel, ExportDataFormat format) Method

Exports form data from the document.

Declaration

public void exportFormData(WritableByteChannel channel, ExportDataFormat format)

Parameters

Name Type Description
channel WritableByteChannel

The channel that receives the exported form data.

format ExportDataFormat

The format of the exported form data.

Remarks

Refer to the following help topic for additional information: Work with PDF Forms (AcroForms).

exportToImages(ImageExportOptions options, int[] pageIndexes) Method

Exports document pages to images.

Declaration

public DXImage[] exportToImages(ImageExportOptions options, int[] pageIndexes)

Parameters

Name Type Description
options ImageExportOptions

Settings that control image export.

pageIndexes int[]

Zero-based indexes of the pages to export.

Returns

Type Description
DXImage[]

Images generated from the specified pages.

Remarks

Note

The exportToImages method returns an array of DXImage objects. Dispose of each image after use to release resources.

The following code snippet exports the first two pages to SVG images using custom image export options:

import com.devexpress.drawing.*;
import com.devexpress.docs.pdf.*;

import java.nio.channels.*;
import java.nio.file.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (PdfDocument pdfDocument =
                 new PdfDocument(FileChannel.open(Path.of("document.pdf")))) {

            // Configure image export settings.
            ImageExportOptions options = new ImageExportOptions();
            options.setImageExportType(ImageExportType.SVG);
            options.setLargestEdgeLength(1000);

            // Export pages 1 and 2 to images.
            DXImage[] images = pdfDocument.exportToImages(
                    options,
                    new int[] { 0, 1 });

            try {
                // Save each exported page as an SVG file.
                for (int i = 0; i < images.length; i++) {
                    images[i].save("page-" + (i + 1) + ".svg");
                }
            } finally {
                // Release image resources.
                for (DXImage image : images) {
                    image.close();
                }
            }
        }
    }
}

Refer to the following help topic for additional information: Export PDF Pages to Images.

exportToImages(int[] pageIndexes) Method

Exports document pages to images.

Declaration

public DXImage[] exportToImages(int[] pageIndexes)

Parameters

Name Type Description
pageIndexes int[]

Zero-based indexes of the pages to export.

Returns

Type Description
DXImage[]

Images generated from the specified pages.

Remarks

Note

The exportToImages method returns an array of DXImage objects. Dispose of each image after use to release resources.

The following code snippet exports all pages of a PDF document to DXImage objects and saves each page as a separate PNG image:

import com.devexpress.drawing.*;
import com.devexpress.docs.pdf.*;

import java.nio.channels.*;
import java.nio.file.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (PdfDocument pdfDocument =
                 new PdfDocument(FileChannel.open(Path.of("document.pdf")))) {

            // Export all pages to images.
            int pageCount = pdfDocument.getPages().size();
            int[] pageIndexes = new int[pageCount];
            for (int i = 0; i < pageCount; i++) {
                pageIndexes[i] = i;
            }

            DXImage[] images = pdfDocument.exportToImages(pageIndexes);

            try {
                // Save each page as a PNG image.
                for (int i = 0; i < images.length; i++) {
                    images[i].save(
                        "page-" + (i + 1) + ".png",
                        DXImageFormat.getPng());
                }
            } finally {
                // Release image resources.
                for (DXImage image : images) {
                    image.close();
                }
            }
        }
    }
}

Refer to the following help topic for additional information: Export PDF Pages to Images.

findText(String text, int startPageIndex, int endPageIndex) Method

Searches the specified page range for the specified text.

Declaration

public Iterable<TextSearchInfo> findText(String text, int startPageIndex, int endPageIndex)

Parameters

Name Type Description
text String

The search text.

startPageIndex int

The zero-based index of the page at which to start the search.

endPageIndex int

The zero-based index of the page at which to end the search.

Returns

Type Description
java.lang.Iterable<TextSearchInfo>

Search results that match the specified text.

Remarks

Refer to the following help topic for additional information: Search and Process Text in PDF Documents.

findText(String text, int startPageIndex) Method

Searches the document for the specified text starting from the specified page.

Declaration

public Iterable<TextSearchInfo> findText(String text, int startPageIndex)

Parameters

Name Type Description
text String

The search text.

startPageIndex int

The zero-based index of the page where the search starts.

Returns

Type Description
java.lang.Iterable<TextSearchInfo>

Search results that match the specified text.

Remarks

Refer to the following help topic for additional information: Search and Process Text in PDF Documents.

findText(String text, TextSearchOptions options, int startPageIndex, int endPageIndex) Method

Searches the specified page range for text with the specified options.

Declaration

public Iterable<TextSearchInfo> findText(String text, TextSearchOptions options, int startPageIndex, int endPageIndex)

Parameters

Name Type Description
text String

The search text.

options TextSearchOptions

Options that control the text search.

startPageIndex int

The zero-based index of the page at which to start the search.

endPageIndex int

The zero-based index of the page at which to end the search.

Returns

Type Description
java.lang.Iterable<TextSearchInfo>

Search results that match the specified text.

Remarks

The following code snippet searches for the word “keyword“ in a PDF document:

import java.nio.channels.*;
import java.nio.file.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (PdfDocument pdfDocument = new PdfDocument(FileChannel.open(
                Path.of("document.pdf")))) {

            TextSearchOptions options = new TextSearchOptions(
                true,   // Match case.
                true    // Match whole words.
            );

            // Search all pages in the document.
            int pageCount = pdfDocument.getPages().size();
            Iterable<TextSearchInfo> results = pdfDocument.findText(
                    "keyword",
                    options,
                    0,
                    pageCount - 1);

            // Process search results.
            for (TextSearchInfo result : results) {

            }

            // Save the document.
        }
    }
}

Refer to the following help topic for additional information: Search and Process Text in PDF Documents.

findText(String text, TextSearchOptions options, int startPageIndex) Method

Searches the document for the specified text starting from the specified page with the specified options.

Declaration

public Iterable<TextSearchInfo> findText(String text, TextSearchOptions options, int startPageIndex)

Parameters

Name Type Description
text String

The text to search for.

options TextSearchOptions

Options that control the text search.

startPageIndex int

The zero-based index of the page where the search starts.

Returns

Type Description
java.lang.Iterable<TextSearchInfo>

Search results that match the specified text.

Remarks

The findText method returns a collection of TextSearchInfo objects. Each object contains search results for a single page.

findText(String text, TextSearchOptions options) Method

Searches the document for the specified text with the specified options.

Declaration

public Iterable<TextSearchInfo> findText(String text, TextSearchOptions options)

Parameters

Name Type Description
text String

The search text.

options TextSearchOptions

Options that control the text search.

Returns

Type Description
java.lang.Iterable<TextSearchInfo>

Search results that match the specified text.

Remarks

Refer to the following help topic for additional information: Search and Process Text in PDF Documents.

findText(String text) Method

Searches the document for the specified text.

Declaration

public Iterable<TextSearchInfo> findText(String text)

Parameters

Name Type Description
text String

The search text.

Returns

Type Description
java.lang.Iterable<TextSearchInfo>

Search results that match the specified text.

Remarks

Refer to the following help topic for additional information: Search and Process Text in PDF Documents.

flatten() Method

Flattens all annotations and form fields in the PDF document.

Declaration

public void flatten()

Remarks

The flatten() method converts all annotations and form fields into static page content. After flattening, users cannot modify annotations or form fields in a PDF viewer.

The flatten() method doest the following:

  • Flattens all annotations in the document.
  • Flattens all form fields in the document.

To flatten only specific annotations or form fields, use flattenAnnotations() or flattenFormFields() method overloads.

Refer to the following help topic for additional information and examples: Flatten PDF Annotations and Form Fields.

flattenAnnotations() Method

Flattens all annotations in the PDF document.

Declaration

public void flattenAnnotations()

Remarks

Refer to the following help topic for additional information and examples: Flatten PDF Annotations and Form Fields.

flattenAnnotations(BaseAnnotation[] annotations) Method

Flattens the specified annotations.

Declaration

public void flattenAnnotations(BaseAnnotation[] annotations)

Parameters

Name Type Description
annotations BaseAnnotation[]

Annotations to flatten.

Remarks

Refer to the following help topic for additional information and examples: Flatten PDF Annotations and Form Fields.

flattenAnnotations(Function<BaseAnnotation,Boolean> predicate) Method

Flattens annotations that match the specified condition.

Declaration

public void flattenAnnotations(Function<BaseAnnotation,Boolean> predicate)

Parameters

Name Type Description
predicate java.util.function.Function<BaseAnnotation,java.lang.Boolean>

A function that specifies whether to flatten an annotation.

Remarks

Refer to the following help topic for additional information and examples: Flatten PDF Annotations and Form Fields.

flattenAnnotations(int pageIndex, BaseAnnotation[] annotations) Method

Flattens the specified annotations on the specified page.

Declaration

public void flattenAnnotations(int pageIndex, BaseAnnotation[] annotations)

Parameters

Name Type Description
pageIndex int

The zero-based page index.

annotations BaseAnnotation[]

Annotations to flatten.

Remarks

Refer to the following help topic for additional information and examples: Flatten PDF Annotations and Form Fields.

flattenAnnotations(int pageIndex, Function<BaseAnnotation,Boolean> predicate) Method

Flattens annotations on the specified page that match the specified condition.

Declaration

public void flattenAnnotations(int pageIndex, Function<BaseAnnotation,Boolean> predicate)

Parameters

Name Type Description
pageIndex int

The zero-based page index.

predicate java.util.function.Function<BaseAnnotation,java.lang.Boolean>

A function that specifies whether to flatten an annotation.

Remarks

Refer to the following help topic for additional information and examples: Flatten PDF Annotations and Form Fields.

flattenAnnotations(int pageIndex) Method

Flattens all annotations on the specified page.

Declaration

public void flattenAnnotations(int pageIndex)

Parameters

Name Type Description
pageIndex int

The zero-based page index.

Remarks

Refer to the following help topic for additional information and examples: Flatten PDF Annotations and Form Fields.

flattenFormFields() Method

Flattens all form fields in the PDF document.

Declaration

public void flattenFormFields()

Remarks

Refer to the following help topic for additional information and examples: Flatten PDF Annotations and Form Fields.

flattenFormFields(Function<FormField,Boolean> predicate) Method

Flattens form fields that match the specified condition.

Declaration

public void flattenFormFields(Function<FormField,Boolean> predicate)

Parameters

Name Type Description
predicate java.util.function.Function<FormField,java.lang.Boolean>

A function that specifies whether to flatten a form field.

Remarks

Refer to the following help topic for additional information and examples: Flatten PDF Annotations and Form Fields.

flattenFormFields(int pageIndex, Function<FormField,Boolean> predicate) Method

Flattens form fields on the specified page that match the specified condition.

Declaration

public void flattenFormFields(int pageIndex, Function<FormField,Boolean> predicate)

Parameters

Name Type Description
pageIndex int

The zero-based page index.

predicate java.util.function.Function<FormField,java.lang.Boolean>

A function that specifies whether to flatten a form field.

Remarks

Refer to the following help topic for additional information and examples: Flatten PDF Annotations and Form Fields.

flattenFormFields(int pageIndex, String[] fieldNames) Method

Flattens the specified form fields on the specified page.

Declaration

public void flattenFormFields(int pageIndex, String[] fieldNames)

Parameters

Name Type Description
pageIndex int

The zero-based page index.

fieldNames java.lang.String[]

The names of form fields to flatten.

Remarks

Refer to the following help topic for additional information and examples: Flatten PDF Annotations and Form Fields.

flattenFormFields(int pageIndex) Method

Flattens all form fields on the specified page.

Declaration

public void flattenFormFields(int pageIndex)

Parameters

Name Type Description
pageIndex int

The zero-based page index.

Remarks

Refer to the following help topic for additional information and examples: Flatten PDF Annotations and Form Fields.

flattenFormFields(String[] fieldNames) Method

Flattens the specified form fields.

Declaration

public void flattenFormFields(String[] fieldNames)

Parameters

Name Type Description
fieldNames java.lang.String[]

The names of form fields to flatten.

Remarks

Refer to the following help topic for additional information and examples: Flatten PDF Annotations and Form Fields.

getAccessMode() Method

Returns the document access mode.

Declaration

public DocumentAccessMode getAccessMode()

Returns

Type Description
DocumentAccessMode

The access mode for the current document.

Remarks

The following code snippet opens an encrypted PDF document, verifies the current access mode, and inspects document permissions:

try (InputStream documentStream =
             Files.newInputStream(Path.of("Document.pdf"));
     PdfDocument pdfDocument =
             new PdfDocument(documentStream, "YOUR_PASSWORD")) {

    // Display the current access mode and document permissions.
    System.out.println(
            "Access mode: " + pdfDocument.getAccessMode() +
            "\nData extraction permissions: " + pdfDocument.getDataExtractionPermissions() +
            "\nModification permissions: " + pdfDocument.getModificationPermissions() +
            "\nInteractivity permissions: " + pdfDocument.getInteractivityPermissions());
}

Refer to the following help topic for additional information: Encrypt PDF Documents.

getAttachments() Method

Returns the document attachment collection.

Declaration

public IAttachmentCollection getAttachments()

Returns

Type Description
IAttachmentCollection

The collection of file attachments in the document.

Remarks

The following code snippet attaches a text file to a PDF document:

import com.devexpress.docs.pdf.*;
import com.devexpress.drawing.printing.DXPaperKind;

import java.nio.channels.*;
import java.nio.file.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (PdfDocument pdfDocument = new PdfDocument()) {

            // Add an A4-size page to the document.
            pdfDocument.getPages().add(DXPaperKind.A4);

            // Create an attachment.
            Attachment attachment = new Attachment();
            attachment.setFileName("sample.txt");
            attachment.setData(Files.readAllBytes(Path.of("sample.txt")));
            attachment.setMimeType("text/plain");
            attachment.setDescription("Sample text file");
            attachment.setRelationship(AssociatedFileRelationship.SOURCE);

            // Add attachment to the document.
            pdfDocument.getAttachments().add(attachment);

            // Save the document.
            try (WritableByteChannel channel =
                     FileChannel.open(Path.of("result.pdf"),
                         StandardOpenOption.CREATE,
                         StandardOpenOption.WRITE,
                         StandardOpenOption.TRUNCATE_EXISTING)) {

                pdfDocument.save(channel);
            }
        }
    }
}

Refer to the following help topic for additional information: Attach Files to PDF Documents.

getBookmarks() Method

Gets PDF bookmarks.

Declaration

public IBookmarkCollection getBookmarks()

Returns

Type Description
IBookmarkCollection

The bookmark collection.

Remarks

Refer to the following help topic for additional information: Create and Manage PDF Bookmarks.

The following code snippet creates nested bookmarks. The document outline displays a collapsible bookmark tree.

Bookmark chapters = new Bookmark("Chapters");

// Create child bookmarks.
Bookmark chapter1 = new Bookmark("Chapter 1");
chapter1.setPage(document.getPages().get(1));
chapter1.setDestination(new FitDestination());

Bookmark chapter2 = new Bookmark("Chapter 2");
chapter2.setPage(document.getPages().get(2));
chapter2.setDestination(new FitDestination());

// Add child bookmarks.
chapters.getChildren().add(chapter1);
chapters.getChildren().add(chapter2);

document.getBookmarks().add(chapters);

getDataExtractionPermissions() Method

Returns data extraction permissions.

Declaration

public DocumentDataExtractionPermissions getDataExtractionPermissions()

Returns

Type Description
DocumentDataExtractionPermissions

Data extraction permissions.

Remarks

Refer to the following help topic for additional information: Set PDF Document Permissions.

getFieldNameCollisions() Method

Returns form field name collisions in the document.

Declaration

public Iterable<FormFieldNameCollision> getFieldNameCollisions()

Returns

Type Description
java.lang.Iterable<FormFieldNameCollision>

A collection of form field name collisions in the document.

Remarks

Use the PdfDocument.getFieldNameCollisions() method to identify form fields with the same fully qualified name before you merge or manipulate them.

The following code snippet finds form fields with the same name, merges each group into a single target field, and saves the updated PDF document:

package pdf;

import com.devexpress.docs.pdf.*;

import java.nio.channels.*;
import java.nio.file.*;
import java.util.List;

public class Main {
    public static void main(String[] args) throws Exception {

        try (FileChannel channel = FileChannel.open(Path.of("Document.pdf"));
             PdfDocument pdfDocument = new PdfDocument(channel)) {

            // Get form field name collisions.
            for (FormFieldNameCollision collision : pdfDocument.getFieldNameCollisions()) {

                System.out.println("Field name: " + collision.getFullName());

                List<FormField> fields = collision.getFields();
                if (fields.size() > 1) {

                    // Merge fields with the same name.
                    FormField target = fields.getFirst();
                    FormField[] sources = fields.subList(1, fields.size())
                            .toArray(new FormField[0]);

                    pdfDocument.mergeFormFields(target, sources);
                }
            }

            try (WritableByteChannel writableByteChannel =
                         FileChannel.open(Path.of("Document_Updated.pdf"),
                                 StandardOpenOption.CREATE,
                                 StandardOpenOption.WRITE,
                                 StandardOpenOption.TRUNCATE_EXISTING)) {

                pdfDocument.save(writableByteChannel);
            }
        }
    }
}

Refer to the following help topic for additional information: Resolve Merge Conflicts.

getFields() Method

Returns the interactive form field collection.

Declaration

public IFormFieldCollection getFields()

Returns

Type Description
IFormFieldCollection

The collection of interactive form fields in the document.

Remarks

The following code snippet iterates through all form fields and prints their names and types:

// Iterate through all form fields in the document, including grouped fields.
for (FormField field : pdfDocument.getFields().toFlatIterable()) {
    System.out.println(field.getName());
    System.out.println(field.getClass().getSimpleName());
}

Refer to the following help topics for additional information:

getFileVersion() Method

Returns the PDF file version.

Declaration

public FileVersion getFileVersion()

Returns

Type Description
FileVersion

The PDF file version.

getImageCacheSize() Method

Returns the image cache size.

Declaration

public long getImageCacheSize()

Returns

Type Description
long

The image cache size, in bytes.

getInteractivityPermissions() Method

Returns interactivity permissions.

Declaration

public DocumentInteractivityPermissions getInteractivityPermissions()

Returns

Type Description
DocumentInteractivityPermissions

Interactivity permissions for the current document.

Remarks

Refer to the following help topic for additional information: Set PDF Document Permissions.

getLanguageCulture() Method

Returns the document language culture.

Declaration

public Locale getLanguageCulture()

Returns

Type Description
Locale

The locale associated with the document.

getMarkInfo() Method

Returns the document mark information.

Declaration

public MarkInfo getMarkInfo()

Returns

Type Description
MarkInfo

The mark information stored in the document.

getMetadata() Method

Returns the document metadata.

Declaration

public DocumentMetadata getMetadata()

Returns

Type Description
DocumentMetadata

The document metadata.

Remarks

Refer to the following help topic for additional information: Manage PDF Document Properties and XMP Metadata.

getModificationPermissions() Method

Returns modification permissions.

Declaration

public DocumentModificationPermissions getModificationPermissions()

Returns

Type Description
DocumentModificationPermissions

Modification permissions for the current document.

Remarks

Refer to the following help topic for additional information: Set PDF Document Permissions.

getPages() Method

Returns the document page collection.

Declaration

public IPageCollection getPages()

Returns

Type Description
IPageCollection

The document page collection.

Remarks

Refer to the following help topic for additional information: Manage PDF Pages.

getPrintPermissions() Method

Returns print permissions.

Declaration

public DocumentPrintPermissions getPrintPermissions()

Returns

Type Description
DocumentPrintPermissions

Print permissions for the current document.

Remarks

Refer to the following help topic for additional information: Set PDF Document Permissions.

getStructureTree() Method

Returns the document structure tree.

Declaration

public StructureTree getStructureTree()

Returns

Type Description
StructureTree

The logical structure tree.

Remarks

The PdfDocument.getStructureTree() method returns the structure tree of a PDF document. Each structure tree node is a StructureElement object.

Refer to the following help topic for additional information: Generate and Edit Tagged PDF Documents.

getViewerPreferences() Method

Returns the viewer preferences stored in the document.

Declaration

public ViewerPreferences getViewerPreferences()

Returns

Type Description
ViewerPreferences

The viewer preferences.

importFormData(InputStream stream, ExportDataFormat format) Method

Imports form data into the document.

Declaration

public void importFormData(InputStream stream, ExportDataFormat format)

Parameters

Name Type Description
stream InputStream

The stream that contains the form data to import.

format ExportDataFormat

The format of the imported form data.

Remarks

Refer to the following help topic for additional information: Work with PDF Forms (AcroForms).

importFormData(ReadableByteChannel channel, ExportDataFormat format) Method

Imports form data into the document.

Declaration

public void importFormData(ReadableByteChannel channel, ExportDataFormat format)

Parameters

Name Type Description
channel ReadableByteChannel

The channel that contains the form data to import.

format ExportDataFormat

The format of the imported form data.

Remarks

Refer to the following help topic for additional information: Work with PDF Forms (AcroForms).

mergeFormFields(FormField target, FormField[] sources) Method

Merges specified source form fields into the target form field.

Declaration

public void mergeFormFields(FormField target, FormField[] sources)

Parameters

Name Type Description
target FormField

The target form field.

sources FormField[]

The source form fields to merge into the target form field.

Remarks

Use the mergeFormFields method to merge form fields with the same name into a single target field.

The following code snippet finds form fields with the same name, merges each group into a single target field, and saves the updated PDF document:

package pdf;

import com.devexpress.docs.pdf.*;

import java.nio.channels.*;
import java.nio.file.*;
import java.util.List;

public class Main {
    public static void main(String[] args) throws Exception {

        try (FileChannel channel = FileChannel.open(Path.of("Document.pdf"));
             PdfDocument pdfDocument = new PdfDocument(channel)) {

            // Get form field name collisions.
            for (FormFieldNameCollision collision : pdfDocument.getFieldNameCollisions()) {

                System.out.println("Field name: " + collision.getFullName());

                List<FormField> fields = collision.getFields();
                if (fields.size() > 1) {

                    // Merge fields with the same name.
                    FormField target = fields.getFirst();
                    FormField[] sources = fields.subList(1, fields.size())
                            .toArray(new FormField[0]);

                    pdfDocument.mergeFormFields(target, sources);
                }
            }

            try (WritableByteChannel writableByteChannel =
                         FileChannel.open(Path.of("Document_Updated.pdf"),
                                 StandardOpenOption.CREATE,
                                 StandardOpenOption.WRITE,
                                 StandardOpenOption.TRUNCATE_EXISTING)) {

                pdfDocument.save(writableByteChannel);
            }
        }
    }
}

Refer to the following help topic for additional information: Resolve Merge Conflicts.

optimize(OptimizationOptions options) Method

Optimizes the PDF document based to the specified settings.

Declaration

public boolean optimize(OptimizationOptions options)

Parameters

Name Type Description
options OptimizationOptions

Optimization settings.

Returns

Type Description
boolean

true if the document was optimized; otherwise, false.

Remarks

Pass a configured OptimizationOptions object to the PdfDocument.optimize() method to optimize the PDF document.

The following code snippet removes metadata, attachments, and thumbnails. It also compresses images to reduce the PDF file size.

package pdf;

import com.devexpress.docs.pdf.*;

import java.nio.channels.*;
import java.nio.file.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (FileChannel channel = FileChannel.open(Path.of("Document.pdf"));
             PdfDocument pdfDocument = new PdfDocument(channel)) {

            // Configure image compression.
            ImageCompressionOptions imageOptions = new ImageCompressionOptions();
            imageOptions.setCompressionType(ImageCompressionType.JPEG);
            imageOptions.setJpegQuality(80);

            // Configure optimization options.
            OptimizationOptions options = new OptimizationOptions();
            options.setRemoveMetadata(true);
            options.setRemoveAttachments(true);
            options.setRemoveThumbnails(true);
            options.setImageCompressionOptions(imageOptions);

            // Optimize the PDF document.
            pdfDocument.optimize(options);

            try (WritableByteChannel writableByteChannel =
                    FileChannel.open(Path.of("Document_Optimized.pdf"),
                        StandardOpenOption.CREATE,
                        StandardOpenOption.WRITE,
                        StandardOpenOption.TRUNCATE_EXISTING)) {

                pdfDocument.save(writableByteChannel);
            }
        }
    }
}

Refer to the following help topic for additional information: Optimize PDF Documents.

removeEncryption() Method

Removes encryption from the document.

Declaration

public void removeEncryption()

Remarks

Refer to the following help topic for additional information: Encrypt PDF Documents.

removeText(Iterable<TextSearchInfo> textSearchResults) Method

Removes text identified by the specified search results.

Declaration

public void removeText(Iterable<TextSearchInfo> textSearchResults)

Parameters

Name Type Description
textSearchResults java.lang.Iterable<TextSearchInfo>

Search results.

removeText(String text, int startPageIndex, int endPageIndex) Method

Removes text from the specified page range.

Declaration

public void removeText(String text, int startPageIndex, int endPageIndex)

Parameters

Name Type Description
text String

The text to remove.

startPageIndex int

The zero-based page index at which to start removing text.

endPageIndex int

The zero-based page index at which to stop removing text.

removeText(String text, int startPageIndex) Method

Removes the specified text starting from the specified page.

Declaration

public void removeText(String text, int startPageIndex)

Parameters

Name Type Description
text String

The text to remove.

startPageIndex int

The zero-based index of the page at which to start removing text.

removeText(String text, TextSearchOptions options, int startPageIndex, int endPageIndex) Method

Removes text from the specified page range using the specified search options.

Declaration

public void removeText(String text, TextSearchOptions options, int startPageIndex, int endPageIndex)

Parameters

Name Type Description
text String

The text to remove.

options TextSearchOptions

Options that control the text search.

startPageIndex int

The zero-based page index at which to start removing text.

endPageIndex int

The zero-based page index at which to stop removing text.

removeText(String text, TextSearchOptions options, int startPageIndex) Method

Removes text from the document starting at the specified page using the specified search options.

Declaration

public void removeText(String text, TextSearchOptions options, int startPageIndex)

Parameters

Name Type Description
text String

The text to remove.

options TextSearchOptions

Options that control the text search.

startPageIndex int

The zero-based page index at which to start removing text.

removeText(String text, TextSearchOptions options) Method

Removes the specified text from the document using the specified search options.

Declaration

public void removeText(String text, TextSearchOptions options)

Parameters

Name Type Description
text String

The text to remove.

options TextSearchOptions

Options that control the text search.

removeText(String text) Method

Removes the specified text from the document.

Declaration

public void removeText(String text)

Parameters

Name Type Description
text String

The text to remove.

save(OutputStream stream, SaveOptions options) Method

Saves the document to an output stream using specified options.

Declaration

public void save(OutputStream stream, SaveOptions options)

Parameters

Name Type Description
stream OutputStream

The output stream.

options SaveOptions

Options that control the save operation.

Remarks

Refer to the following help topic for additional information: Save PDF Documents.

save(OutputStream stream) Method

Saves the document to an output stream.

Declaration

public void save(OutputStream stream)

Parameters

Name Type Description
stream OutputStream

The output stream.

Remarks

The following code snippet loads a PDF document, adds a page, and saves the document using an output stream:

package barcodes;

import com.devexpress.docs.pdf.*;
import com.devexpress.drawing.printing.*;

import java.io.OutputStream;
import java.nio.file.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (InputStream stream =
                     Files.newInputStream(Path.of("Document.pdf"));
             PdfDocument pdfDocument = new PdfDocument(stream)) {

            // Add an A4-size page to the document.
            pdfDocument.getPages().add(DXPaperKind.A4);

            // Configure save options.
            SaveOptions saveOptions = new SaveOptions();
            saveOptions.setUpdateCreatedAt(true);
            saveOptions.setSyncMetadata(true);

            // Save the document to a PDF file.
            try (OutputStream outputStream =
                         Files.newOutputStream(Path.of("Document.pdf"))) {

                pdfDocument.save(outputStream);
            }
        }
    }
}

Refer to the following help topic for additional information: Save PDF Documents.

save(WritableByteChannel channel, SaveOptions options) Method

Saves the document to a writable channel using specified options.

Declaration

public void save(WritableByteChannel channel, SaveOptions options)

Parameters

Name Type Description
channel WritableByteChannel

The channel to which the document is written.

options SaveOptions

Options that control the save operation.

Remarks

The following code snippet loads a PDF document, adds a page, and saves the document using a writable channel:

import com.devexpress.docs.pdf.*;
import com.devexpress.drawing.printing.*;

import java.nio.channels.*;
import java.nio.file.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (FileChannel channel = FileChannel.open(Path.of("Document.pdf"));
             PdfDocument pdfDocument = new PdfDocument(channel)) {

            // Add an A4-size page to the document.
            pdfDocument.getPages().add(DXPaperKind.A4);

            // Configure save options.
            SaveOptions saveOptions = new SaveOptions();
            saveOptions.setUpdateCreatedAt(true);
            saveOptions.setSyncMetadata(true);

            // Save the document to a PDF file.
            try (WritableByteChannel writableByteChannel =
                         FileChannel.open(Path.of("Document.pdf"),
                                 StandardOpenOption.CREATE,
                                 StandardOpenOption.WRITE,
                                 StandardOpenOption.TRUNCATE_EXISTING)) {

                pdfDocument.save(writableByteChannel, saveOptions);
            }
        }
    }
}

Refer to the following help topic for additional information: Save PDF Documents.

save(WritableByteChannel channel) Method

Saves the document to a writable channel.

Declaration

public void save(WritableByteChannel channel)

Parameters

Name Type Description
channel WritableByteChannel

The channel to which the document is written.

Remarks

Refer to the following help topic for additional information: Save PDF Documents.

setImageCacheSize(long value) Method

Sets the image cache size.

Declaration

public void setImageCacheSize(long value)

Parameters

Name Type Description
value long

The image cache size, in bytes.

setLanguageCulture(Locale value) Method

Sets the document language culture.

Declaration

public void setLanguageCulture(Locale value)

Parameters

Name Type Description
value Locale

The locale to assign to the document.

setMarkInfo(MarkInfo value) Method

Sets the document mark information.

Declaration

public void setMarkInfo(MarkInfo value)

Parameters

Name Type Description
value MarkInfo

The mark information to assign to the document.

setMetadata(DocumentMetadata value) Method

Assigns metadata to the document.

Declaration

public void setMetadata(DocumentMetadata value)

Parameters

Name Type Description
value DocumentMetadata

The metadata to assign to the document.

Remarks

Refer to the following help topic for additional information: Manage PDF Document Properties and XMP Metadata.

setViewerPreferences(ViewerPreferences value) Method

Assigns the viewer preferences to the document.

Declaration

public void setViewerPreferences(ViewerPreferences value)

Parameters

Name Type Description
value ViewerPreferences

The viewer preferences.