1

In the following C# code I attempt to determine the width of the page so that I can stretch a table with 3 columns to the full width of the page (minus the margins). Initially, I thought that I should set the width of each table column as 1/3 of the page width. However, I found that section.PageSetup.PageWidth , section.PageSetup.LeftMargin and section.PageSetup.RightMargin in the code below return a value of 0.

    Section section = document.AddSection();
    section.PageSetup.PageFormat = PageFormat.A4;
    section.PageSetup.Orientation = Orientation.Portrait;

    int sectionWidth = (int)Math.Ceiling(section.PageSetup.PageWidth -
                            section.PageSetup.LeftMargin -
                            section.PageSetup.RightMargin);

    int columnWidth = (int)Math.Ceiling(sectionWidth / 3);

I assumed that setting the page format to PageFormat.A4 and the orientation to Orientation.Portrait will set the value of section.PageSetup.PageWidth accordingly and will also set the values for the margins to some default values. Can someone please tell me what I am doing wrong? I only just started using MigraDoc yesterday. Many thanks.

user2430797
  • 320
  • 5
  • 18
  • 1
    This may help you out: http://stackoverflow.com/questions/15966672/pdfsharp-page-size-and-set-margin-issue-c-sharp (The marked answer says the included code is migradoc). – Steve Wellens Aug 30 '16 at 00:26
  • Thanks Steve. Yes it helps. I've learnt that I could use this: `PdfSharp.Drawing.XSize size = PdfSharp.PageSizeConverter.ToSize(PdfSharp.PageSize.A4)` to get the width of the whole page which is inclusive of the margins. Now I have to find a way to subtract the default margins to get the "usable width" of the page. – user2430797 Aug 30 '16 at 02:34

2 Answers2

3

You can use document.DefaultPageSetup to query the default margins.

MigraDoc uses self-made nullable values (implemented in the days of .NET 1.1) and values that were not set will return 0, not the default value that will actually be used.

See also:
https://stackoverflow.com/a/22679890/1015447

Community
  • 1
  • 1
-1

This is still happening in PDFShapr.MigraDoc-wpf (1.50.5147) I am using with .Net Core 3.1. I solved it by cloning into the section the document's default page setup:

var section = this.Document.AddSection();
section.PageSetup = this.Document.DefaultPageSetup.Clone(); 

And then I used the section's page setup for example to compute the with of the columns of a table relative to the page with:

var tbl = section.Headers.Primary.AddTable();
var col1 = tbl.AddColumn(Unit.FromCentimeter(PageLineLength(section.PageSetup) * 0.75));    
var col2 = tbl.AddColumn(Unit.FromCentimeter(PageLineLength(section.PageSetup) - col1.Width.Centimeter));

Where PageLineLength:

PageLineLength(PageSetup pageSetup)
{
        return pageSetup.PageWidth.Centimeter - pageSetup.LeftMargin.Centimeter - pageSetup.RightMargin.Centimeter;
}
Lupa
  • 586
  • 1
  • 8
  • 22