2017-10-06 82 views
0

我正在使用文件代码以附加模式打开pdf文件。如何使用itextpdf将图像附加到android中的现有pdf文件

String FILE = ROOT + "/PDF/" + "DemoLogix.pdf"; 
PdfWriter.getInstance(document, new FileOutputStream(FILE, true)); 
document.open(); 

但是,当我使用下面的代码

  PdfPTable table5 = new PdfPTable(new float[]{1}); 
      Bitmap bitmap = BitmapFactory.decodeFile(path); //path is where image is stored. 
      ByteArrayOutputStream stream1 = new ByteArrayOutputStream(); 
      bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream1); 
      Image image1 = Image.getInstance(stream1.toByteArray()); 
      PdfPCell cell3 = new PdfPCell(image1, false); 
      cell3.setPadding(30); 
      cell3.setBorderWidth(0.0f); 
      image1.scaleToFit(100, 500); 
      image1.setAlignment(image1.ALIGN_RIGHT); 
      table5.addCell(cell3); 
      document.add(table5); 
      document.close(); 

它仍然没有作品加入我的形象。相反,它会覆盖以前的文本。请有人帮助我。

回答

1

加载所需的PDF修改

PdfReader reader = new PdfReader(srcPdf); 
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destPdf)); 
PdfContentByte content = stamper.getOverContent(1); 

然后,加载图像(的ImagePath对于IMAGEM文件的完整路径):

Image image = Image.getInstance(imagePath); 

// scale the image to 50px height 
image.scaleAbsoluteHeight(50); 
image.scaleAbsoluteWidth((image.getWidth() * 50)/image.getHeight()); 

由于图像尺寸大,它的缩放到50像素高度,然后将其添加到PDF。

然后将页面坐标设置在我们想要的位置。要知道,对于Y轴的0值是在页面的底部,而不是顶部:

image.setAbsolutePosition(70, 140); 

所有你现在需要做的就是把它添加到页面引用,并关闭压模:

content.addImage(image); 
stamper.close(); 

就是这样!

+0

此答案正在工作。你能提出任何可以在内容结尾添加图像的方法吗? –

相关问题