Sample program showing how to create a PDF using jPDFProcess. You first create a PDF, add a page to it then use the Graphics object form the page to draw onto it. On the page we draw text and an image. In this little snippet, the compression used for the image within the PDF document is set to JPEG2000. The same code can be used to add content to an existing page.

// create document
PDFDocument pdfDoc = new PDFDocument ();
 
// add a page
PDFPage page = pdfDoc.appendNewPage(8.5 * 72, 11 * 72);
 
// get graphics from the page
// this object is a Graphics2D Object and you can draw anything 
// you would draw on a Graphics2D
PDFGraphics g2d = (PDFGraphics) page.createGraphics();
 
// set image compression to JPEG2000
g2d.setImageCompression(new ImageCompression(ImageCompression.COMPRESSION_JPEG2000, 0.8f));
 
// load image 
BufferedImage myimage = ImageIO.read(new File("C:\\myfolder\\image.png"));
 
// draw image on the graphics object of the page 
g2d.drawImage(myimage,5,5,null);
 
// courier 12 font
Font courierFont = PDFGraphics.COURIER.deriveFont(24f);            
g2d.setColor(Color.red);
 
// draw text on the graphics object of the page
page.drawText("NEW TEXT", courierFont, Color.BLUE, 494, 14, null);
 
// Save the document
pdfDoc.saveDocument ("C:\\myfolder\\out.pdf");

Download Full Java Sample Code

Tagged: