I’m trying to create a word document that shows student’s pictures. the picture are shown in a table. When all the picture for a student have been printed, it goes to the next one on a new page. I would like to have a specific header for each student. So if student1 has got 2 pages of pictures, header should say “Header for Student 1” on both pages, then it creates a new page and header should change to “Header for Student 2”. Currently, the header remains the same on each page for all students. It’s always “Header for Student 1”.
Here is my code :
public void CreateOneDocxForAll()
{
string date = DateTime.Now.ToString("yyyyMMdd");
// Utiliser GetFilePath pour obtenir le chemin complet du fichier DOCX
string docxFileName = date + "_AllStudents.docx";
string filePath = PathFinder.GetFilePath(docxFileName);
// Créer un document Word (DOCX)
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document))
{
// Ajouter un élément principal (MainDocumentPart) au document
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
// Parcourir les élèves pour créer une page par élève
foreach (var eleve in Eleves)
{
// Créer un HeaderPart pour chaque élève et l'ajouter au MainDocumentPart
HeaderPart headerPart = mainPart.AddNewPart<HeaderPart>();
string headerPartId = mainPart.GetIdOfPart(headerPart);
// Construire le contenu de l'en-tête pour chaque élève
Header header = new Header();
Paragraph headerParagraph = new Paragraph();
ParagraphProperties paragraphProperties = new ParagraphProperties();
paragraphProperties.Append(new Justification() { Val = JustificationValues.Center });
Run headerRun = new Run();
headerRun.Append(new DocumentFormat.OpenXml.Wordprocessing.Text($"Header for {eleve.EleveName}"));
headerParagraph.Append(paragraphProperties);
headerParagraph.Append(headerRun);
header.Append(headerParagraph);
headerPart.Header = header;
// Créer un élément de référence à l'en-tête pour chaque section
SectionProperties sectionProperties = new SectionProperties();
HeaderReference headerReference = new HeaderReference() { Id = headerPartId, Type = HeaderFooterValues.Default };
sectionProperties.Append(headerReference);
body.Append(sectionProperties);
// Ajouter une nouvelle section pour chaque élève
PageMargin pageMargin = new PageMargin()
{
Top = (int)(1.5 * twipValue), // 1 cm = 567twips
Right = UInt32Value.FromUInt32((uint)(1 * twipValue)),
Bottom = (int)(1.5 * twipValue),
Left = UInt32Value.FromUInt32((uint)(1 * twipValue)),
Header = UInt32Value.FromUInt32((uint)(1 * twipValue)),
Footer = UInt32Value.FromUInt32((uint)(1 * twipValue)),
Gutter = 0 // 0 inch
};
sectionProperties.Append(pageMargin);
// Crée un nouveau paragraphe avec un run et du texte
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text($"Les photos de {eleve.EleveName} - du {Debut.ToString("dd/MM/yyyy")} au {Fin.ToString("dd/MM/yyyy")}"));
List<Photo> photos = eleve.Photos;
// Create the table
Table table = new Table();
// Set the style and other formatting for the table
TableProperties tableProperties = new TableProperties(
new TableBorders(
new TopBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new BottomBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new LeftBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new RightBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideHorizontalBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideVerticalBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 }
)
);
TableWidth tableWidth = new TableWidth() { Width = "100%", Type = TableWidthUnitValues.Pct };
tableProperties.Append(tableWidth);
table.AppendChild(tableProperties);
int nbPhoto = 0;
int numberOfPhotos = eleve.Photos.Count;
int numberOfLines = (int)Math.Ceiling((double)numberOfPhotos / 3);
for (int i = 0; i < numberOfLines; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < 3; j++)
{
TableCell cell = new TableCell();
TableCellProperties cellProperties = new TableCellProperties(
new TableCellWidth { Type = TableWidthUnitValues.Dxa, Width = "2400" },
new TableCellBorders(
new TopBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new BottomBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new LeftBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new RightBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideHorizontalBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideVerticalBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 }
),
new CantSplit()
);
cell.Append(cellProperties);
if (nbPhoto < photos.Count)
{
cell.Append(new Paragraph(new Run(new DocumentFormat.OpenXml.Wordprocessing.Text($"Date : {photos[nbPhoto].DateTaken.ToString("dd/MM/yyyy")}"))));
if (!string.IsNullOrEmpty(photos[nbPhoto].Title)) cell.Append(new Paragraph(new Run(new DocumentFormat.OpenXml.Wordprocessing.Text($"{photos[nbPhoto].Title}"))));
InsertPictureFromByteArray(wordDocument, mainPart, photos[nbPhoto].Image, cell, DesiredWidth, DesiredHeight);
if (photos[nbPhoto].Domaine != null)
{
cell.Append(new Paragraph(new Run(new DocumentFormat.OpenXml.Wordprocessing.Text($"Domaine : {photos[nbPhoto].Domaine.DomaineName}"))));
cell.Append(new Paragraph(new Run(new DocumentFormat.OpenXml.Wordprocessing.Text($"{photos[nbPhoto].Domaine.DomaineDescription}"))));
}
if (photos[nbPhoto].Competence != null)
{
cell.Append(new Paragraph(new Run(new DocumentFormat.OpenXml.Wordprocessing.Text($"Compétence : {photos[nbPhoto].Competence.CompetenceName}"))));
cell.Append(new Paragraph(new Run(new DocumentFormat.OpenXml.Wordprocessing.Text($"{photos[nbPhoto].Competence.CompetenceDescription}"))));
}
}
else
{
cell.Append(new Paragraph(new Run(new DocumentFormat.OpenXml.Wordprocessing.Text())));
}
row.Append(cell);
nbPhoto++;
}
table.Append(row);
}
// Add the table to the body of the document.
body.Append(table);
// Ajouter une nouvelle page pour chaque élève
Paragraph pageBreak = new Paragraph(new Run(new Break() { Type = BreakValues.Page }));
body.Append(pageBreak);
}
// Enregistrer les modifications apportées au MainDocumentPart
mainPart.Document.Save();
}
}
Thank you for your help !
N D is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.