我正在使用iText库通过选择图像来创建pdf。 一切都很好,但我遇到了这个问题。
当图像的高度大于文档的大小时,图像在pdf中看起来很奇怪。
下面是我创建pdf的代码。我还附上了pdf的快照。
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDFfiles/");
Path path = path + filename +
".pdf";
File f = new File(file, filename +
".pdf");
Log.v("stage 1", "store the pdf in sd card");
//t.append("store the pdf in sd card\n");
Document document = new Document(PageSize.A5, 38, 38, 50, 38);
Log.v("stage 2", "Document Created");
//t.append("Document Created\n");
Rectangle documentRect = document.getPageSize();
try {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
Log.v("Stage 3", "Pdf writer");
// t.append("Pdf writer\n");
document.open();
Log.v("Stage 4", "Document opened");
// t.append("Document opened\n");
for (int i = 0; i < imagesuri.size(); i++)
{
Bitmap bmp = BitmapFactory.decodeFile(imagesuri.get(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 70, stream);
image = Image.getInstance(imagesuri.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());
}
Log.v("Stage 6", "Image path adding");
image.setAbsolutePosition((documentRect.getWidth() - image.getScaledWidth()) / 2, (documentRect.getHeight() - image.getScaledHeight()) / 2);
Log.v("Stage 7", "Image Alignments");
isPdfCreated = true;
image.setBorder(Image.BOX);
image.setBorderWidth(15);
document.add(image);
document.newPage();
}
Log.v("Stage 8", "Image adding");
// t.append("Image adding\n");
document.close();
Log.v("Stage 7", "Document Closed" + path);
// t.append("Document Closed\n");
} catch (Exception e) {
e.printStackTrace();
}
document.close();
imagesuri.clear()
答案 0 :(得分:1)
缩放绝对值时,可以更改图像的纵横比。
例如:如果图像尺寸为600乘800,则宽度为高度的75%。如果要将此图像放在尺寸为400 x 600的页面上,则将此百分比更改为66%。这会使图像变形。
你表现得好像让你感到惊讶(你说图像看起来很奇怪),但这是一种正常现象:改变纵横比将始终以某种方式拉伸图像。例如:如果图像是某人脸部的图像,则脸部会变得更宽(使人看起来更胖)或更高(使人看起来更瘦)。
如果你想避免这种情况,你不应该使用scaleAbsolute()
。您应该使用scaleToFit()
方法替换该方法。 scaleToFit()
方法会缩放图像,但会保留纵横比。
例如:如果我们有一个600乘800的图像,并将其缩放为适合400乘600的矩形,则图像将被缩放到400乘以533.当您将此缩放图像添加到400的矩形时600,你将有67个用户单位的额外空白区域,但如果你想保留纵横比(如果你不想让你的图像看起来很奇怪),那就不应该避免。
将页面大小调整为图像大小会更好一些,但也许您的应用程序需要特定的页面大小。