Mark Gill
Mark Gill

Reputation: 1

Java Image to PDF

How can an image file be converted into a PDF file using java? I am taking output from a graphic library. the output that I am able to export is in image formats like JPEG and PNG. I want to convert that image file to PDF file.

Upvotes: 0

Views: 1049

Answers (2)

Jayesh
Jayesh

Reputation: 101

Use IText PDF API for Java you must first download the IText JAR file from the IText website

First a Document instance is created.

Second, a PDFWriter is created, passing the Document instance and an OutputStream to its constructor. The Document instance is the document we are currently adding content to. The OutputStream is where the generated PDF document is written to.

 OutputStream file =     newFileOutputStream(newFile("/path/JavaGeneratedPDF.pdf"));      
    Document document = new Document();
    PdfWriter.getInstance(document, file);

Here make sure that you handle DocumentException

Inserting Image in PDF

Image image = Image.getInstance ("/Image.jpg");
        image.scaleAbsolute(200f, 100f); //image width,height   

Here make sure that you handle MalformedURLException

Now Open PDF document, add image and close document instance

document.open();                   
document.add(image);
document.close();
file.close();

Upvotes: 0

mark stephens
mark stephens

Reputation: 3184

You can use Itext to add an Image to a PDF.

Upvotes: 1

Related Questions