【问题标题】:Create PDF from Image - android using ItextPdf从图像创建 PDF - android 使用 ItextPdf
【发布时间】:2017-11-28 13:41:06
【问题描述】:

我有一个包含以下数据的活动:

我正在使用以下代码从此视图生成 pdf:

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, stream);
Image image = Image.getInstance(stream.toByteArray());
image.setAbsolutePosition(0, 0);

Document document = new Document(image);
PdfWriter.getInstance(document, new FileOutputStream(filePath));
document.open();
document.add(image);
document.close();

但如果我在 recyclerview 中有超过 20 行,我会收到此错误:

exceptionconverter: com.itextpdf.text.documentexception: the page size must be smaller than 14400 by 14400. it's 1080.0 by 25288.0

这是因为图像的高度超过了最大页面大小 14400。我得到了那部分。

但是如果图像大小超过页面大小,我想知道如何将图像分成两页。

我尝试了以下代码:

        float width = image.getScaledWidth();
        float height = image.getScaledHeight();
        Rectangle page = new Rectangle(width, height / 2);

        Document document = new Document(page);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
        document.open();
        PdfContentByte canvas = writer.getDirectContentUnder();
        canvas.addImage(image, width, 0, 0, height, 0, -height / 2);
        document.newPage();
        canvas.addImage(image, width, 0, 0, height, 0, 0);
        document.newPage();
        canvas.addImage(image, width, 0, 0, height, -width / 2, - height / 2);
        document.newPage();
        canvas.addImage(image, width, 0, 0, height, -width / 2, 0);
        document.close();

但仍然无法使其正常工作。有人能指出我正确的方向吗?

【问题讨论】:

    标签: android bitmap android-recyclerview itext


    【解决方案1】:

    这可能有效,也可能无效。试一试。 使用以下方法调整位图大小

    public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = image.getWidth();
        int height = image.getHeight();
    
        float bitmapRatio = (float)width / (float) height;
        if (bitmapRatio > 1) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        }
        return Bitmap.createScaledBitmap(image, width, height, true);
    }
    

    【讨论】:

    • 嘿@kcg,谢谢。我试过这个,它最多可以处理 50 行。非常感谢:)
    猜你喜欢
    • 2012-07-17
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    相关资源
    最近更新 更多