Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save documentprocessing/57fbcacf65c466ffe88f6d01d835c115 to your computer and use it in GitHub Desktop.
Save documentprocessing/57fbcacf65c466ffe88f6d01d835c115 to your computer and use it in GitHub Desktop.
Create New PDF File from Scratch using Apache PDFBox
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import java.io.IOException;
public class CreatePDFExample {
public static void main(String[] args) {
// 1. Create a new empty document
try (PDDocument document = new PDDocument()) {
// 2. Create a blank page (A4 size by default)
PDPage page = new PDPage();
document.addPage(page);
// 3. Prepare content for the page
try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
// 4. Begin text content
contentStream.beginText();
// 5. Set font and font size
contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
// 6. Position the text (x,y coordinates from bottom-left corner)
contentStream.newLineAtOffset(100, 700);
// 7. Add text content
contentStream.showText("Hello, PDFBox!");
contentStream.newLineAtOffset(0, -20); // Move down 20 units
contentStream.showText("This is a new PDF created with Java.");
// 8. End text content
contentStream.endText();
}
// 9. Save the document to file
document.save("new-document.pdf");
System.out.println("PDF created successfully!");
} catch (IOException e) {
System.err.println("Error creating PDF: " + e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment