Discussion

3
Replies
1248
Views
VamsiK18 Member since 2016 3 posts
Areteans
Posted: 2 years ago
Last activity: 3 months 3 weeks ago

Convert any type of Image to PDF

Hi All,
Below is the code to convert any encoded Base64 Image stream to encoded PDF stream:
It can convert TIFF, JPG, JPEG, PNG, GIF etc.,
//Prepare byte array output stream
java.io.ByteArrayOutputStream outfile = new java.io.ByteArrayOutputStream();
//Create new document
com.lowagie.text.Document document = new com.lowagie.text.Document();
try{
// Get Instance of PDF writer
com.lowagie.text.pdf.PdfWriter writer = com.lowagie.text.pdf.PdfWriter.getInstance(document,outfile);
writer.setStrictImageSequence(true);
// Open the document
document.open();
//TIFF Conversion
if (FileType.equalsIgnoreCase("tif")||FileType.equalsIgnoreCase("tiff"))
{
com.lowagie.text.pdf.RandomAccessFileOrArray ra = new com.lowagie.text.pdf.RandomAccessFileOrArray(Base64Util.decodeToByteArray(attachStream));
// count number of pages in TIFF
int pages = com.lowagie.text.pdf.codec.TiffImage.getNumberOfPages(ra);
for(int i = 0; i< pages;i++)
{
//get each image for TIFF file
com.lowagie.text.Image tiff = com.lowagie.text.pdf.codec.TiffImage.getTiffImage(ra,i+1);
// Scale the Image
float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin()) / tiff.getWidth()) * 100;
tiff.scalePercent(scaler);
// Add each image to document
document.add(tiff);
}
}
//Other types of images (JPG,JPEG,PNG,GIF etc.,)
else
{
com.lowagie.text.Image jpg = com.lowagie.text.Image.getInstance(Base64Util.decodeToByteArray(attachStream));
//Scale the image
float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin()) / jpg.getWidth()) * 100;
jpg.scalePercent(scaler);
//Add image to document
document.add(jpg);
}
document.close();
String pdfStream = Base64Util.encodeToString(outfile.toByteArray());
ConvertedStream = pdfStream;
outfile.flush();
}catch(Exception e){
//e.printstacktrace();
}
Low-Code App Development Data Integration Java and Activities User Interface Developer Knowledge Share
Share this page LinkedIn