I want to use Java to set the table header and table body together, and I also need to add a solid line at the bottom of each page.
I am new to Aspose Word. Please provide code sample.
Thanks in advance
I want to use Java to set the table header and table body together, and I also need to add a solid line at the bottom of each page.
I am new to Aspose Word. Please provide code sample.
Thanks in advance
To set the table header and body on the same page in Aspose.Words for Java, you can use the DocumentBuilder class to create a table and ensure that the rows do not break across pages. Additionally, you can add a solid line at the bottom of each page by using the Shape class to draw a line.
Here’s a sample code snippet demonstrating how to achieve this:
import com.aspose.words.*;
public class TableExample {
public static void main(String[] args) throws Exception {
// Create a new document
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Start a new table
Table table = builder.startTable();
// Insert header row
builder.insertCell();
builder.write("Header 1");
builder.insertCell();
builder.write("Header 2");
builder.endRow();
// Insert body rows
for (int i = 0; i < 10; i++) {
builder.insertCell();
builder.write("Row " + (i + 1) + ", Cell 1");
builder.insertCell();
builder.write("Row " + (i + 1) + ", Cell 2");
builder.endRow();
}
builder.endTable();
// Set the table to not break across pages
for (Row row : table.getRows()) {
row.getRowFormat().setAllowBreakAcrossPages(false);
}
// Add a solid line at the bottom of each page
Shape line = new Shape(doc, ShapeType.LINE);
line.setWidth(500);
line.setHeight(0);
line.setTop(100); // Adjust the position as needed
line.setLeft(0);
line.getLineFormat().setColor(Color.BLACK);
line.getLineFormat().setWeight(2.0);
doc.getFirstSection().getBody().getParagraphs().add(new Paragraph(doc));
doc.getFirstSection().getBody().getLastParagraph().appendChild(line);
// Save the document
doc.save("TableWithHeaderAndBody.docx");
}
}
Document class.DocumentBuilder is used to start a table and insert header and body rows.AllowBreakAcrossPages property is set to false for each row to ensure that the table does not split across pages.Shape class and positioned at the bottom of the page.This code will create a Word document with a table that has its header and body on the same page, along with a solid line at the bottom. Adjust the line’s position as necessary to fit your layout requirements.