2017-10-06 79 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

此答案正在工作。你能提出任何可以在內容結尾添加圖像的方法嗎? –

相關問題