PDFBox:将高清图像写入PDF

时间:2017-12-27 14:34:19

标签: android pdfbox

我正在尝试将使用cameraa拍摄的图像转换为A4 PDF

    // Read image width and height
    float imageWidth = bitmap.getWidth();
    float imageHeight = bitmap.getHeight();

    // Read page width and height ignoring the margins
    float pageWidth = PDRectangle.A4.getWidth() - (margin_left_right * 2);
    float pageHeight = PDRectangle.A4.getHeight() - (margin_top_bottom * 2);

    Log.d("Image Resize", String.valueOf(imageWidth) + " x " + String.valueOf(imageHeight));
    Log.d("Image Resize", String.valueOf(pageWidth) + " x " + String.valueOf(pageHeight));

    # Image: 4160.0 x 3120.0
    # Page: 575.27563 x 821.8898

    Log.d("Image Resize", String.valueOf(requiredRatio));
    Log.d("Image Resize", String.valueOf(newImageWidth) + " x " + String.valueOf(newImageHeight));

    # Required ratio: 0.13828741
    # After scaling: 575 x 431

问题是大小为4160 x 3120的图片,在调整为575 x 431后,看起来非常像素化。

PDF如何解决这个问题?在使用4160 x 3120撰写时,是否可以在600 dpicontentStream.drawImage()

question还支持以下事实:如果在不调整大小等于图像高度和宽度的页面上进行调整,OP只能看到15%的图像,应该如何按比例缩小而不会丢失质量?

1 个答案:

答案 0 :(得分:0)

有一个重载的drawImage()方法可以做到这一点

contentStream.drawImage(PDImageXObject, float x, float y)
contentStream.drawImage(PDImageXObject, float x, float y, float height, float width)

通过在contentStream.drawImage()上指定显式宽度和高度,可以实现此目的。例如,如果您想要将图像显示为小4倍但仍保持相同的分辨率,则可以使用

完成
scaleDownRatio = 0.25;
pageSize = PDRectangle.A4;

# this will draw image at bottom left corner
PDImageXObject pageImageXObject = LosslessFactory.createFromImage(document, bitmap);
contentStream.drawImage(pageImageXObject, 0, 0, bitmap.getWidth() * ratio, bitmap.getHeight() * ratio)

# to center it you can use something like
contentStream.drawImage(pageImageXObject, (pageSize.getWidth() - bitmap.getWidth() * ratio) / 2, (pageSize.getHeight() - bitmap.getHeight() * ratio) / 2, bitmap.getWidth() * ratio, bitmap.getHeight() * ratio)