ImageGear Java PDF > How to... > Add an Image to a PDF |
To add an image to a PDF document:
The following is an illustration of how to add an image from file or from a BufferedImage to the PDF page:
Copy Code | |
---|---|
import com.accusoft.imagegearpdf.*; import java.io.*; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; class PdfDemo { private PDF pdf; private Document document; // Add an image file to the specified page of the PDF document. public boolean addImage(String imageFilename, long pageNumber) { Page page = null; try { // Retrieve specific page to add image into. page = document.getPage(pageNumber); // Get options for adding image. AddImageOptions addOptions = getAddImageOptions(); // Add image to PDF page. page.addImage(imageFilename, addOptions); return true; } catch (Throwable ex) { // Failed to add image to the page. System.err.println("Exception: " + ex.toString()); return false; } finally { if (page != null) { // Close PDF page as it is not needed anymore. page.close(); } } } // Add a Bufferedimage to the specified page of the PDF document. public boolean addImage(BufferedImage bufferedImage, long pageNumber) { Page page = null; try { // Retrieve specific page to add image into. page = document.getPage(pageNumber); // Get options for adding image. AddImageOptions addOptions = getAddImageOptions(); // Convert BufferedImage to byte array. ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (!ImageIO.write(bufferedImage, "png", outputStream)) { // The source image could not be written as a PNG image stream. return false; } byte[] imageData = outputStream.toByteArray(); // Add image to PDF page. page.addImage(imageData, addOptions); return true; } catch (Throwable ex) { // Failed to add image to the page. System.err.println("Exception: " + ex.toString()); return false; } finally { if (page != null) { // Close PDF page as it is not needed anymore. page.close(); } } } // Prepare and return AddImageOptions. private AddImageOptions getAddImageOptions() { AddImageOptions options = new AddImageOptions(); options.setX(20); options.setY(400); options.setWidth(200); options.setHeight(200); return options; } } |