Hello
I get a System.NullReferenceException at style.Font.Size = 20; (beneath [Title]), when trying out the following code.
What am I doing wrong?
The project is simplified down to as little as possible, and still get the error message.
VS2019 CE, PDFsharp-MigraDoc-gdi v1.50.5147 from nuget
(please make note I'm a novice coder)
Code:
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PdfTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void createPDF()
{
// Create a new PDF document
Document document = new Document();
Section section = document.AddSection();
section.PageSetup.PageFormat = PageFormat.A4;
document.Info.Title = "Test";
document.Info.Author = "Test";
document.Info.Subject = "Test";
DefineStyles(document);
Paragraph paragraph = section.Headers.Primary.AddParagraph();
paragraph.Style = "Title";
paragraph.AddText("HEADER Test Text");
paragraph.Format.Alignment = ParagraphAlignment.Left;
paragraph = section.Headers.Primary.AddParagraph();
paragraph.Style = "Footer";
paragraph.AddText("Footer test text");
paragraph.Format.Alignment = ParagraphAlignment.Left;
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(false);
pdfRenderer.Document = document;
pdfRenderer.RenderDocument();
const string filename = "c:\\temp\\HelloWorld.pdf";
pdfRenderer.PdfDocument.Save(filename);
// ...and start a viewer.
Process.Start(filename);
}
public static void DefineStyles(Document document)
{
Style style = document.Styles["Normal"];
style.Font.Name = "Arial";
style.Font.Size = 14;
// Create a font
style = document.Styles["Title"];
style.Font.Size = 20;
style.Font.Bold = true;
style = document.Styles["DateField"];
style.Font.Size = 10;
style = document.Styles["Text"];
style.Font.Bold = true;
style = document.Styles["Footer"];
style.Font.Size = 8;
style = document.Styles["Heading1"];
style.Font.Size = 30;
}
private void button1_Click(object sender, EventArgs e)
{
createPDF();
}
}
}