PdfTable isn't added to my document

我只是一个虾纸丫 提交于 2019-12-24 10:00:04

问题


Here's the code:

public void PrintBoletin(int studentId, int gradeParaleloId)
{
    StudentRepository studentRepo = new StudentRepository();
    var student = studentRepo.FindStudent(studentId);
    int rowHeight = 20;

    string filePath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\Boletin.pdf";
    Document document = new Document(PageSize.LETTER);
    BaseFont baseFont = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1250, BaseFont.EMBEDDED);
    Font font = new Font(baseFont, 8);

    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create));
    document.Open();

    GradeParaleloRepository paraRep = new GradeParaleloRepository();
    var gra = paraRep.FindGradeParalelo(gradeParaleloId);
    Paragraph p = new Paragraph(new Phrase("Boletin de Notas - Gestion " + DateTime.Now.Year + " \n " + gra.Grade.Name + " " + gra.Name + "\n Colegio Madre Vicenta Uboldi \n " + DateTime.Now, font));
    Paragraph p2 = new Paragraph(new Phrase("Alumno: " + student.StudentId + " - " + student.LastNameFather + " " + student.LastNameMother + ", " + student.Name, font));

    document.Add(p);
    document.Add(p2);

    PdfPTable table = new PdfPTable(14); //14 Column table.
    table.TotalWidth = 550f;
    float[] widths = new float[] { 1.4f, 0.18f, 0.18f, 0.18f, 0.18f, 0.18f, 0.18f, 0.18f, 0.18f, 0.18f, 0.18f, 0.18f, 0.18f, 0.18f };
    table.SetWidths(widths);

    PdfPCell materia = new PdfPCell(new Phrase("MATERIA", font));
    materia.Rowspan = 2;
    materia.Colspan = 2;
    materia.HorizontalAlignment = 1;
    materia.VerticalAlignment = 1;
    table.AddCell(materia);


    table.SpacingBefore = 20f;
    table.SpacingAfter = 20f;

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

    Process.Start(filePath);
}

When I open the generated PDF file, no table is added to the document at all. Only the paragraphs are. Any ideas?


回答1:


You create a table with 14 columns, but only add one. In PdfPTable you create rows by just adding cells. If number of cells added is equal to the expected column number, a row is created. So if you only add one cell, no row is created.

Furthermore, you use ColSpan = 2, so you only need to add 7 columns per row.

I changed RowSpan to 1 as it didn't work well here when all the cells were rowspanned, it didn't make sense to have it spanned anyway, so...

Here's my modification which creates a single row:

for (int i = 0; i < widths.Length / 2; i++)
{
    PdfPCell materia = new PdfPCell(new Phrase("MATERIA", font));
    materia.Rowspan = 1;
    materia.Colspan = 2;
    materia.HorizontalAlignment = 1;
    materia.VerticalAlignment = 1;
    table.AddCell(materia);
}


来源:https://stackoverflow.com/questions/6071665/pdftable-isnt-added-to-my-document

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!