2017-10-09 3 views
1

저는 데이터베이스에서 pdf를 가져 와서 데이터베이스에서 검색해야하는 서명의 이미지로 PDF에 서명하는이 기능을 연구 중입니다. 이 경우 iTextSharp을 사용하고 있지만 어떻게 든 작동하지 않고 데이터베이스에서 PDF가 손상됩니다.Itextsharp PDF가 손상되었습니다

이것은 내가 잘못 여기서 뭐하는 거지 내 컨트롤러

public ActionResult Approve(int? id) 
{ 
    ApplicationUser users = db.Users.Find(User.Identity.GetUserId()); 
    Reports reports = db.Reports.Find(id); 

    if (reports == null || users == null) return View(); 

    byte[] content = reports.Content; 
    byte[] signature = users.Signature; 

    iTextSharp.text.Image sigImg = iTextSharp.text.Image.GetInstance(signature); 

    PdfReader reader = new PdfReader(content); 
    using (MemoryStream ms = new MemoryStream()) 
    { 
     PdfStamper stamper = new PdfStamper(reader, ms); 

     sigImg.SetAbsolutePosition(0f,0f); 

     sigImg.ScalePercent(90.0f); // 100.0f == same size 


     //Give some space after the image 
     sigImg.SpacingAfter = 1f; 
     sigImg.Alignment = Element.ALIGN_BOTTOM; 

     PdfContentByte over = stamper.GetOverContent(1); 

     over.AddImage(sigImg); 

     reports.Content = ms.ToArray(); 
     content = reports.Content; 

     ms.Flush(); 
     db.SaveChanges(); 
     if(stamper!= null) 
      stamper.Close(); 
     if(reader!= null) 
      reader.Close(); 

     return File(content, "application/pdf"); 

     // Clean up 

    } 
} 

의 코드? 아직 완전한 스탬프 PDF를 포함하지 않는 MemoryStream을 의미 PdfStamper

if(stamper!= null) 
    stamper.Close(); 

을 닫기 전에

답변

1

당신은 MemoryStream

reports.Content = ms.ToArray(); 

의 내용을 검색 할 수 있습니다.

따라서 명령의 순서를 변경하십시오. 특히 ms에서 바이트를 검색하기 전에 stamper을 닫으십시오.

제쳐두고 : stamper!= null을 확인하는 이유는 무엇입니까? 분명히 null 일 수는 없습니다 ...

+0

감사합니다. ms.flush()가하는 일을 알려주시겠습니까? –

+0

'MemoryStream'의'flush' ... 본질적으로 NOP ... no-operation 호출이라고 가정합니다. 콘텐츠가 대상 매체에 기록되기 전에 내부 버퍼가있는 모든 스트림에서 '플러시'가 가능하지만 RAM 메모리가 이미 대상 매체 인 'MemoryStream'에서는 그렇지 않습니다. – mkl

+0

감사합니다 !! 그것은 일했다 :) –