Aspose - 问题自动 table 调整大小,适合页面

Aspose - Issue in Auto table Resize, Fit to Page

我们的项目面临 table 可调整大小的问题。

图书馆 - aspose.words

问题: 我们正在使用 aspose 生成 PDF 文档,在我们的 pdf 中有多个 tables。目前,如果 table 太大而不适合页面,它将 运行 关闭页面。我们要实现这些table的自动缩放,自动缩放这样如果table太大那么它可以自动调整宽度,table里面的字体这样它总是适合到页面。

此外,在调查时我发现了一个 属性 Autofit,但它对我的场景没有用,因为它不会改变字体大小。

我认为,对于您的情况,您可以尝试使用 Document.Updatetablelayout method to calculate actual table width and then check if the table fits the page. In the following example I created a simple table that exits the page bounds and then updated the table to make it fit the page. In the example a simplified method for scaling font size is used, it is better to use 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");

这是 table 在不更新内容的情况下的样子 更新字体大小后,它看起来像这样

希望对您有所帮助。

披露:我在 Aspose.Words 团队工作。