2014-10-22 2 views
0

을위한, 그래서 나는 다음과 같이 내 PDF 파일을 생성 관리 :머리글과 바닥 글 내가 iTextSharp를 사용하여 PDF 파일을 생성하기 위해 노력하고있어 각 PDF 페이지

:

enter image description here

이 내 코드입니다 내 컨트롤러에서

나는 문자열 (JSON 형식) < ---- 문자열 screendata에서 데이터를 얻을 :

[HttpPost] 
public void GenaraleExportPDF(String screendata,String monTitre,String file) 
{ 
    ExportManager export = new ExportManager(); 

    String MapPath = Server.MapPath("~/Content/"); 

    string filepath = MapPath + file; 

    //Appel Methodes Export Manager pour generer PDF 
    export.GenererPdfJSON(screendata, monTitre, MapPath, file); 

    //Ajout Response : transmitfile self buffers 
    Response.Buffer = false; 
    Response.Clear(); 
    Response.ClearContent(); 
    Response.ClearHeaders(); 
    Response.ContentType = "application/pdf"; 
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file); 
    Response.TransmitFile(filepath); 
    Response.End(); 
} 

기타 기능 :

테이블의 헤더와 데이터를 생성 -> AjoutHeaderDataTablePdf() :

public PdfPTable AjoutHeaderDataTablePdf(object[] tableObjet, PdfPTable table, iTextSharp.text.Font fntTableFontHdr) 
{ 
    table.HeaderRows = 2; 
    table.HorizontalAlignment = 0; 
    table.TotalWidth = 500f; 
    table.LockedWidth = true; 
    float[] widths = new float[] { 60f, 40f, 60f, 40f, 60f, 80f}; 

    table.SetWidths(widths); 

    //Font Color 
    BaseColor ForeGroundmyColorHeader = WebColors.GetRGBColor("#FFFFFF"); 
    BaseColor ForeGroundmyColorOthers = WebColors.GetRGBColor("#232323"); 
    BaseColor BackGroundmyColor = WebColors.GetRGBColor("#32A3E0"); 

    BaseColor BackGroundmyColorOther1 = WebColors.GetRGBColor("#D8E4FD"); 
    BaseColor BackGroundmyColorOther2 = WebColors.GetRGBColor("#FFFFFF"); 


    var FontHeader = FontFactory.GetFont("Times New Roman", 9, ForeGroundmyColorHeader); 

    var FontOthers = FontFactory.GetFont("Times New Roman", 8, ForeGroundmyColorOthers); 

    var borderColor = WebColors.GetRGBColor("#E4E4E4"); 
    var borderWidth =0f; 

    /***Begin Header***/ 


    /******Fin Header******/ 
    // Ajout Headers columnsName 

    foreach (var o in tableObjet) 
    { 
     Dictionary<string, object> dictionary = (Dictionary<string, object>)o; 


     foreach (KeyValuePair<string, object> pair in dictionary) 
     { 


      PdfPCell CellOneHdr2 = new PdfPCell(new Phrase(pair.Key, FontHeader)); 

      CellOneHdr2.BackgroundColor = BackGroundmyColor; 



      CellOneHdr2.BorderColorLeft = borderColor; 
      CellOneHdr2.BorderColorRight = borderColor; 
      CellOneHdr2.BorderColorTop = borderColor; 
      CellOneHdr2.BorderColorBottom = borderColor; 
      CellOneHdr2.BorderWidthLeft = borderWidth; 
      CellOneHdr2.BorderWidthRight = borderWidth; 
      CellOneHdr2.BorderWidthTop = borderWidth; 
      CellOneHdr2.BorderWidthBottom = borderWidth; 

      CellOneHdr2.PaddingTop = 6f; 
      CellOneHdr2.PaddingLeft = 5f; 

      CellOneHdr2.FixedHeight = 26f; 
      table.AddCell(CellOneHdr2); 

     } 
     break; 
    } 

    //Ajout de contenu de cellules 
    int count = 0; 
    BaseColor BackGroundmyColorOtherX; 
    for (int ii = 0; ii < 5; ii++) 

    { 

     foreach (var o in tableObjet) 
     { 
      Dictionary<string, object> dictionary = (Dictionary<string, object>)o; 

      if (count % 2 == 0) 
       BackGroundmyColorOtherX = BackGroundmyColorOther1; 
      else 
       BackGroundmyColorOtherX = BackGroundmyColorOther2; 

      foreach (KeyValuePair<string, object> pair in dictionary) 
      { 
       PdfPCell CellOneHdr2 = new PdfPCell(new Phrase(pair.Value.ToString(), FontOthers)); 

       CellOneHdr2.BackgroundColor = BackGroundmyColorOtherX; 
       CellOneHdr2.FixedHeight = 23f; 

       CellOneHdr2.BorderColorLeft = borderColor; 
       CellOneHdr2.BorderColorRight = borderColor; 
       CellOneHdr2.BorderColorTop = borderColor; 
       CellOneHdr2.BorderColorBottom = borderColor; 
       CellOneHdr2.BorderWidthLeft = borderWidth; 
       CellOneHdr2.BorderWidthRight = borderWidth; 
       CellOneHdr2.BorderWidthTop = borderWidth; 
       CellOneHdr2.BorderWidthBottom = borderWidth; 

       CellOneHdr2.PaddingTop = 6f; 
       CellOneHdr2.PaddingLeft = 5f; 

       table.AddCell(CellOneHdr2); 

      } 
      count++; 

     } 
    } 
    table.HorizontalAlignment = 1; 
    return table; 
} 

