How to Create PDF using Java

In this short how-to guide, we will walk you through to how to create PDF using Java. This tutorial will help you, how to generate PDF file in Java using simple API calls, whether you are working in Windows, macOS, or Linux platforms.

Steps to Create PDF using Java

  1. Configure your project to add Aspose.PDF for Java from the Maven repository
  2. Include reference to Aspose.PDF namespace in your application
  3. Instantiate Document class object to generate PDF from Java
  4. Initialize TextFragment Class to add text and set textual properties
  5. Create PDF from Java by saving on disk

In the above steps, an instance of Document class is used to create an empty PDF file which is followed by addition of empty page in pages collection. By using TextBuilder Class instance, we will add text and also set textual properties. Finally, we will generate PDF using Java.

Code to Create PDF from Java

import com.aspose.pdf.Document;
import com.aspose.pdf.FontRepository;
import com.aspose.pdf.License;
import com.aspose.pdf.Page;
import com.aspose.pdf.Position;
import com.aspose.pdf.TextBuilder;
import com.aspose.pdf.TextFragment;
public class CreatePdfUsingJava {
public static void main(String[] pdfCreateArgs) throws Exception {
// Setting the product license to create PDF in Java
License lic = new License();
lic.setLicense("Total.Java.Family.lic");
// Instantiate document class object to generate PDF from Java
Document document = new Document();
// Include a page in PDF
Page pdfPage = document.getPages().add();
// TextFragment class to add text
TextFragment textFragment = new TextFragment("Knowledgebase Testing Text");
// Setting different properties of text
textFragment.setPosition(new Position(100, 600));
textFragment.getTextState().setFontSize(12);
textFragment.getTextState().setFont(FontRepository.findFont("TimesNewRoman"));
textFragment.getTextState().setBackgroundColor(com.aspose.pdf.Color.fromRgb(java.awt.Color.LIGHT_GRAY));
textFragment.getTextState().setForegroundColor(com.aspose.pdf.Color.fromRgb(java.awt.Color.RED));
// Create TextBuilder object to add page
TextBuilder textBuilder = new TextBuilder(pdfPage);
// Include added fragment to the PDF page
textBuilder.appendText(textFragment);
// Creating PDF using Java
document.save("Create Pdf using Java.pdf");
}
}

In the aforementioned example, we started by creating an empty PDF file using Document class object and added an empty page inside that. Then by using TextFragment class instance, we added the desired text and set the required properties. By using TextBuilder class instance, the added page and respective text is appended in PDF document. Finally, using Java create PDF file is managed by save method.

In the last topic, we focused on how to Flatten PDF Form Fields in Java. Whereas, the above example focuses on, how to create PDF in Java.

 English