2011-12-28 2 views
3

iTextSharpText를 사용하여 PDF를 작성 중입니다.iTextSharp - 텍스트 오버랩 이미지

동적 텍스트를 이미지 위에 추가하라는 메시지가 나타납니다. 나는 이미이 포럼과 다른 웹 사이트에서 발견 한 몇 가지 예제를 시도했지만,이 권리를 얻을 수없는 것처럼 보였습니다.

나는이 스레드 (iTextSharp Adding Text plus Barcode in a single cell?)를 따라 갔고 두 답을 모두 시도했다.

먼저 나는 시도 :

  var img_operacao = Image.GetInstance(String.Format("{0}{1}", Settings.Default.SiteRootURL, "/PublishingImages/PDF_operacao.png")); 
      img_operacao.ScaleToFit(150, 41); 

      img_operacao.Alignment = Image.UNDERLYING; 

      var ph0 = new Phrase(title0, pageHeader); 
      var cell = new PdfPCell(); 

      cell.AddElement(ph0); 
      cell.AddElement(new Phrase(new Chunk(img_operacao, 0, 0))); 
      table.AddCell(cell); 

그리고이있어 : http://imageshack.us/photo/my-images/515/25265113.png/

내 두 번째 시도 :

  var img_operacao = Image.GetInstance(String.Format("{0}{1}", Settings.Default.SiteRootURL, "/PublishingImages/PDF_operacao.png")); 
      img_operacao.ScaleToFit(150, 41); 

      img_operacao.Alignment = Image.UNDERLYING; 

      var cell = new PdfPCell 
         { 
          Border = Rectangle.NO_BORDER, 
          PaddingTop = 0, 
          PaddingBottom = 0, 
          HorizontalAlignment = Element.ALIGN_CENTER, 
          VerticalAlignment = Element.ALIGN_MIDDLE 
         }; 

      var ph0 = new Phrase(); 
      ph0.Add(new Chunk(title0, pageHeader)); 
      ph0.Add(new Chunk(img_operacao, 0, 0, true)); 

      cell.AddElement(ph0); 
      table.AddCell(cell); 

을 그리고있어 : http://imageshack.us/photo/my-images/688/89424619.png/

내가했습니다 해본 덩어리, 단락 등 여러 가지 변형이 있지만 이미지 위에 텍스트를 가져올 수 없습니다 !!!

나를 도울 수있는 사람이 있다면 정말 감사하겠습니다. 당신이 PdfPCell에 배경 이미지를 추가 할 것 같은 지금 붙어있어 ...

덕분에 많은

폴라

답변

3

것 같습니다. 권장되는 접근 방식은 IPdfPCellEvent 인터페이스를 구현하는 것입니다. 문서화 된 것처럼 IPdfPCellEvent을 구현하는 사용자 정의 클래스를 작성할 때 하나의 메소드 CellLayout 만 작성하면됩니다. 코드에서 사용자가 웹 환경에있을 것 같습니다, 그래서이 간단한 예를 들어 HTTP 처리기 (.ASHX)을 따라하기 쉽게해야합니다 :

<%@ WebHandler Language="C#" Class="cellEvent" %> 
using System; 
using System.Web; 
using iTextSharp.text; 
using iTextSharp.text.pdf; 

public class cellEvent : IHttpHandler { 
    public void ProcessRequest (HttpContext context) { 
    HttpServerUtility Server = context.Server; 
    HttpResponse Response = context.Response; 
    Response.ContentType = "application/pdf"; 
    // replace with your image 
    string imagePath = Server.MapPath("./Image1.png"); 
    Image image = Image.GetInstance(imagePath); 
    using (Document document = new Document()) { 
     PdfWriter.GetInstance(document, Response.OutputStream);  
     document.Open(); 
     PdfPTable table = new PdfPTable(2); 
     for (int i = 1; i < 10; ++i) { 
     PdfPCell cell = new PdfPCell(new PdfPCell()); 
     // add the text 
     cell.Phrase = new Phrase(string.Format("CELL 1, ROW {0}", i)); 
     // your class that adds the background image 
     cell.CellEvent = new TestCellEvent() { 
      CellImage = image 
     }; 
     table.AddCell(cell); 
     // add __new__ cell; CellEvent no longer applies; 
     // (no background image) 
     table.AddCell(new PdfPCell(new Phrase(
      string.Format("CELL 2, ROW {0}", i 
     )))); 
     } 
     document.Add(table); 
    } 
    } 
    public bool IsReusable { get { return false; } } 

// custom class to implement a cell background image 
    class TestCellEvent : IPdfPCellEvent { 
    public Image CellImage; 
    public void CellLayout(
     PdfPCell cell, Rectangle position, PdfContentByte[] canvases 
    ) 
    { 
     PdfContentByte cb = canvases[PdfPTable.BACKGROUNDCANVAS]; 
     // scale image to the cell's __full__ height 
     CellImage.ScaleAbsoluteHeight(cell.Height); 
     // scale image to the cell's __full__ width 
     CellImage.ScaleAbsoluteWidth(cell.Width); 
     // you must also explcitly set the image position! 
     CellImage.SetAbsolutePosition(position.Left, position.Bottom); 
     // add the image to the cell 
     cb.AddImage(CellImage); 
    } 
    } 
} 

이 희망 인라인 주석이 이해. Image 개체가 번 인스턴스화 된 것을 알 수 있습니다. 이미지 데이터가 PDF에 한 번만 추가되므로 동일한 이미지를 다시 사용하는 경우 이렇게하면 파일 크기가 크게 줄어들고 각 셀에 대해 Image이 반복적으로 인스턴스화됩니다.

행운을 비네.

+0

이미지가 천 단어의 가치가 있기 때문에 http://imageshack.us/photo/my-images/806/54794843.png/ 이제 텍스트를 정렬해야합니다. 정말 고맙습니다!!! 너는 내 하루를 진정으로 구했다 !! –

+0

WOW, 위대한 책임자 ... 그것은 나에게도 매우 유용합니다 !!! – AndreaNobili

0

내 자신의 필요에 따라이 문제를 해결하는 동안 문제가 발생했습니다. Table 객체를 만들고 여러 열을 정의했습니다. 첫 번째 열은 최소 너비로 설정되고 나머지는 양식에 배치되는 텍스트의 위치에 적절한 너비가 설정됩니다. 나는 약 1 "x7"의 이미지를 생성 중이다. 이미지가 표 행의 첫 번째 열에있는 셀에 추가되었습니다. SetAbsoluteHeight 및 SetAbsoluteWidth에 의해 설정된 크기가 열의 크기를 훨씬 초과하므로 이미지 종류가 나머지 행 열에/아래로 채워집니다. 이미지 위에 겹쳐지는 텍스트의 경우, 텍스트 폭을 조정하기 위해 열 너비, Chunk.Newlines 및 단락 SetLeading 추가 (행 간격 늘리기)가 사용되었습니다.

+0

StackOverflow에 오신 것을 환영합니다. 도움을 주셔서 감사합니다.필자의 대답은 가독성을 높이기 위해 서식을 다시 사용하고 표현의 이점을 얻을 수 있습니다. 도움이되는 아이디어를 얻으려면 [둘러보기]를 가져 가세요. – Yunnosch