在我们的项目中,我们面临着一个表的Re-sizeable问题。
库 - aspose.words
问题:我们正在使用aspose生成PDF文档,在我们的pdf中,有多个表格。目前,如果一个表格太大,不适合放在一个页面上,它就会从页面上跑掉。我们想为这些表格实现自动缩放,如果表格太大,它可以自动调整表格的宽度和字体,使其始终适合页面。
另外在研究的时候,我发现了一个属性Autofit,但是对于我的方案没有用,因为这个并不能改变字体大小。
我想,在你的情况下,你可以尝试使用以下方法 文档.更新表格布局 方法来计算实际的表格宽度,然后检查表格是否适合页面。在下面的例子中,我创建了一个退出页面边界的简单表格,然后更新表格使其适合页面。在这个例子中,使用了一个简化的缩放字体大小的方法,最好是用 DocumentVisitor 来实现这一目的。
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Build a simple table that exits page bounds.
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 20; j++)
{
builder.InsertCell();
builder.Write("Test");
}
builder.EndRow();
}
Table t = builder.EndTable();
// If you check width of cells in the created table before calling this method, width will be zero,
// this means auto-width. After calling this method width of cells is updated and it is possible to calculate actual table width.
doc.UpdateTableLayout();
// Calculate width of the table.
double tableWidth = 0;
foreach (Cell c in t.FirstRow.Cells)
tableWidth += c.CellFormat.Width;
Section tableParentSection = (Section)t.GetAncestor(NodeType.Section);
if (tableWidth > tableParentSection.PageSetup.ContentWidth)
{
double fontRatio = tableParentSection.PageSetup.ContentWidth / tableWidth;
// Change font in the table.
// Note: this is rood mothod to change font size only for demonstration purposes.
// I would recommend you to use DocumentVisitor to change font size.
NodeCollection paragraphs = t.GetChildNodes(NodeType.Paragraph, true);
foreach (Paragraph p in paragraphs)
{
p.ParagraphBreakFont.Size *= fontRatio;
foreach (Run r in p.Runs)
r.Font.Size *= fontRatio;
}
}
doc.Save(@"C:\Temp\out.pdf");
希望能帮到你。
披露:我在Aspose.Words团队工作。