How can set the page size of MigraDoc?

2019-07-08 09:32发布

问题:

Sorry for I am just beginner of PDFsharp.

How can I set PageSize to a document? Let's say A4. How to set it? Here it is my code. Thanks.

    Document document = new Document();

    // Add a section to the document
    Section section = document.AddSection();
    section.AddParagraph("dddddd");


    // Add a section to the document
    var table = section.AddTable();
    table.AddColumn("8cm");
    table.AddColumn("8cm");

    var row = table.AddRow();
    var paragraph = row.Cells[0].AddParagraph("Left text");
    paragraph.AddTab();
    paragraph.AddText("Right text");
    paragraph.Format.ClearAll();
    // TabStop at column width minus inner margins and borders:
    paragraph.Format.AddTabStop("27.7cm", TabAlignment.Right);
    row.Cells[1].AddParagraph("Second column");
    table.Borders.Width = 1;

回答1:

A4 is the default size.

Every section has a PageSetup property where you can set page size, margins and such.

var section = document.LastSection;
section.PageSetup.PageFormat = PageFormat.A4;
section.PageSetup.TopMargin = "3cm";

You should never modify DefaultPageSetup, use a Clone() instead. PageFormat does not work for the Clone(), because PageWidth and PageHeight are set for the default size A4.
To get Letter format, you can use this code to overwrite PageWidth and PageHeight:

var section = document.LastSection;
section.PageSetup = Document.DefaultPageSetup.Clone();
section.PageSetup.PageFormat = PageFormat.Letter; // Has no effect after Clone(), just for documentation purposes.
section.PageSetup.PageWidth = Unit.FromPoint(612);
section.PageSetup.PageHeight = Unit.FromPoint(792);
section.PageSetup.TopMargin = "3cm";

To get Letter format, you can use this code to reset PageWidth and PageHeight to make PageFormat work again:

var section = document.LastSection;
section.PageSetup = Document.DefaultPageSetup.Clone();
section.PageSetup.PageWidth = Unit.Empty;
section.PageSetup.PageHeight = Unit.Empty;
section.PageSetup.PageFormat = PageFormat.Letter;
section.PageSetup.TopMargin = "3cm";

Creating a Clone() is useful if your code uses e.g. left and right margins to calculate table widths or such. No need to create a Clone if you set all margins explicitly or do not use margins for calculations.
If you need Clone() you can use the methods shown here to set the page size.



标签: c# migradoc