我正在尝试将 ScrollView
转换为 Bitmap
,但生成的图像仅包含部分内容。
这就是我创建 JPEG 图像的方法:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, stream);
byte[] img = stream.toByteArray();
我尝试通过以下方式创建位图
对象:
尝试 1:
int totalWidth=((ScrollView)contentView).getChildAt(0).getWidth();
int totalHeight=((ScrollView)contentView).getChildAt(0).getHeight();
Bitmap bitmap = Bitmap.createBitmap(totalWidth, totalHeight, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
contentView.layout(contentView.getLeft(), contentView.getTop(), contentView.getRight(), contentView.getBottom());
contentView.draw(c);
尝试 2:
Bitmap bitmap = Bitmap.createBitmap(contentView.getWidth(), contentView.getHeight(), Bitmap.Config.ARGB_8888);
contentView.layout(contentView.getLeft(), contentView.getTop(), contentView.getRight(), contentView.getBottom());
contentView.draw(c);
尝试 3:
Bitmap bitmap = Bitmap.createBitmap(contentView.getMeasuredWidth(), contentView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
contentView.layout(contentView.getLeft(), contentView.getTop(), contentView.getRight(), contentView.getBottom());
contentView.draw(c);
最终,我将图像添加到 PDF,如下所示:
public boolean saveReportAsPdf(Bitmap bitmap) {
try {
Image image;
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Reports";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
Log.d("PDFCreator", "PDF Path: " + path);
File file = new File(dir, "audit.pdf");
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, stream);
byte[] imageimg = Image.getInstance(stream.toByteArray());
image.setAlignment(Image.MIDDLE);
document.add(image);
document.close();
} catch (Exception i1) {
i1.printStackTrace();
}
return true;
}
这会产生以下输出:
这仅显示第 7 行之前的图像。如下所示,还有第 8 行到第 13 行。
第 8 行到第 13 行缺失。
最佳答案
问题不在于你的形象。根据您在聊天中提供的反馈,图像已完成。但是,您的图像比 A4 页面大,并且您使用 A4 尺寸的页面创建 PDF 文档。这意味着图像不适合页面。
您应该创建一个 PDF,其页面大小与图像相同。这样做是这样的:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, stream);
image = Image.getInstance(stream.toByteArray());
image.setAbsolutePosition(0, 0);
Document document = new Document(image);
PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
document.add(image);
document.close();
请注意以下行:
Document document = new Document(image);
这会导致 PDF 文档的页面与图像的尺寸相同。当我们将图像添加到位置 (0, 0)
时,它将完全适合页面。
P.S.:您正在使用 Java 的 iText 版本。如果您在 Android 上工作,则应该使用 Android 端口。 Android 端口名为 iTextG .
关于Android-ScrollView 到位图转换中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29203970/