首页 > 解决方案 > 使用 PDF 库在现有 PDF 文件上绘制小图像

问题描述

我正在开发一个创建 PDF 文件的应用程序,我需要在其上绘制一些小图像。</p>

问题是 PDF 上绘制的图像模糊且质量非常低。我也尝试在不缩放图像的情况下绘制图像,同样的情况发生了,它们是模糊的。

这是我绘制一张图像的片段(我没有使用 iText)

Bitmap calendarBitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.icon_200ppp_calendar);
pdfCanvas.drawBitmap(scaleToFitHeight(calendarBitmap, 16), xCoord, yCoord, null);

public Bitmap scaleToFitHeight(Bitmap b, int height) {
   float factor = height / (float) b.getHeight();
   return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
}

我有 PNG 和 SVG 格式的图像(转换为 VectorDrawable),结果是一样的。

这是PNG: 文件

这是通过 Android Studio 从 SVG 文件生成的 XML:SVG 转换为 VectorDrawable

这些是结果:

模糊图像放大

模糊图像缩小

标签: androidsvgbitmappdf-generationpng

解决方案


您必须将图像的密度设置为 X 因子。例如:

Bitmap bm = new Bitmap(..);
bm.setDensity(bm.getDensity()*4);
// try with different X's: 2, 3, 4, 5, 6.

这种质量损失的发生是因为当您写入 PDF 时,它会自动调整您的位图大小以适应该画布分辨率。此外,如果您调整图像大小,位图,如果您有一个 50X50 的图像并且您想调整为 50X10 的大小,那么您必须小心它会弄乱图像。而是尝试按一个因素调整位图的大小:

bm.getWidth()/4, 
bm.getHeight()/4

等等。


推荐阅读