테이블의 제목 생성 -> TitreTablePdfCentre() :

public PdfPTable TitreTablePdfCentre(int NbrCol, String Titre) 
{ 
    BaseColor ForeGroundmyColorHeader = WebColors.GetRGBColor("#FFFFFF"); 
    BaseColor BackGroundmyColorHeader = WebColors.GetRGBColor("#32A3E0"); 

    var borderColor = WebColors.GetRGBColor("#E4E4E4"); 
    var borderWidth = 0.1f; 

    var FontHeader = FontFactory.GetFont("Times New Roman", 12, ForeGroundmyColorHeader); 

    //Creer PdfTable contenant NbrCol colonnes 
    PdfPTable table = new PdfPTable(NbrCol); 
    table.HeaderRows = 2; 
    //Ajouter un Titre en haut du fichier 

    PdfPCell cell = new PdfPCell(new Phrase(Titre, FontHeader)); 
    // fusionner les NbrCol celllules en une seul cellule 
    cell.Colspan = NbrCol; 

    //Metre au centre : 0=Left, 1=Centre, 2=Right 
    cell.HorizontalAlignment = 1; 

    // Ajout La cellule à Pdftable 

    /**Style**/ 

    cell.FixedHeight = 30f; 
    cell.PaddingTop = 6f; 
    cell.BackgroundColor = BackGroundmyColorHeader; 


    cell.BorderColorLeft = borderColor; 
    cell.BorderColorRight = borderColor; 
    cell.BorderColorTop = borderColor; 
    cell.BorderColorBottom = borderColor; 
    cell.BorderWidthLeft = borderWidth; 
    cell.BorderWidthRight = borderWidth; 
    cell.BorderWidthTop = borderWidth; 
    cell.BorderWidthBottom = borderWidth; 

    table.AddCell(cell); 
    table.HorizontalAlignment = 1; 
    return table; 
} 

는 JSON 데이터를 생성을 -> GenererPdfJSON () :

