开发者

Java Image to PDF

开发者 https://www.devze.com 2023-04-11 20:13 出处:网络
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 开发者_JAVA技巧is in image formats like JPEG and PNG.

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 开发者_JAVA技巧is in image formats like JPEG and PNG. I want to convert that image file to PDF file.


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


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消