HelloMigraDoc
Version 6.1.0
In this article
- Introduction
- Setting the font resolver
- Creating the document object
- Defining styles
- Adding a cover page
- Adding a table of contents
- Adding the content section
- Adding paragraphs
- Adding tables
- Adding a chart
- Rendering the document
This article describes the extensive HelloMigraDoc sample of the PDFsharp.samples solution.
Introduction
The HelloMigraDoc sample shows how to create a MigraDoc document using styles and multiple kinds of content. It shows how styles improve the cleanness and maintainability of the code that creates a document. The document furthermore includes a cover page and a table of contents. In addition to paragraphs using several format properties, tables and a chart are added as content. The "HelloMigraDoc" project of the PDFsharp.Samples solution contains the code of this sample. You can find it here on GitHub.
Below all the code of the sample is explained.
Setting the font resolver
To make all fonts needed for the document resolvable, a font resolver is set when using the Core build of MigraDoc (see Choose a PDFsharp build):
#if CORE
// Core build does not use Windows fonts,
// so set a FontResolver that handles the fonts our samples need.
GlobalFontSettings.FontResolver = new SamplesFontResolver();
#endif
See full Program.cs file in PDFsharp.Sample repository.
For your own projects you should create your own font resolver which supports all the fonts needed. But pay attention that SamplesFontResolver loads the fonts from the repository-specific assets folder of PDFsharp.Samples, while you must provide your font files in an appropriate way that works without repository.
To learn about font resolving see Document Object Model / Document / MigraDoc settings / Font resolving.
Creating the document object
Program.Main
callsDocuments.CreateDocument()
, which assembles the whole document in this sample.
The first step here is to create the Document instance:
// Create a new MigraDoc document.
var document = new Document
{
Info =
{
Title = "Hello, MigraDoc",
Subject = "Demonstrates an excerpt of the capabilities of MigraDoc.",
Author = "Stefan Lange"
}
};
See Documents class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
These lines create the MigraDoc document and add some information about the document.
To learn about adding document information see Document Object Model / Document / Document settings.
Defining styles
Now, Documents.CreateDocument()
starts Styles.DefineStyles()
and passes the Document instance.
This method starts with setting the default font:
// Get the predefined style Normal.
var style = document.Styles[StyleNames.Normal]!;
// Because all styles are derived from Normal, the next line changes the
// font of the whole document. Or, more exactly, it changes the font of
// all styles and paragraphs that do not redefine the font.
style.Font.Name = "Arial";
See Styles class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
Normal is the default style all other paragraph styles derive from. So, Arial will be inherited to all styles and to all objects of the document, as long as it doesn’t get overridden.
For information about using styles and their inheritance see Document Object Model / Document / Formatting.
After that, the styles for the first three heading levels are defined:
// Heading1 to Heading9 are predefined styles with an outline level. An outline level
// other than OutlineLevel.BodyText automatically creates the outline (or bookmarks)
// in PDF.
style = document.Styles[StyleNames.Heading1]!;
style.Font.Name = "Times New Roman";
style.Font.Size = 16;
style.Font.Color = Colors.DarkBlue;
style.ParagraphFormat.PageBreakBefore = true;
style.ParagraphFormat.SpaceAfter = 6;
// Set KeepWithNext for all headings to prevent headings from appearing all alone
// at the bottom of a page. The other headings inherit this from Heading1.
style.ParagraphFormat.KeepWithNext = true;
style = document.Styles[StyleNames.Heading2]!;
style.Font.Size = 14;
style.ParagraphFormat.PageBreakBefore = false;
style.ParagraphFormat.SpaceBefore = 6;
style.ParagraphFormat.SpaceAfter = 6;
style = document.Styles[StyleNames.Heading3]!;
style.Font.Size = 12;
style.Font.Italic = true;
style.ParagraphFormat.SpaceBefore = 6;
style.ParagraphFormat.SpaceAfter = 3;
See Styles class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
Size, SpaceBefore and SpaceAfter are properties of the type Unit (see Document Object Model / Formats / Unit for more information).
Color is a property of the type Color (see Document Object Model / Formats / Colors for more information).
As the comment above states, the document outline is automatically generated for all paragraphs using one of the heading styles.
For Heading1 the font name, size, and color are set. Further, there shall be a page break before these headings and some space afterwards. Size and SpaceAfter are properties of the type Unit. The integers assigned here are implicitly converted to a Unit of the unit type Point (see Document Object Model / Formats / Unit for more information). KeepWithNext ensures that the heading and the next paragraph will not be separated by an automatic page break.
For Heading2 the font size, PageBreakBefore, and SpaceAfter are changed. Those values override those that would be inherited from Heading1 otherwise. Additionally, a space before the paragraph is set. All properties not overridden here will be inherited from Heading1. In this case, this is the font name and color and the KeepWithNext value.
For Heading3 the font size and paragraph spaces are changed. Additionally, the font is set to italic. All properties not overridden here will be inherited from Heading2. This is the font name and color and the KeepWithNext value, which were inherited from Heading1 originally, and the PageBreakBefore false value from Heading2.
For information about using styles and their inheritance see Document Object Model / Document / Formatting.
To explore the possibilities of formatting a font see Document Object Model / Formats / Font.
To learn about formatting a paragraph see Document Object Model / Formats / Paragraph.
Next, the styles for the header and footer are set:
style = document.Styles[StyleNames.Header]!;
style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right);
style = document.Styles[StyleNames.Footer]!;
style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center);
See Styles class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
Some tab stops are added here to align the contents of the header and footer. For this document it would be sufficient to set the paragraph alignment instead. However, using tab stops for alignment you could even align multiple data to different positions in the header or footer.
To learn about headers and footers and how to use tab stops inside to present various information see Document Object Model / Contents / Headers & footers.
For further information about tab stops see Document Object Model / Formats / Tab stops.
Finally, two user-defined styles are added:
// Create a new style called TextBox based on style Normal.
style = document.Styles.AddStyle(TextBoxStyle, StyleNames.Normal);
style.ParagraphFormat.Alignment = ParagraphAlignment.Justify;
style.ParagraphFormat.Borders.Width = 2.5;
style.ParagraphFormat.Borders.Distance = "3pt";
style.ParagraphFormat.Shading.Color = Colors.SkyBlue;
// Create a new style called TOC based on style Normal.
style = document.Styles.AddStyle(TocStyle, StyleNames.Normal);
style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right, TabLeader.Dots);
style.ParagraphFormat.Font.Color = Colors.Blue;
They refer to constants defined in the Styles class:
public const string TextBoxStyle = "TextBox";
public const string TocStyle = "TOC";
See Styles class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
The Width and Distance properties and the position parameter of AddTabStop are of type Unit (see Document Object Model / Formats / Unit for more information).
Color is a property of the type Color (see Document Object Model / Formats / Colors for more information).
For the first one, named "TextBox" (TextBoxStyle), the alignment, the width of and distance to a border and a shading is set. For the second one, named "TOC" (TocStyle), a tab stop is added, and the font color is set. The default paragraph style Normal is used as the base style for both.
To learn about creating own styles see Document Object Model / Document / Formatting.
To explore the possibilities of formatting borders see Document Object Model / Formats / Borders & line format.
For information about setting a shading see Document Object Model / Formats / Shading & fill format.
Adding a cover page
After defining the styles, Documents.CreateDocument()
starts Cover.DefineCover()
and passes the Document instance.
This adds a cover page to the document and starts with adding a new section:
var section = document.AddSection();
See Cover class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
Actually, there are no pages defined in a MigraDoc document. Those are created only when rendering a PDF. However, this is the beginning of the document, so the cover will start of course on a blank page. You should ensure that all content dedicated to the cover page fits in one page. Before adding the content for the next page, a page break will be inserted manually (see Adding a table of contents).
To learn about how documents are structured see Document Object Model / Document / Document structure.
For information about the page flow of a MigraDoc document and how to control it see Document Object Model / Document / Page control.
A paragraph is added as the first element of this section:
var paragraph = section.AddParagraph();
paragraph.Format.SpaceAfter = "3cm";
See Cover class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
SpaceAfter is a property of the type Unit (see Document Object Model / Formats / Unit for more information).
This paragraph is added to the section. But there’s no content added to the paragraph. It is just an empty paragraph. The space after the paragraph is set to 3 centimeters using direct formatting. This is the purpose of that paragraph. It acts as a spacer to let the following image start further down on the page.
For information about direct formatting see Document Object Model / Document / Formatting.
To learn about formatting a paragraph see Document Object Model / Formats / Paragraph.
Now, the aforementioned image is added:
var imagePath = IOUtility.GetAssetsPath("migradoc/images/MigraDoc-landscape.png")!;
var image = section.AddImage(imagePath);
image.Width = "10cm";
See Cover class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
The GetAssetsPath call only gets the path to the image, so important are only the following lines, which add the image to the section and format it. The image is set to a width of 10 centimeters. This will scale the image while maintaining its aspect ratio unchanged.
For information about adding and formatting images see Document Object Model / Contents / Images.
The image is followed by some text:
paragraph = section.AddParagraph("A sample document that demonstrates the\ncapabilities of ");
paragraph.AddFormattedText("MigraDoc", TextFormat.Bold);
paragraph.Format.Font.Size = 16;
paragraph.Format.Font.Color = Colors.DarkRed;
paragraph.Format.SpaceBefore = "8cm";
paragraph.Format.SpaceAfter = "3cm";
See Cover class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
Size, SpaceBefore and SpaceAfter are properties of the type Unit (see Document Object Model / Formats / Unit for more information).
The word "MigraDoc" is added in a formatted text, to set only that word to bold. The whole text is formatted directly instead of using styles. You could decide to use a heading style for the document title, but here the text is not wanted to be part of the document outline. Instead of a style, direct formatting is chosen. There’s no need to use a style, as this paragraph is meant to be the only occurrence of that specific format.
To learn about paragraphs and formatted text see Document Object Model / Contents / Text.
To explore the possibilities of formatting a font see Document Object Model / Formats / Font.
Finally, a series of paragraphs displaying some information about the document is added:
paragraph = section.AddParagraph("Rendering date: ");
paragraph.AddDateField();
section.AddParagraph($"Version: {MigraDocRenderingBuildInformation.GitSemVer}");
section.AddParagraph($"Branch: {MigraDocRenderingBuildInformation.BranchName}");
section.AddParagraph($"Assembly: {MigraDocRenderingBuildInformation.AssemblyTitle}");
paragraph = section.AddParagraph("Platform: ");
var platform = MigraDocRenderingBuildInformation.TargetPlatform;
if (String.IsNullOrEmpty(platform))
paragraph.AddFormattedText("(none)", TextFormat.Italic);
else
paragraph.AddText(platform);
See Cover class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
To the first paragraph a date field is added to render the current date and time. The other paragraphs show some information about the used MigraDoc version. For the last paragraph, you can see how the format can be made dependent of the content.
For information about fields see Document Object Model / Contents / Fields.
Adding a table of contents
The cover shall be followed by a table of content.
Documents.CreateDocument()
starts TableOfContents.DefineTableOfContents()
and passes the Document instance.
This method does not start a new section, but gets the last one to continue adding contents to it:
var section = document.LastSection;
section.AddPageBreak();
See TableOfContents class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
As you can see, there is also a page break added to end the cover page and start the table of contents on a new one.
For information about the page flow of a MigraDoc document and how to control it see Document Object Model / Document / Page control.
Then the heading for the table of content is added:
var paragraph = section.AddParagraph("Table of Contents");
paragraph.Format.Font.Size = 14;
paragraph.Format.Font.Bold = true;
paragraph.Format.SpaceAfter = 24;
paragraph.Format.OutlineLevel = OutlineLevel.Level1;
See TableOfContents class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
Size and SpaceAfter are properties of the type Unit (see Document Object Model / Formats / Unit for more information).
The paragraph representing this heading is formatted using direct formatting. The Heading1 style set in Defining styles could have been used instead, like it is done in the rest of the document (see Adding paragraphs for example). But obviously this heading shall not match the style of the other headings of that level.
The font is set to the desired size and to bold and also the space after that paragraph is set. By setting OutlineLevel to Level1, this heading will appear at the same level in the document outline as the headings that use the style Heading1.
For information about direct formatting see Document Object Model / Document / Formatting.
To explore the possibilities of formatting a font see Document Object Model / Formats / Font.
To learn about formatting a paragraph see Document Object Model / Formats / Paragraph.
To learn about headings and outline level see Document Object Model / Document / Document structure.
The table of content itself consists of the following paragraphs:
paragraph = section.AddParagraph();
paragraph.Style = Styles.TocStyle;
var hyperlink = paragraph.AddHyperlink(Paragraphs.BookmarkName);
hyperlink.AddText("Paragraphs\t");
hyperlink.AddPageRefField(Paragraphs.BookmarkName);
paragraph = section.AddParagraph();
paragraph.Style = Styles.TocStyle;
hyperlink = paragraph.AddHyperlink(Tables.BookmarkName);
hyperlink.AddText("Tables\t");
hyperlink.AddPageRefField(Tables.BookmarkName);
paragraph = section.AddParagraph();
paragraph.Style = Styles.TocStyle;
hyperlink = paragraph.AddHyperlink(Charts.BookmarkName);
hyperlink.AddText("Charts\t");
hyperlink.AddPageRefField(Charts.BookmarkName);
See TableOfContents class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
Each of these paragraphs uses the TocStyle defined in Defining styles.
A hyperlink is added, which refers to a bookmark.
To the hyperlink some text with a tab (\t
) appended and a PageRefField instance are added.
The PageRefField will render the page number of the given bookmark.
Due to the tab it will be aligned at the tab stop defined in the TocStyle style.
The referred bookmarks are identified by strings which are here saved in the BookmarkName constants of the Paragraphs (see Adding paragraphs), Tables (see Adding tables), and Charts (Adding a chart) classes.
For information about using styles see Document Object Model / Document / Formatting.
To learn about hyperlinks, the referenced bookmark fields, and PageRefField see Document Object Model / Contents / Hyperlinks and Document Object Model / Contents / Fields.
Adding the content section
Now the actual content of the document shall be added.
This shall be done to a new section, which defines also headers and footers.
Therefore Documents.CreateDocument()
starts DefineContentSection()
and passes the Document instance.
First, the section is created and some settings of the page setup are set:
var section = document.AddSection();
section.PageSetup.OddAndEvenPagesHeaderFooter = true;
section.PageSetup.StartingNumber = 1;
See Documents class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
The section is set to use different headers and footers for odd and for even pages. Furthermore, it is set to start with page number one. This does not affect the page numbers shown in PDF viewer applications, but the page numbers shown inside the document when using fields.
To explore the possibilities of changing the page setup see Document Object Model / Formats / Page setup.
For information about fields and controlling the page number see Document Object Model / Contents / Fields.
The headers of the section are defined as follows:
// For the odd page header, add a paragraph with right aligned text due to the given tab.
// See definition of style StyleNames.Header.
var header = section.Headers.Primary;
header.AddParagraph("\tOdd Page Header");
// For the even page header, add a paragraph with left aligned text due to the missing tab.
// See definition of style StyleNames.Header.
header = section.Headers.EvenPage;
header.AddParagraph("Even Page Header");
See Documents class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
The Primary and EvenPage headers are created in the moment of access. So, by adding a paragraph, the header is automatically created if not yet existing. The Primary header is the header usually used. As the section is set to use different headers and footers for odd and even pages, it is used for the odd ones only and the even pages will use the EvenPage header.
Regard the tab (\t
) at the beginning of the Primary header’s paragraph content.
As the headers will use the StyleNames.Header
style defined in Defining styles, it will align the text to the right to the tab stop defined there.
There is no tab in the EvenPage header’s paragraph content, so the content of the even pages will appear left aligned.
For information about headers and footers see Document Object Model / Contents / HeadersAndFooters.
To learn about tab stops see Document Object Model / Formats / Tab stops.
Finally, the footers are defined:
// Create a paragraph with centered page number. See definition of style StyleNames.Footer.
var paragraph = new Paragraph();
paragraph.AddTab();
paragraph.AddPageField();
// Add paragraph to footer for odd pages.
section.Footers.Primary.Add(paragraph);
// Add clone of paragraph to footer for even pages. Cloning is necessary because an object must
// not belong to more than one other object. If you forget cloning an exception is thrown.
section.Footers.EvenPage.Add(paragraph.Clone());
See Documents class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
The section is set to use different headers and footers for odd and for even pages. But what if the headers shall be different and the footers shall not? You can just add the same content to the Primary and EvenPage footer. But each object of the document must only have one parent. Therefore, you have to clone it before adding it to a second object, like done here for the given paragraph.
The paragraph itself got a tab and a page field to show the current page number as content.
As the footers will use the StyleNames.Footer
style defined in Defining styles, the tab will align the page number at the center.
The relationship between parent and child document objects and the Clone method are explained in Document Object Model / Document / Document structure.
Adding paragraphs
The first chapter of the content section is added by Paragraphs.DefineParagraphs()
.
It is started now by Documents.CreateDocument()
which also passes the Document instance.
The heading is added first:
var paragraph = document.LastSection.AddParagraph("Paragraph Layout Overview",
StyleNames.Heading1);
paragraph.AddBookmark(BookmarkName);
See Paragraphs class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
The paragraph is set to use StyleNames.Heading1
which is defined in Defining styles.
The added bookmark with the string constant BookmarkName is used as a reference in the table of contents (see Adding a table of contents).
For information about using styles see Document Object Model / Document / Formatting.
To learn about bookmark fields see Document Object Model / Contents / Fields.
DefineParagraphs starts DemonstrateAlignment and passes the Document instance. As the name says, it adds some alignment examples:
document.LastSection.AddParagraph("Alignment", StyleNames.Heading2);
document.LastSection.AddParagraph("Left Aligned", StyleNames.Heading3);
var paragraph = document.LastSection.AddParagraph();
paragraph.Format.Alignment = ParagraphAlignment.Left;
paragraph.AddText(FillerText.Text);
document.LastSection.AddParagraph("Right Aligned", StyleNames.Heading3);
paragraph = document.LastSection.AddParagraph();
paragraph.Format.Alignment = ParagraphAlignment.Right;
paragraph.AddText(FillerText.Text);
document.LastSection.AddParagraph("Centered", StyleNames.Heading3);
paragraph = document.LastSection.AddParagraph();
paragraph.Format.Alignment = ParagraphAlignment.Center;
paragraph.AddText(FillerText.Text);
document.LastSection.AddParagraph("Justified", StyleNames.Heading3);
paragraph = document.LastSection.AddParagraph();
paragraph.Format.Alignment = ParagraphAlignment.Justify;
paragraph.AddText(FillerText.MediumText);
See Paragraphs class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
A heading for the alignment subchapter is added, followed by four blocks for each alignment example. Each block consists of a heading and a paragraph, that is set to the appropriate alignment. The texts added to the paragraphs are defined in the FillerText class.
For information about direct formatting see Document Object Model / Document / Formatting.
To learn about setting the alignment and formatting a paragraph see Document Object Model / Formats / Paragraph.
The same is done to show some indent examples in DemonstrateIndent:
document.LastSection.AddParagraph("Indent", StyleNames.Heading2);
document.LastSection.AddParagraph("Left Indent", StyleNames.Heading3);
var paragraph = document.LastSection.AddParagraph();
paragraph.Format.LeftIndent = "2cm";
paragraph.AddText(FillerText.Text);
document.LastSection.AddParagraph("Right Indent", StyleNames.Heading3);
paragraph = document.LastSection.AddParagraph();
paragraph.Format.RightIndent = "1in";
paragraph.AddText(FillerText.Text);
document.LastSection.AddParagraph("First Line Indent", StyleNames.Heading3);
paragraph = document.LastSection.AddParagraph();
paragraph.Format.FirstLineIndent = "12mm";
paragraph.AddText(FillerText.Text);
document.LastSection.AddParagraph("First Line Negative Indent", StyleNames.Heading3);
paragraph = document.LastSection.AddParagraph();
paragraph.Format.LeftIndent = "1.5cm";
paragraph.Format.FirstLineIndent = "-1.5cm";
paragraph.AddText(FillerText.Text);
See Paragraphs class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
The indent properties are of the type Unit (see Document Object Model / Formats / Unit for more information).
These examples show how setting LeftIndent, RightIndent, and FirstLineIndent affect the rendered text. As you can see in the last example, the FirstLineIndent value is added to the LeftIndent value to calculate the actual indent of the first line from the page margin.
For information about setting the indents and formatting a paragraph see Document Object Model / Formats / Paragraph.
DemonstrateFormattedText called next shows a paragraph containing a lot of FormattedText instances which each realize a different inline formatting:
document.LastSection.AddParagraph("Formatted Text", StyleNames.Heading2);
var paragraph = document.LastSection.AddParagraph();
paragraph.AddText("Text can be formatted ");
paragraph.AddFormattedText("bold", TextFormat.Bold);
paragraph.AddText(", ");
paragraph.AddFormattedText("italic", TextFormat.Italic);
paragraph.AddText(", or ");
paragraph.AddFormattedText("bold & italic", TextFormat.Bold | TextFormat.Italic);
paragraph.AddText(".");
paragraph.AddLineBreak();
paragraph.AddText("You can set the ");
var formattedText = paragraph.AddFormattedText("size");
formattedText.Size = 15;
paragraph.AddText(", the ");
formattedText = paragraph.AddFormattedText("color");
formattedText.Color = Colors.Firebrick;
paragraph.AddText(", the ");
paragraph.AddFormattedText("font", new Font("Times New Roman", 12));
paragraph.AddText(".");
paragraph.AddLineBreak();
paragraph.AddText("You can set the ");
formattedText = paragraph.AddFormattedText("subscript");
formattedText.Subscript = true;
paragraph.AddText(" or ");
formattedText = paragraph.AddFormattedText("superscript");
formattedText.Superscript = true;
paragraph.AddText(".");
See Paragraphs class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
Size is a property of the type Unit (see Document Object Model / Formats / Unit for more information).
Color is a property of the type Color (see Document Object Model / Formats / Colors for more information).
For the text parts that shall be added with unchanged format, Text instances are added. The FormattedText instances change the font inherited by the paragraph by direct formatting. After each sentence a line break is added. Note that each blank at the cuts between Text and FormattedText instances is assigned to the Text instance as only the specific text excerpts wrapped in formatted texts shall use the appropriate format.
To learn about paragraphs and formatted text see Document Object Model / Contents / Text.
To explore the possibilities of formatting a font see Document Object Model / Formats / Font.
Finally, DemonstrateBordersAndShading adds examples for setting the borders and the shading of a paragraph:
document.LastSection.AddPageBreak();
document.LastSection.AddParagraph("Borders and Shading", StyleNames.Heading2);
document.LastSection.AddParagraph("Border around Paragraph", StyleNames.Heading3);
var paragraph = document.LastSection.AddParagraph();
paragraph.Format.Borders.Width = 2.5;
paragraph.Format.Borders.Color = Colors.Navy;
paragraph.Format.Borders.Distance = 3;
paragraph.AddText(FillerText.MediumText);
document.LastSection.AddParagraph("Shading", StyleNames.Heading3);
paragraph = document.LastSection.AddParagraph();
paragraph.Format.Shading.Color = Colors.LightCoral;
paragraph.AddText(FillerText.Text);
document.LastSection.AddParagraph("Borders & Shading", StyleNames.Heading3);
paragraph = document.LastSection.AddParagraph();
paragraph.Style = Styles.TextBoxStyle;
paragraph.AddText(FillerText.MediumText);
See Paragraphs class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
Width and Distance are properties of the type Unit (see Document Object Model / Formats / Unit for more information).
Color is a property of the type Color (see Document Object Model / Formats / Colors for more information).
A manual page break is added before the heading of this subchapter. The first example defines a paragraph with a border of a specific width and color and a padding of 3 points to the border (which is the Distance property). The second example defines a paragraph with a shading set. While the paragraph in the first two examples is formatted using direct formatting, for the third one a style is set. This TextBoxStyle was defined in Defining styles and sets the alignment, border, and shading of the paragraph.
To explore the possibilities of formatting borders see Document Object Model / Formats / Borders & line format.
For information about setting a shading see Document Object Model / Formats / Shading & fill format.
Adding tables
The second chapter of the content section is added by Tables.DefineTables()
.
It is started now by Documents.CreateDocument()
which also passes the Document instance.
The heading is added like it was done in Adding paragraphs.
DefineTables starts DemonstrateSimpleTable and passes the Document instance. A table with two columns and three rows is added:
document.LastSection.AddParagraph("Simple Tables", StyleNames.Heading2);
var table = new Table
{
Borders =
{
Width = 0.75
}
};
var column = table.AddColumn(Unit.FromCentimeter(2));
column.Format.Alignment = ParagraphAlignment.Center;
table.AddColumn(Unit.FromCentimeter(5));
var row = table.AddRow();
row.Shading.Color = Colors.PaleGoldenrod;
row.HeadingFormat = true;
var cell = row.Cells[0];
cell.AddParagraph("Itemus");
cell = row.Cells[1];
cell.AddParagraph("Descriptum");
row = table.AddRow();
cell = row.Cells[0];
cell.AddParagraph("1");
cell = row.Cells[1];
cell.AddParagraph(FillerText.ShortText);
row = table.AddRow();
cell = row.Cells[0];
cell.AddParagraph("2");
cell = row.Cells[1];
cell.AddParagraph(FillerText.Text);
table.SetEdge(0, 0, 2, 3, Edge.Box, BorderStyle.Single, 1.5, Colors.Black);
document.LastSection.Add(table);
See Tables class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
The Width property and the width parameter of SetEdge are of type Unit (see Document Object Model / Formats / Unit for more information).
Color is a property of the type Color (see Document Object Model / Formats / Colors for more information).
The table is initialized with a border width of 0.75 point. Two columns are added with a width of two and five centimeters. For the first one the alignment is set to center.
A first row is added and a shading set. The HeadingFormat property is set to true. Due to this, the row would be repeated if the table would span over multiple pages. Two other rows with content are added.
While columns and rows have to be created explicitly, you don’t have to do this for cells. You can simply access a cell with the Cells property.
Before adding the table to the section, the SetEdge method is called to change the border for the given area of cells.
This area spans from column 0 and row 0 to column 2 and row 3, so it spans the whole table.
By setting the edge parameter to Edge.Box
it is defined that only the outer borders of this area shall be changed.
They are now changed to a single black border with a width of 1.5 point.
Finally, the table is added to the last section, as it was created, but not added by now.
For information about using styles and direct formatting see Document Object Model / Document / Formatting.
To learn about how to create and format tables see Document Object Model / Contents / Tables.
To explore the possibilities of formatting borders see Document Object Model / Formats / Borders & line format.
To learn about setting a shading see Document Object Model / Formats / Shading & fill format.
For information about formatting a paragraph see Document Object Model / Formats / Paragraph.
For a second example DefineTables starts DemonstrateAlignment and passes the Document instance. It shows how to horizontally and vertically align the content of table cells:
document.LastSection.AddParagraph("Cell Alignment", StyleNames.Heading2);
var table = document.LastSection.AddTable();
table.Borders.Visible = true;
table.Format.Shading.Color = Colors.LavenderBlush;
table.Shading.Color = Colors.Salmon;
table.TopPadding = 5;
table.BottomPadding = 5;
var column = table.AddColumn();
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn();
column.Format.Alignment = ParagraphAlignment.Center;
column = table.AddColumn();
column.Format.Alignment = ParagraphAlignment.Right;
table.Rows.Height = 35;
var row = table.AddRow();
row.VerticalAlignment = VerticalAlignment.Top;
row.Cells[0].AddParagraph("Text");
row.Cells[1].AddParagraph("Text");
row.Cells[2].AddParagraph("Text");
row = table.AddRow();
row.VerticalAlignment = VerticalAlignment.Center;
row.Cells[0].AddParagraph("Text");
row.Cells[1].AddParagraph("Text");
row.Cells[2].AddParagraph("Text");
row = table.AddRow();
row.VerticalAlignment = VerticalAlignment.Bottom;
row.Cells[0].AddParagraph("Text");
row.Cells[1].AddParagraph("Text");
row.Cells[2].AddParagraph("Text");
See Tables class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
Height and the padding properties are of the type Unit (see Document Object Model / Formats / Unit for more information).
Color is a property of the type Color (see Document Object Model / Formats / Colors for more information).
This table is added to the last section and initialized with the default border width of 0.5 point as the Visible property of the borders is set, but the Width property is not.
Furthermore, the difference between the table’s shading and the table’s paragraph format shading is regarded.
The color Salmon, which is set to table.Shading.Color
, will shade all the table cells.
The color LavenderBlush, which is set to table.Format.Shading.Color
, will be inherited to all paragraphs in all cells.
This paragraph shading won’t fill the whole cells as there’s padding between the paragraphs and their parent cells and as the height of the rows is set explicitly to 35 points.
Also, if the paragraphs of a row were of a different height, the shorter ones would not be able to fill their cells completely.
The top and bottom padding of the cells is set to 5 points, for the left and right padding a default value of 1.2 millimeters is used.
The columns added to the table are set to different alignments, which will be inherited to the paragraphs. For the rows each one is set to one of the possible vertical alignment values, which is inherited to the cells. This way the table shows all the combinations of these horizontal and the vertical alignments.
For information about text positioning inside of tables see Document Object Model / Contents / Tables.
DefineTables starts DemonstrateCellMerge and passes the Document instance to add a third example. Like the name states, it shows how to merge cells in a table:
document.LastSection.AddParagraph("Cell Merge", StyleNames.Heading2);
var table = document.LastSection.AddTable();
table.Borders.Visible = true;
table.TopPadding = 5;
table.BottomPadding = 5;
table.AddColumn();
table.AddColumn();
table.AddColumn();
table.Rows.Height = 35;
var row = table.AddRow();
row.Cells[0].AddParagraph("Merge Right");
row.Cells[0].MergeRight = 1;
row = table.AddRow();
row.Cells[0].MergeDown = 1;
row.Cells[0].VerticalAlignment = VerticalAlignment.Bottom;
row.Cells[0].AddParagraph("Merge Down");
table.AddRow();
See Tables class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
Height and the padding properties are of the type Unit (see Document Object Model / Formats / Unit for more information).
Again, a table is added to the last section. Its borders and padding are initialized the same way as in the last example. Also the row and cell count and the row height are the same. But now, the first cell of the first row is defined to merge one cell to the right and gets an appropriate text. Same is done with the first cell of the second row, but merging down here. The vertical alignment is set to Bottom.
For information about merging cells see Document Object Model / Contents / Tables.
Adding a chart
The third chapter of the content section is added by Charts.DefineCharts()
.
It is started now by Documents.CreateDocument()
which also passes the Document instance.
The heading is added like it was done in Adding paragraphs.
The sample chart is added by this code:
var paragraph = document.LastSection.AddParagraph("Chart Overview", StyleNames.Heading1);
paragraph.AddBookmark(BookmarkName);
document.LastSection.AddParagraph("Sample Chart", StyleNames.Heading2);
var chart = new Chart();
chart.Left = 0;
chart.Width = Unit.FromCentimeter(16);
chart.Height = Unit.FromCentimeter(12);
var series = chart.SeriesCollection.AddSeries();
series.ChartType = ChartType.Column2D;
series.Add(1, 17, 45, 5, 3, 20, 11, 23, 8, 19);
series.HasDataLabel = true;
series = chart.SeriesCollection.AddSeries();
series.ChartType = ChartType.Line;
series.Add(41, 7, 5, 45, 13, 10, 21, 13, 18, 9);
var xSeries = chart.XValues.AddXSeries();
xSeries.Add("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N");
chart.XAxis.Title.Caption = "X-Axis";
chart.YAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.HasMajorGridlines = true;
chart.PlotArea.LineFormat.Color = Colors.DarkGray;
chart.PlotArea.LineFormat.Width = 1;
document.LastSection.Add(chart);
See Charts class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
Width and Height are properties of the type Unit (see Document Object Model / Formats / Unit for more information). To the Left property also values of the type Unit can be assigned.
Color is a property of the type Color (see Document Object Model / Formats / Colors for more information).
After adding headings, the chart is created. Its left position is set to zero, which is the default anyway. Its size is set to 16 x 12 centimeters. Two data series are added to the chart, the first one displayed as simple bars (Column2D) and the second one as a line. For the first one also HasDataLabel is set to true, so the data values are printed on the bars.
With AddXSeries the descriptions for the data on the x-axis are added. Also, a caption is added to the x-axis. The y-axis is defined as having major tick marks at the outside and to show major grid lines. A default interval of 5 will be used for them. The line format of the plot area is set to 1 point width and dark gray. This affects the border of the plotted coordinate system.
Finally, the chart is added to the last section, as it was created, but not added by now.
To learn about using styles see Document Object Model / Document / Formatting.
For information about adding charts see Document Object Model / Contents / Charts.
To learn about setting the size and position see Document Object Model / Formats / Sizing & positioning.
To explore the possibilities of formatting the line format see Document Object Model / Formats / Borders & line format.
Rendering the document
When the document creation is finished, rendering starts. This sample writes the document to an MDDDL file first. This line can be omitted if you only want to create a PDF or RTF file.
// Write MigraDoc DDL to a file.
MigraDoc.DocumentObjectModel.IO.DdlWriter.WriteToFile(document, "MigraDoc.mdddl");
};
See Program class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
MDDDL (MigraDoc Document Description Language) is a text-based serialization of a MigraDoc document. For more information and examples see see MigraDoc Overview / Grammar by Example.
Now, a PdfDocumentRenderer instance is created:
// Create a renderer for the MigraDoc document.
var pdfRenderer = new PdfDocumentRenderer
{
// Associate the MigraDoc document with a renderer.
Document = document,
PdfDocument =
{
// Change some settings before rendering the MigraDoc document.
PageLayout = PdfPageLayout.SinglePage,
ViewerPreferences =
{
FitWindow = true
}
}
};
See Program class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
These lines create the PdfDocumentRenderer instance, associate the created document with it, and set some settings of the PDF file.
Then the MigraDoc document is rendered and saved:
// Layout and render document to PDF.
pdfRenderer.RenderDocument();
// Save the document...
var filename = PdfFileUtility.GetTempPdfFullFileName("samples-MigraDoc/HelloMigraDoc.pdf");
pdfRenderer.PdfDocument.Save(filename);
// ...and start a viewer.
PdfFileUtility.ShowDocument(filename);
See Program class of the HelloMigraDoc sample in PDFsharp.Sample repository. Show resulting PDF
RenderDocument renders the MigraDoc Document instance to a PDFsharp PdfDocument instance. Save then saves the PDFsharp document to the given file.
You can ignore the other lines, as they only get the filename and start the file in a PDF viewer.
For information about rendering and saving a document to a PDF file or, alternatively, to an RTF file see Document Object Model / Document / Rendering.