在Android中,iText将图像转换为pdf太短

时间:2014-08-12 10:18:29

标签: android pdf itext

我正在将图像从SD卡转换为pdf文件,但不幸的是,该图像没有采用pdf文件的全长。如何设置图像以涵盖所有pdf文件。这是我的代码

File f = new File(filePath);
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image companyLogo = Image.getInstance(stream.toByteArray());
companyLogo.setAbsolutePosition(10,700);
companyLogo.scalePercent(100);
document.add(companyLogo); 

任何人都可以告诉我,我该怎么做才能涵盖完整的pdf页面。任何帮助将非常感激。谢谢:))

1 个答案:

答案 0 :(得分:1)

File f = new File(filePath);
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image companyLogo = Image.getInstance(stream.toByteArray());

//get size of document
Rectangle documentRect = document.getPageSize();

if(bmp.getWidth()>documentRect.getWidth() || bmp.getHeight()>documentRect.getHeight())
{
    //bitmap is larger than page,so set bitmap's size similar to the whole page 
    companyLogo.scaleAbsolute(documentRect.getWidth(), documentRect.getHeight());
}
else
{
    //bitmap is smaller than page, so add bitmap simply.[note: if you want to fill page by stretching image, you may set size similar to page as above]
    companyLogo.scaleAbsolute(bmp.getWidth(), bmp.getHeight());
}

//set the image with center of the page
companyLogo.setAbsolutePosition((documentRect.getWidth()-image.getScaledWidth())/2, (documentRect.getHeight()-image.getScaledHeight())/2);

注意:

使用上面的代码强制图像覆盖整个页面,

只需替换

if(bmp.getWidth()>documentRect.getWidth() || bmp.getHeight()>documentRect.getHeight())
{
    //bitmap is larger than page,so set bitmap's size similar to the whole page 
    companyLogo.scaleAbsolute(documentRect.getWidth(), documentRect.getHeight());
}
else
{
    //bitmap is smaller than page, so add bitmap simply.[note: if you want to fill page by stretching image, you may set size similar to page as above]
    companyLogo.scaleAbsolute(bmp.getWidth(), bmp.getHeight());
}

    companyLogo.scaleAbsolute(documentRect.getWidth(), documentRect.getHeight());

我希望它会有所帮助!!