2011-02-04 1 views
6

Я пытаюсь добавить горизонтальную линию на вершине, чтобы разделить текст заголовка от фактических значений в моем PDF-файле: enter image description hereкод не рисуя горизонтальную линию в моем PDF

Вот мой код:

public class StudentList 
{ 
    public void PrintStudentList(int gradeParaleloID) 
    { 
     StudentRepository repo = new StudentRepository(); 
     var students = repo.FindAllStudents() 
          .Where(s => s.IDGradeParalelo == gradeParaleloID); 

     try 
     { 
      Document document = new Document(PageSize.LETTER); 

      PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\Alumnos.pdf", FileMode.Create)); 
      document.Open(); 

      PdfContentByte cb = writer.DirectContent; 
      cb.SetLineWidth(2.0f); // Make a bit thicker than 1.0 default 
      cb.SetGrayStroke(0.95f); // 1 = black, 0 = white 
      cb.MoveTo(20, 30); 
      cb.LineTo(400, 30); 
      cb.Stroke(); 

      PdfPTable table = new PdfPTable(3);     
      float[] widths = new float[] { 0.6f, 0.75f, 2f }; 
      table.SetWidths(widths); 
      PdfPCell numeroCell = new PdfPCell(new Phrase("Nro.")); 
      numeroCell.Border = 0; 
      numeroCell.HorizontalAlignment = 0; 
      table.AddCell(numeroCell); 

      PdfPCell codigoCell = new PdfPCell(new Phrase("RUDE")); 
      codigoCell.Border = 0; 
      codigoCell.HorizontalAlignment = 0; 
      table.AddCell(codigoCell); 

      PdfPCell nombreCell = new PdfPCell(new Phrase("Apellidos y Nombres")); 
      nombreCell.Border = 0; 
      nombreCell.HorizontalAlignment = 0; 
      table.AddCell(nombreCell); 

      int c = 1; 
      foreach (var student in students) 
      { 
       PdfPCell cell = new PdfPCell(new Phrase(c.ToString())); 
       cell.Border = 0; 
       cell.HorizontalAlignment = 0; 
       table.AddCell(cell); 

       cell = new PdfPCell(new Phrase(student.Rude.ToString())); 
       cell.Border = 0; 
       cell.HorizontalAlignment = 0; 
       table.AddCell(cell); 

       cell = new PdfPCell(new Phrase(student.LastNameFather + " " + student.LastNameMother + " " + student.Name)); 
       cell.Border = 0; 
       cell.HorizontalAlignment = 0; 
       table.AddCell(cell); 
       c++; 
      } 
      table.SpacingBefore = 20f; 
      table.SpacingAfter = 30f; 

      document.Add(table); 
      document.Close(); 
     } 
     catch (DocumentException de) 
     { 
      Debug.WriteLine(de.Message); 
     } 
     catch (IOException ioe) 
     { 
      Debug.WriteLine(ioe.Message); 
     } 

    } 
} 

Я не понимаю, почему cb.Stroke() не работает. Какие-либо предложения?

+0

FYI: SetGrayStroke, кажется, на самом деле быть 0 = черными , 1 = белый. –

ответ

12

Рисунок с классом PdfContentByte iTextSharp может быть немного запутанным. Высота фактически относительно дна, а не вершины. Таким образом, верхняя часть страницы не является 0f, а на самом деле является document.Top, которая на вашей странице размером PageSize.LETTER равна 726f. Так что если вы хотите, чтобы нарисовать вашу линию 30 единиц из верхней, попробуйте:

cb.MoveTo(20, document.Top - 30f); 
cb.LineTo(400, document.Top - 30f); 

Просто любопытно - почему это трудный путь, вместо того, чтобы использовать границы таблицы? (Я заметил, что вы установили свои границы в 0). Пытаться проложить линии вручную - самая большая боль. Если вы когда-либо перемещаете содержимое в своем PDF-файле, вам нужно будет убедиться, что ваши измерения все еще работают.

Попробуйте это:

numeroCell.Border = 0; 
numeroCell.BorderColorBottom = new BaseColor(System.Drawing.Color.Black); 
numeroCell.BorderWidthBottom = 1f; 

codigoCell.Border = 0; 
codigoCell.BorderColorBottom = new BaseColor(System.Drawing.Color.Black); 
codigoCell.BorderWidthBottom = 1f; 

nombreCell.Border = 0; 
nombreCell.BorderColorBottom = new BaseColor(System.Drawing.Color.Black); 
nombreCell.BorderWidthBottom = 1f; 

Это должно дать вам хорошую Сплошную черную линию под вашу строкой заголовка, никаких измерений не требуются:

Table border sample

+0

Это замечательно! Спасибо! –