I'm using this depo git application that allows you to capture or choose images and save them in a pdf document. It's working great except the image saved does not fit the whole screen.
So I tried changing theses numbers Document document = new Document(PageSize.A4, 38, 38, 50, 38);
or image.setBorderWidth(15);
(documentRect.getWidth() - image.getScaledWidth()) / 2,
(documentRect.getHeight() - image.getScaledHeight()) / 2);
but no luck...
Furthermore the author didn't not use any imageview
on layout so I have to edit problematically. Any ideas ?
Update : apparently changing image.scaleAbsolute(bmp.getWidth(), bmp.getHeight());
to
image.scaleAbsolute(500f, 500f);
or image.scalePercent(500f);
does the trick (I have to play with the numbers to fit the page).
Downside the quality image is horrible...
PdfUtils
public static final String LOG_ACTIVITY = "PdfUtils";
public static String ImgPdf(Activity activity, ArrayList<String> listPathImg,String folder, String pdfName) {
String result ="";
Image image;
String path = FileUtils.createFolderApp(folder);
path = path + pdfName + ".pdf";
Document document = new Document(PageSize.A4, 38, 38, 50, 38);
Log.v(LOG_ACTIVITY, "Document Created");
Rectangle documentRect = document.getPageSize();
try {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
document.open();
for (int i = 0; i < listPathImg.size(); i++) {
Bitmap bmp = MediaStore
.Images
.Media
.getBitmap(
activity.getContentResolver(),
Uri.fromFile(new File(listPathImg.get(i))));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 70, stream);
image = Image.getInstance(listPathImg.get(i));
if (bmp.getWidth() > documentRect.getWidth() || bmp.getHeight() > documentRect.getHeight()) {
//bitmap is larger than page,so set bitmap's size similar to the whole page
image.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]
image.scaleAbsolute(bmp.getWidth(), bmp.getHeight());
}
image.setAbsolutePosition(
(documentRect.getWidth() - image.getScaledWidth()) / 2,
(documentRect.getHeight() - image.getScaledHeight()) / 2);
image.setBorder(Image.BOX);
image.setBorderWidth(15);
document.add(image);
document.newPage();
}
result=path;
} catch (Exception err) {
err.printStackTrace();
result="";
} finally {
document.close();
}
return result;
}
Solution from this answer.
I changed image.scaleAbsolute(bmp.getWidth(), bmp.getHeight());
to
image.scalePercent(scaler);
ofc you have to include
float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
- document.rightMargin() - indentation) / image.getWidth()) * 100;
Now it fit. Though the image quality is not perfect.