Android: 如何设置图片大小与文档页面大小相同?

Android: How to set Image size will be same as document page size?

我正在使用 iText 库生成 PDF 文档。在这样的 PDF 中,我每页添加多张图片。

下面是生成PDF的代码。

Document document = new Document();

PdfWriter writer = PdfWriter.getInstance(document, fos);
writer.setPageEvent(new PageWithRectangle());

document.open();

for (int i = 0; i < listSelected.size(); i++) {
    //PdfPTable table = new PdfPTable(1);
    //table.setWidthPercentage(100);
    document.newPage();
    Bitmap bMap = BitmapFactory.decodeFile(listSelected.get(i));
    // Bitmap rotated = Bitmap.createBitmap(bMap, 0, 0,
    // bMap.getWidth(),bMap.getHeight(), null, true);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bMap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    Image image = Image.getInstance(stream.toByteArray());
    image.setBorder(Image.BOX);
    image.setBorderWidth(10); 
    float documentWidth = document.getPageSize().getWidth()
            - document.leftMargin() - document.rightMargin();
    float documentHeight = document.getPageSize().getHeight()
            - document.topMargin() - document.bottomMargin();
    image.scaleToFit(documentWidth, documentHeight);

    Log.e("Document - Image  = Height", document.getPageSize().getHeight()+" - "+image.getScaledHeight());

    float leftMargin =  document.getPageSize().getWidth() - image.getScaledWidth();
    float lMargin = leftMargin / 2 ;

    float topMargin =  document.getPageSize().getHeight() - image.getScaledHeight(); 
    float tMargin = topMargin / 2 ;

    image.setAbsolutePosition(lMargin,tMargin);
    /*PdfPCell cell = new PdfPCell(image);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(cell);*/

    document.add(image);
}
document.close();

Is it possible to set page size same as image size, so top and bottom white field will not display?

这个问题已经在 2013 年 5 月得到回答:Writing image into pdf file in java

How can i set page as LANDSCAPE?

现在您正在创建 A4 格式的文档。

Document document = new Document();

相当于:

Document document = new Document(PageSize.A4, 36, 36, 36, 36);

如果你想创建一个旋转90度的A4页面(让纵向变成横向),那么你可以这样做:

Document document = new Document(PageSize.A4.rotate());

当然,您也可以创建具有所需尺寸的自定义 Rectangle 对象。这就是这个问题的答案:Writing image into pdf file in java