【问题标题】:Android: How to set Image size will be same as document page size?Android:如何设置图像大小与文档页面大小相同?
【发布时间】:2015-02-28 19:52:32
【问题描述】:

我正在使用 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();
  • 是否可以将页面大小设置为与图像大小相同,从而没有白色的顶部和底部边距?
  • 如何将页面设置为横向?

【问题讨论】:

标签: android pdf-generation itext


【解决方案1】:

是否可以将页面大小设置为与图像大小相同,因此不会显示顶部和底部的白色字段?

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

如何将页面设置为横向?

现在您正在创建 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多