首先,这是我的代码:
string pdfTemplate = Application.StartupPath + "\\Templates\\Template Medico.pdf";
string newFile = Application.StartupPath + "\\Relatórios\\Relatório Médico_" + dataArquivo + ".pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
// Form Filling
pdfFormFields.SetField("data", data);
pdfFormFields.SetField("medico_nome", campo);
pdfFormFields.SetField("numero_consultas", numeroConsultas);
// Table Building
int numColumns = ds.Tables[0].Columns.Count;
PdfPTable datatable = new PdfPTable(numColumns);
datatable.DefaultCell.Padding = 10;
datatable.WidthPercentage = 100;
datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
float[] columnWidths = { 80, 80, 80, 80, 80, 80, 80, 80, 80 };
datatable.SetWidths(columnWidths);
float[] totalWidth = { 80, 80, 80, 80, 80, 80, 80, 80, 80 };
datatable.SetTotalWidth(totalWidth);
// Table Header
for (int k = 0; k < ds.Tables[0].Columns.Count; k++)
{
Phrase collumname = new Phrase(ds.Tables[0].Columns[k].ColumnName, FontFactory.GetFont("Verdana", 9));
datatable.AddCell(collumname);
}
// Lines and Columns
if (ds.Tables[0].Rows.Count <= 9) // less than 9 rows = no problem, no new pages and table spliting needed
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
datatable.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.WHITE;
datatable.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
Phrase phrase = new Phrase(ds.Tables[0].Rows[i][j].ToString(), FontFactory.GetFont("Verdana", 9));
datatable.AddCell(phrase);
}
}
// Write down the table on page 2
PdfContentByte content = pdfStamper.GetUnderContent(2);
datatable.WriteSelectedRows(0, -1, 70.0f, 495.0f, content);
}
else
{
int newPage = 3;
int currentPage = 2;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
datatable.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.WHITE;
datatable.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
Phrase phrase = new Phrase(ds.Tables[0].Rows[i][j].ToString(), FontFactory.GetFont("Verdana", 9));
datatable.AddCell(phrase);
}
if (i > 0 && i % 9 == 0)
{ //How do i print the table ONLY every 9 iterations? (9 iterations = 9 rows)
PdfContentByte content = pdfStamper.GetUnderContent(currentPage);
// Or how do i make a loop using the rowStart and rowEnd arguments of the
// WriteSelectedRows function in order to write only a set of 9 rows for each page?
datatable.WriteSelectedRows(0, -1, 70.0f, 495.0f, content);
pdfStamper.InsertPage(newPage, pdfReader.GetPageSize(2));
newPage++;
currentPage++;
}
}
}
该代码对我目前遇到的主要问题进行了很好的评论,但真正更大的问题,如线程标题中所述,是通过行和列以某种方式“拆分”或“控制”循环/迭代以匹配页,跳到另一页,继续写表。
任何帮助将不胜感激。