如何在FlowDocument中设置A4页面宽度,解决打印时第四列缺失问题
问题根源
你遇到的打印列显示异常是3个核心原因共同导致的:
- FlowDocument默认带了左右页边距,你直接把
PageWidth设为打印区域宽度后,实际表格可用宽度要小于设置值,固定像素的列宽总和超出可用宽度后第四列就会被裁切 - 你设置的四列固定像素宽度(总460px)加单元格间距后,已经接近A4纸横向打印一半宽度,和你观察到的「页面仅占A4一半」的现象吻合
- 你的代码存在两个逻辑错误:取行索引偏移、重复添加同一个Paragraph实例,也会引发渲染异常
修复步骤
- 先清空FlowDocument默认页边距,避免可用宽度被占用
FlowTabledoc.PagePadding = new Thickness(0); // 如果需要留边,可设置为 new Thickness(10,5,10,5) 对应左、上、右、下的边距
- 列宽改用比例分配,不要用固定像素,保证永远适配页面可用宽度
// 按你原来的列宽比例分配,自动适配整个打印宽度,不会超出也不会留空白 logflowtable.Columns[0].Width = new GridLength(60.0, GridUnitType.Star); logflowtable.Columns[1].Width = new GridLength(120.0, GridUnitType.Star); logflowtable.Columns[2].Width = new GridLength(190.0, GridUnitType.Star); logflowtable.Columns[3].Width = new GridLength(90.0, GridUnitType.Star);
- 修正代码逻辑错误
// 取行索引不要加1,刚添加的行索引就是当前r值 currentRow = logflowtable.RowGroups[0].Rows[r]; // 不要重复添加同一个Paragraph实例,需要空行的话每次实例化新对象 FlowTabledoc.Blocks.Add(new Paragraph() { FontSize =14 });
- 可选:如果要固定A4尺寸打印,显式设置页面尺寸即可
// A4纸对应WPF单位(96DPI)的宽高 FlowTabledoc.PageWidth = 793.7; FlowTabledoc.PageHeight = 1122.5;
完整可运行代码参考
PrintDialog printDlg = new PrintDialog(); FlowDocument FlowTabledoc = new FlowDocument(); // 清空默认边距 FlowTabledoc.PagePadding = new Thickness(0); FlowTabledoc.PageWidth = printDlg.PrintableAreaWidth; Table logflowtable = new Table(); FlowTabledoc.Blocks.Add(logflowtable); logflowtable.CellSpacing = 5; int numberOfColumns = 4; for (int x = 0; x < numberOfColumns; x++) { logflowtable.Columns.Add(new TableColumn()); } // 比例分配列宽 logflowtable.Columns[0].Width = new GridLength(60.0, GridUnitType.Star); logflowtable.Columns[1].Width = new GridLength(120.0, GridUnitType.Star); logflowtable.Columns[2].Width = new GridLength(190.0, GridUnitType.Star); logflowtable.Columns[3].Width = new GridLength(90.0, GridUnitType.Star); logflowtable.RowGroups.Add(new TableRowGroup()); int RowAnzahl = LogTB.Rows.Count; int ColAnzahl = LogTB.Columns.Count; for (int r = 0; r <= RowAnzahl - 1; r++) { logflowtable.RowGroups[0].Rows.Add(new TableRow()); // 修正索引 TableRow currentRow = logflowtable.RowGroups[0].Rows[r]; currentRow.FontSize = 14; currentRow.FontWeight = FontWeights.Normal; for (int c = 0; c <= ColAnzahl - 1; c++) { currentRow.Cells.Add(new TableCell(new Paragraph(new Run(LogTB.Rows[r][c].ToString())))); } // 每次新建空段落 FlowTabledoc.Blocks.Add(new Paragraph() { FontSize =14 }); } FlowTabledoc.Name = "FlowDoc"; IDocumentPaginatorSource idpSource = FlowTabledoc; printDlg.PrintDocument(idpSource.DocumentPaginator, "Title-Header");
内容的提问来源于stack exchange,提问作者HothCoder
相关产品推荐
相关产品推荐

