Android应用拍摄图片转PDF实现咨询(附现有代码)
如何在Android中将拍摄的图片添加到PDF文档中
嘿,看起来你已经搞定了PDF里添加文本组件的部分,现在就差把拍摄的图片整合进去了!我给你两种靠谱的解决方案,一种是基于你现在用的Android原生PdfDocument的修改方案,另一种是用iText库的实现,都能完美解决你的问题。
一、基于Android原生PdfDocument的解决方案
你现有代码里已经调用了canvas.drawBitmap(),但大概率是图片没有正确加载或者尺寸适配出了问题。我帮你完善这部分逻辑:
1. 正确加载并压缩拍摄的图片
首先要把你存在指定目录的照片文件转换成Bitmap,而且要避免大图片导致内存溢出:
// 替换成你实际的照片文件路径 String photoPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/VIEW REPORT/Photos/你的照片文件名.jpg"; Bitmap bitmap = BitmapFactory.decodeFile(photoPath); if (bitmap != null) { // 压缩图片适配PDF页面宽度(和你设置的500页面宽度匹配,留50边距) int targetWidth = 450; int targetHeight = (int) (bitmap.getHeight() * ((float) targetWidth / bitmap.getWidth())); Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, true); }
2. 修改你的PDF生成代码
把图片绘制逻辑整合到你现有代码里,注意设置合适的位置避免覆盖文本:
public void gerarPDF(View view) { PdfDocument documentoPDF = new PdfDocument(); PdfDocument.PageInfo detalhesDaPagina = new PdfDocument.PageInfo.Builder(500, 600, 1).create(); PdfDocument.Page novaPagina = documentoPDF.startPage(detalhesDaPagina); Canvas canvas = novaPagina.getCanvas(); Paint corDoTexto = new Paint(); corDoTexto.setColor(Color.BLACK); // 保留你原有的文本绘制代码 canvas.drawText(textView6.getText().toString(), 50, 100, corDoTexto); canvas.drawText(textView.getText().toString(), 50, 130, corDoTexto); canvas.drawText(etCliente.getText().toString(), 105, 130, corDoTexto); canvas.drawText(textView2.getText().toString(), 50, 150, corDoTexto); canvas.drawText(etPostes.getText().toString(), 105, 150, corDoTexto); canvas.drawText(textView3.getText().toString(), 50, 170, corDoTexto); canvas.drawText(etObservacao.getText().toString(), 145, 170, corDoTexto); // 加载并绘制图片 String photoPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/VIEW REPORT/Photos/你的照片文件名.jpg"; Bitmap bitmap = BitmapFactory.decodeFile(photoPath); if (bitmap != null) { int targetWidth = 450; int targetHeight = (int) (bitmap.getHeight() * ((float) targetWidth / bitmap.getWidth())); Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, true); // 把图片放在文本下方,设置x=25(留边距),y=200(避开文本区域) canvas.drawBitmap(scaledBitmap, 25, 200, new Paint()); // 回收Bitmap避免内存泄漏 bitmap.recycle(); scaledBitmap.recycle(); } else { // 图片加载失败时的提示 canvas.drawText("无法加载照片", 50, 200, corDoTexto); } documentoPDF.finishPage(novaPagina); // 保留你原有的PDF保存代码 SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyhhmmss"); String pdfName = "pdf" + sdf.format(Calendar.getInstance().getTime()) + ".pdf"; String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/VIEW REPORT/Pdf"; File dir = new File(path); if(!dir.exists()) dir.mkdirs(); File pdffile = new File(dir, pdfName); if( documentoPDF != null ){ try { OutputStream out = new FileOutputStream(pdffile); if( out != null ){ documentoPDF.writeTo(out); documentoPDF.close(); out.close(); Toast.makeText(this, "PDF GERADO COM SUCESSO", Toast.LENGTH_LONG).show(); } } catch (IOException e) { e.printStackTrace(); Toast.makeText(this, "FALHA AO GERAR PDF: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } }
二、基于iText库的解决方案
如果你需要更灵活的布局(比如多图片、复杂排版),iText是更好的选择,实现起来也更简洁:
1. 添加iText依赖
在你的Module级别build.gradle中添加依赖:
implementation 'com.itextpdf:itext7-core:7.2.5' implementation 'com.itextpdf:itext7-layout:7.2.5'
2. 实现PDF生成代码
public void gerarPDFComItext(View view) { // 设置PDF保存路径 String pdfPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/VIEW REPORT/Pdf/pdf_" + System.currentTimeMillis() + ".pdf"; File pdfFile = new File(pdfPath); try { // 初始化PDF文档 PdfWriter writer = new PdfWriter(pdfFile); PdfDocument pdfDoc = new PdfDocument(writer); Document document = new Document(pdfDoc, PageSize.A5); // 用A5尺寸接近你原来的500x600 // 添加文本内容 document.add(new Paragraph(textView6.getText().toString()).setMarginBottom(5)); Paragraph clientePara = new Paragraph(textView.getText().toString()) .add(new Text(etCliente.getText().toString()).setFontSize(12)); document.add(clientePara.setMarginBottom(5)); Paragraph postesPara = new Paragraph(textView2.getText().toString()) .add(new Text(etPostes.getText().toString()).setFontSize(12)); document.add(postesPara.setMarginBottom(5)); Paragraph obsPara = new Paragraph(textView3.getText().toString()) .add(new Text(etObservacao.getText().toString()).setFontSize(12)); document.add(obsPara.setMarginBottom(20)); // 添加图片 String photoPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/VIEW REPORT/Photos/你的照片文件名.jpg"; ImageData imageData = ImageDataFactory.create(photoPath); Image image = new Image(imageData); // 设置图片宽度适配页面,自动按比例调整高度 float pageWidth = document.getPageEffectiveArea(PageSize.A5).getWidth(); image.setWidth(pageWidth - 40); // 左右各留20边距 image.setAutoScaleHeight(true); document.add(image); // 关闭文档 document.close(); Toast.makeText(this, "PDF GERADO COM SUCESSO", Toast.LENGTH_LONG).show(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(this, "FALHA AO GERAR PDF: " + e.getMessage(), Toast.LENGTH_LONG).show(); } }
注意事项
- 确保你已经申请了读写外部存储的权限(Android 10+建议使用应用私有目录,或者申请
MANAGE_EXTERNAL_STORAGE权限;Android 13+还需要READ_MEDIA_IMAGES权限读取照片)。
内容的提问来源于stack exchange,提问作者Eduardo Guidugli
相关产品推荐
相关产品推荐