public void GenererPdfJSON(String screendata, String Titre, String MapPath, String file) 
{ 
    //Convertir String JSON to Table object[] 
    object[] tableObjet = TbaleJSON(screendata); 

    //Retourne Nbr Lignes Object 
    int nbrlignes = NbrLignesTableJSON(tableObjet); 

    //Calcul de nombre de colonnes de tableObjet 
    int nbrcol = NbrColonnesTableJSON(tableObjet); 

    //Creer PdfTable contenant nbrcol colonnes en heut de la feuille 
    PdfPTable table = TitreTablePdfCentre(nbrcol, Titre); 
    table.HeaderRows = 2; 
    Document document = new Document(); 

    //Ajout de qlq Style 
    iTextSharp.text.Font fntTableFontHdr = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK); 

    //Lien Physique Server.MapPath("~/Content/") + fichierpdf.pdf 
    string filepath = MapPath + file; 

    //Ecrire les données dans le fichier 
    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filepath, FileMode.Create)); 
    //Ouvrir le document 
    document.Open(); 

    /**pagination***/ 
    Paragraph para = new Paragraph("Hello world. Checking Header Footer", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 22)); 

    para.Alignment = Element.ALIGN_CENTER; 

    document.Add(para); 


    //*****************// 
    //Ajouter le noms colonnes et les donnees dans les cellules avec Style fntTableFontHdr 
    table = AjoutHeaderDataTablePdf(tableObjet, table, fntTableFontHdr); 


    document.Add(table); 
    document.Close(); 
} 

내 문제는 페이지 번호, 제목 등을 표시하기 위해 각 페이지마다 머리글과 바닥 글을 만들고 싶다는 것입니다. ..

+0

도움말 Plz !! –

+1

이 Java 예제를 살펴보십시오. http://itextpdf.com/examples/iia.php?id=118. C#으로 변환하는 것은 간단합니다. –

+0

솔루션에 대한 감사하지만, 나는 문서의 모든 페이지에 대해 머리말과 꼬리말을 만들고 싶다. 나는 머리말/꼬리말을 의미하지 않는다. –

답변

0

PdfPageEventHelper를 재정 의하여 바닥 글과 머리글을 추가 할 수 있습니다. 다음 코드는 PdfWriters Page Event에 클래스의 인스턴스를 추가하여 현재 문서와 연결해야합니다. writer.PageEvent = new PageEventHelper();. 문서가 열려지기 전에이를 배치해야합니다.

document.NewPage()이 호출되면 OnEndPage가 호출되어 지정된 위치에 현재 페이지 번호가 추가됩니다. "of Y"를 추가하려면 정확한 페이지 수를 확보하기 위해 문서가 닫힐 때까지 기다려야합니다. PdfPageEvenHelper 클래스에

public class PageEventHelper : PdfPageEventHelper 
{ 
    PdfContentByte cb; 
    PdfTemplate template; 


    public override void OnOpenDocument(PdfWriter writer, Document document) 
    { 
     cb = writer.DirectContent; 
     template = cb.CreateTemplate(width, height); 
    } 

    public override void OnEndPage(PdfWriter writer, Document document) 
    { 
     base.OnEndPage(writer, document); 

     int pageN = writer.PageNumber; 
     String text = "Page " + pageN.ToString() + " of "; 

     Rectangle pageSize = document.PageSize; 

     cb.BeginText(); 
     cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12F); 
     cb.SetTextMatrix(Width, Height); 
     cb.ShowText(text); 

     cb.EndText(); 
     //Add the template to each page so we can add the total page number later 
     cb.AddTemplate(template, Width, Height); 
    } 

    public override void OnCloseDocument(PdfWriter writer, Document document) 
    { 
     base.OnCloseDocument(writer, document); 

     template.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12F); 
     template.BeginText(); 
     template.SetTextMatrix(0, 0); 
     //Add the final page number. 
     template.ShowText("" + (writer.PageNumber - 1)); 
     //This will write the number on all templates on all pages 
     template.EndText(); 
    } 
} 

자세한 내용은 http://api.itextpdf.com/itext/com/itextpdf/text/pdf/PdfPageEventHelper.html에서 찾을 수 있습니다. 이것은 Java로 작성되었지만 C#에서 동일한 코드를 사용하기가 쉽습니다.

이 원칙은 다른 템플릿을 사용하여 바닥 글과 머리글을 추가하는 데 사용할 수 있습니다.