Reputation: 515
I have used PDFBox to convert a png image to pdf document and i am successfully able to do that.
But i am encountering an issue in which the the pdf document only shows 50% width of the image (height is shown full).Please help me with this.
The code i am using is as follows:
public static void createPDFFromImage( String file, String image) throws IOException, COSVisitorException
{
PDDocument doc = null;
try
{
doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage( page );
PDXObjectImage ximage = null;
if( image.toLowerCase().endsWith( ".jpg" ) || image.toLowerCase().endsWith( ".jpeg" ))
{
BufferedImage awtImage = ImageIO.read( new File( image ) );
ximage = new PDJpeg(doc, awtImage, 0 );
}
else
{
BufferedImage awtImage = new BufferedImage(250,250, BufferedImage.TYPE_INT_RGB);
awtImage = ImageIO.read(new FileImageInputStream(new File( image )));
ximage = new PDPixelMap(doc, awtImage);
}
System.out.println(" Width of the image.... " + ximage.getWidth());
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
contentStream.drawImage( ximage, 20, 20);
//contentStream.drawImage( ximage, 20, 20 );
contentStream.close();
doc.save( file );
}
finally
{
if( doc != null )
{
doc.close();
}
}
}
NOTE:everytime the dimension of the image gets changed while saving
Please help. Thanks
Upvotes: 0
Views: 933
Reputation: 163
These code may be hepful to you.
public void createPDFFromImage(String pdfFile,
List<String> imgList,int x, int y, float scale) throws IOException, COSVisitorException {
// the document
PDDocument doc = null;
try {
doc = new PDDocument();
Iterator iter = imgList.iterator();
int imgIndex=0;
while(iter.hasNext()) {
PDPage page = new PDPage();
doc.addPage(page);
BufferedImage tmp_image = ImageIO.read(new File(iter.next().toString()));
BufferedImage image = new BufferedImage(tmp_image.getWidth(), tmp_image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
image.createGraphics().drawRenderedImage(tmp_image, null);
PDXObjectImage ximage = new PDPixelMap(doc, image);
imgIndex++;
PDPageContentStream contentStream = new PDPageContentStream(
doc, page,true,true);
contentStream.drawXObject(ximage, x, y, ximage.getWidth()*scale, ximage.getHeight()*scale);
contentStream.close();
}
doc.save(pdfFile);
} finally {
if (doc != null) {
doc.close();
}
}
}
Upvotes: 0