Create PDF Files in Java

Aspose.PDF for Java supports both simple document creation and OCR-assisted searchable PDF workflows.

Create a new PDF document

Use this approach when you need to generate a simple PDF file from scratch.

  1. Create a new PDF Document.
  2. Add a Page to the document.
  3. Create a TextFragment and add it to the page.
  4. Save the output PDF Document.
public static void createNewDocument(Path outputFile) {
    try (Document document = new Document()) {
        Page page = document.getPages().add();
        page.getParagraphs().add(new TextFragment("Hello World!"));
        document.save(outputFile.toString());
    }
}

Create a searchable PDF

The createSearchablePdf example uses Document.convert(...) with a CallBackGetHocr implementation. The callback writes the source image to a temporary file, invokes Tesseract with the hocr option, reads the generated HOCR markup, and returns it to Aspose.PDF.

  1. Open the source PDF Document.
  2. Create the CallBackGetHocr callback and convert the source document to searchable PDF content.
  3. Save the updated PDF Document.
public static void createSearchablePdf(Path inputFile, Path outputFile) {
    Path tempDir = outputFile.getParent().resolve("ocr-temp");
    CallBackGetHocr cbgh = new CallBackGetHocr() {
        @Override
        public String invoke(java.awt.image.BufferedImage img) {
            // save the image, run Tesseract with "hocr", and return the HOCR text
            return fileContents.toString();
        }
    };
    try (Document document = new Document(inputFile.toString())) {
        document.convert(cbgh);
        document.save(outputFile.toString());
    }
}

Get document window settings

Use this example to inspect the current viewer preferences stored in an existing PDF document.

  1. Open the source PDF Document.
  2. Read the required window and display properties from the document.
  3. Output the current settings for inspection or debugging.
public static void getDocumentWindow(Path inputFile) {
    try (Document document = new Document(inputFile.toString())) {
        System.out.println("CenterWindow: " + document.isCenterWindow());
        System.out.println("Direction: " + document.getDirection());
        System.out.println("DisplayDocTitle: " + document.isDisplayDocTitle());
        System.out.println("FitWindow: " + document.isFitWindow());
        System.out.println("HideMenuBar: " + document.isHideMenubar());
        System.out.println("HideToolBar: " + document.isHideToolBar());
        System.out.println("HideWindowUI: " + document.isHideWindowUI());
        System.out.println("NonFullScreenPageMode: " + document.getNonFullScreenPageMode());
        System.out.println("PageLayout: " + document.getPageLayout());
        System.out.println("PageMode: " + document.getPageMode());
    }
}

Set document window preferences

This example updates how the PDF should be displayed when it is opened in a compatible viewer.

  1. Open the source PDF Document.
  2. Set the required window, layout, and page-mode preferences.
  3. Save the updated PDF Document.
public static void setDocumentWindow(Path inputFile, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        document.setCenterWindow(true);
        document.setDirection(Direction.R2L);
        document.setDisplayDocTitle(true);
        document.setFitWindow(true);
        document.setHideMenubar(true);
        document.setHideToolBar(true);
        document.setHideWindowUI(true);
        document.setNonFullScreenPageMode(PageMode.UseOC);
        document.setPageLayout(PageLayout.TwoColumnLeft);
        document.setPageMode(PageMode.UseThumbs);
        document.save(outputFile.toString());
    }
}

Embed fonts in an existing PDF

Use this approach when a document should carry its required fonts for more reliable rendering on other systems.

  1. Open the source PDF Document.
  2. Enable standard font embedding and iterate through the fonts used by each Page.
  3. Mark any non-embedded Font objects for embedding.
  4. Save the updated document.
public static void embeddedFonts(Path inputFile, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        document.setEmbedStandardFonts(true);
        for (Page page : document.getPages()) {
            for (Font pageFont : page.getResources().getFonts()) {
                if (!pageFont.isEmbedded()) {
                    pageFont.setEmbedded(true);
                }
            }
        }
        document.save(outputFile.toString());
    }
}

Embed fonts when creating a new PDF

This example creates a new PDF and assigns an embedded font to the text content from the start.

  1. Create a new PDF Document and add a Page.
  2. Create the required TextFragment, TextSegment, and TextState.
  3. Resolve the target Font from the repository and mark it as embedded.
  4. Add the text content to the page and save the output document.
public static void embeddedFontsInNewDocument(Path outputFile) {
    try (Document document = new Document()) {
        try (Page page = document.getPages().add()) {
            TextFragment fragment = new TextFragment("");
            TextSegment segment = new TextSegment(" This is a sample text using Custom font.");
            TextState textState = new TextState();
            Font font = FontRepository.findFont("Arial");
            font.setEmbedded(true);
            textState.setFont(font);
            segment.setTextState(textState);
            fragment.getSegments().add(segment);
            page.getParagraphs().add(fragment);
        }
        document.save(outputFile.toString());
    }
}

Set a default font for PDF output

Use this pattern when the saved document should fall back to a specific font during output generation.

  1. Open the source PDF Document.
  2. Create PdfSaveOptions and set the default font name.
  3. Save the document with the configured save options.
public static void setDefaultFont(Path inputFile, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        PdfSaveOptions saveOptions = new PdfSaveOptions();
        saveOptions.setDefaultFontName("Arial");
        document.save(outputFile.toString(), saveOptions);
    }
}

Get all fonts used in a PDF

This example lists every font detected in the document so you can audit font usage before exporting or updating the file.

  1. Open the source PDF Document.
  2. Enumerate the fonts returned by the document font utilities.
  3. Output the name of each detected Font.
public static void getAllFonts(Path inputFile) {
    try (Document document = new Document(inputFile.toString())) {
        for (Font font : document.getFontUtilities().getAllFonts()) {
            System.out.println(font.getFontName());
        }
    }
}

Improve font embedding by subsetting fonts

Use this approach when you want to reduce font payload while keeping embedded font data aligned with document usage.

  1. Open the source PDF Document.
  2. Run font subsetting through the document font utilities with the required FontSubsetStrategy values.
  3. Save the optimized document.
public static void improveFontsEmbedding(Path inputFile, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        document.getFontUtilities().subsetFonts(FontSubsetStrategy.SubsetAllFonts);
        document.getFontUtilities().subsetFonts(FontSubsetStrategy.SubsetEmbeddedFontsOnly);
        document.save(outputFile.toString());
    }
}

Set the document open zoom factor

This example configures the initial zoom level that should be applied when the PDF is opened.

  1. Open the source PDF Document.
  2. Create a GoToAction with an XYZExplicitDestination.
  3. Assign the action as the document open action and save the result.
public static void setZoomFactor(Path inputFile, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        GoToAction action = new GoToAction(new XYZExplicitDestination(1, 0.0, 0.0, 0.5));
        document.setOpenAction(action);
        document.save(outputFile.toString());
    }
}

Get the document open zoom factor

Use this example to inspect whether a PDF already defines an explicit zoom level for its open action.

  1. Open the source PDF Document.
  2. Check whether the open action is a GoToAction with an XYZExplicitDestination.
  3. Output the configured zoom value or report that no zoom is set.
public static void getZoomFactor(Path inputFile) {
    try (Document document = new Document(inputFile.toString())) {
        if (document.getOpenAction() instanceof GoToAction action
                && action.getDestination() instanceof XYZExplicitDestination destination) {
            System.out.println("Zoom: " + destination.getZoom());
        } else {
            System.out.println("Zoom: not set");
        }
    }
}