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.
- Create a new PDF Document.
- Add a Page to the document.
- Create a TextFragment and add it to the page.
- 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.
- Open the source PDF Document.
- Create the
CallBackGetHocrcallback and convert the source document to searchable PDF content. - 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.
- Open the source PDF Document.
- Read the required window and display properties from the document.
- 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.
- Open the source PDF Document.
- Set the required window, layout, and page-mode preferences.
- 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.
- Open the source PDF Document.
- Enable standard font embedding and iterate through the fonts used by each Page.
- Mark any non-embedded Font objects for embedding.
- 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.
- Create a new PDF Document and add a Page.
- Create the required TextFragment, TextSegment, and TextState.
- Resolve the target Font from the repository and mark it as embedded.
- 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.
- Open the source PDF Document.
- Create PdfSaveOptions and set the default font name.
- 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.
- Open the source PDF Document.
- Enumerate the fonts returned by the document font utilities.
- 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.
- Open the source PDF Document.
- Run font subsetting through the document font utilities with the required FontSubsetStrategy values.
- 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.
- Open the source PDF Document.
- Create a GoToAction with an XYZExplicitDestination.
- 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.
- Open the source PDF Document.
- Check whether the open action is a GoToAction with an XYZExplicitDestination.
- 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");
}
}
}