Java converts an image into a PDF file

Source: Internet
Author: User

/**
* Convert an image into a PDF file
* Location of the IMG in which imgfilepath needs to be converted. For example, imgfilepath = "D: \ projectpath \ 55555.jpg ";
* The location of the PDF converted by pdffilepath is pdffilepath = "D: \ projectpath \ test.pdf ";
* @ Param Image
* @ Return
* @ Throws ioexception
*/

Public Boolean imgtopdf (string imgfilepath, string pdffilepath) throws ioexception {
File file = new file (imgfilepath );
If (file. exists ()){
Document document = new document ();
Fileoutputstream Fos = NULL;
Try {
Fos = new fileoutputstream (pdffilepath );
Using writer. getinstance (document, FOS );

// Add some information about the PDF document, such as the author and topic.
Document. addauthor ("arui ");
Document. addsubject ("test pdf .");
// Set the document size
Document. setpagesize (pagesize. A4 );
// Open the document
Document. open ();
// Write a piece of text
// Document. Add (new paragraph ("just test ..."));
// Read an image
Image image = image. getinstance (imgfilepath );
Float imageheight = image. getscaledheight ();
Float imagewidth = image. getscaledwidth ();
Int I = 0;
While (imageheight> 500 | imagewidth> 500 ){
Image. scalepercent (100-i );
I ++;
Imageheight = image. getscaledheight ();
Imagewidth = image. getscaledwidth ();
System. Out. println ("imageheight->" + imageheight );
System. Out. println ("imagewidth->" + imagewidth );
}

Image. setalignment (image. align_center );
//// Set the absolute position of the image
// Image. setabsoluteposition (0, 0 );
// Image. scaleabsolute (500,400 );
// Insert an image
Document. Add (image );
} Catch (incluentexception de ){
System. Out. println (De. getmessage ());
} Catch (ioexception IOE ){
System. Out. println (IOE. getmessage ());
}
Document. Close ();
FOS. Flush ();
FOS. Close ();
Return true;
} Else {
Return false;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.