Create pdf with image using java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class GeneratePDFWithImageDemo {
public static void main(String[] args) {
new GeneratePDFWithImageDemo().createPDF();
}
public void createPDF(){
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("C://Test.pdf"));
document.open();
PdfPTable table = new PdfPTable(1); //1 column.
Image image = Image.getInstance("C://Image/MyImage.jpg");
image.scaleToFit(800f, 600f);
image.scaleAbsolute(800f,600f); // Give the size of image you want to print on pdf
PdfPCell nestedImgCell=new PdfPCell(image);
table.addCell(nestedImgCell);
document.add(table);
document.close ();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("======== PDF Created Successfully =========);
}
}
Comments
Post a Comment