Breaking News
Home / Java / Java Snippets / How to create PDF file using Java API?

How to create PDF file using Java API?

Create PDF using Java APIThis snippet shows how to created a empty PDF file using the PDFBox Apache Framework.

package com.livrona.snippets.pdf;

import java.io.IOException;

import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

/**
 * This snippet shows how to create a blank PDF and write the contents to a
 * file.
 */
public class CreateBlankPDF {

	/**
	 * Create the Blank PDF
	 * 
	 * @param file
	 * @throws IOException
	 * @throws COSVisitorException
	 */
	public void create(String file) throws IOException, COSVisitorException {
		PDDocument document = null;
		try {
			// create the PDF document object
			document = new PDDocument();

			// create an empty page, add it to the document
			PDPage blankPage = new PDPage();
			document.addPage(blankPage);

			// save the document to the file stream.
			document.save(file);
		} finally {
			if (document != null) {
				document.close();
			}
		}
	}

	/**
	 * This will create a blank document.
	 * 
	 * @param args
	 *            The command line arguments.
	 * 
	 * @throws IOException
	 *             If there is an error writing the document data.
	 * @throws COSVisitorException
	 *             If there is an error generating the data.
	 */
	public static void main(String[] args) throws IOException,
			COSVisitorException {
		CreateBlankPDF creator = new CreateBlankPDF();
		if (args.length != 1) {
			creator.usage();
		} else {

			creator.create(args[0]);
		}
	}

	/**
	 * This will print out a message telling how to use this example.
	 */
	private void usage() {
		System.err.println("usage: " + this.getClass().getName()
				+ " <output-pdf-file>");
	}
}

 [pb_builder]

Check Also

How to progamatically get the Java version?

Snippet The key here is to use the system property java.version and get minor and …

Leave a Reply