PDF files
A report, an invoice or a certificate is usually a PDF. The PDFsharp package from nuget.org makes PDF files from a program. This lesson writes a two-page report with a title, a line and a few rows of text, and reads the file back to check it. It is the third lesson in a row that uses a package, so the steps are short.
What you will learn#
- how a PDF page is measured and drawn,
- a document, a page, and an
XGraphicsthat draws on it, - fonts, brushes and pens,
- saving a file and opening it again to check it,
- what to look at before using a PDF package in a real program.
How a PDF page works#
A PDF page is a sheet with a size in points (one point is 1/72 of an inch): an A4 page is about 595 points wide and 842 high. The point 0,0 is the top left corner, and y grows downwards. Text and lines are drawn at positions in points, and each piece of text has a font and a size.
PDFsharp has the same shape as the drawing classes of the earlier lessons:
| Idea | In PDFsharp |
|---|---|
| the file | PdfDocument |
| a sheet | PdfPage, from oDocument.AddPage(NULL) |
| a surface to draw on | XGraphics, from new XGraphics().FromPdfPage(oPage) |
| a font | XFont (a name and a size) |
| what text is filled with | a brush, XBrushes.Black |
| what a line is drawn with | a pen, XPens.Black |
The steps#
They are the steps of the lessons A NuGet package, Excel files and Pictures on every system: a project file, dotnet publish, wrapassembly.ring, dnLoad and dnImportFrom. The project file names the package:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<AssemblyName>Pdf</AssemblyName>
<DebugType>none</DebugType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="PdfSharp" Version="6.1.1" />
</ItemGroup>
</Project>The program wraps only the namespaces that it uses: PdfSharp.Pdf (the document and the pages), PdfSharp.Pdf.IO (reading files) and PdfSharp.Drawing (fonts, brushes and XGraphics).
The program#
# a PDF file with a NuGet package - PDFsharp makes the pages: text, lines and a title, then the program reads the file back
# (the project is in the folder Pdf: Pdf.csproj names PdfSharp, and Empty.cs is the one source file a project needs)
load "dotnet.ring"
using { "System.IO" }
cHere = currentdir()
cDll = cHere + "/Pdf/libs/PdfSharp.dll"
cClasses = cHere + "/Pdf/classes"
# STEP 1. Get the package and the packages it needs (nuget.org the first time) with dotnet publish
if not fexists(cDll)
? "getting the package..."
system("dotnet publish Pdf -c Release -o Pdf/libs -nologo -v q > nul")
ok
if not fexists(cDll)
? "The package could not be restored. It is downloaded from nuget.org the first time, so the computer needs the internet once."
bye
ok
# STEP 2. Make Ring classes for the namespaces that the program uses
chdir("../../../tools/dotnettools")
system(exefilename() + " wrapassembly.ring " + cDll + " " + cClasses + " PdfSharp.Pdf PdfSharp.Pdf.IO PdfSharp.Drawing > nul")
chdir(cHere)
# STEP 3. Load the assembly and the classes
dnLoad(cDll)
dnImportFrom(cClasses + "/","PdfSharp.Pdf")
dnImportFrom(cClasses + "/","PdfSharp.Pdf.IO")
dnImportFrom(cClasses + "/","PdfSharp.Drawing")
func main
cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet-report.pdf"])
# 1. A document has pages, and a page is drawn with an XGraphics, like a canvas. Fonts are made with dnNew and the names of the
# parameters of the constructor; the brush and the pen are ready objects of the classes XBrushes and XPens.
oDocument = new PdfDocument()
oDocument.Info.Title = "Sales report"
oTitleFont = new XFont("Arial",22)
oTextFont = new XFont("Arial",12)
oBlack = new XBrushes().Black
oPen = new XPens().Black
aProducts = [ ["Tea",12.5,4], ["Coffee",20,3], ["Cake",8.25,2] ]
for nPage = 1 to 2
oPage = oDocument.AddPage(NULL)
oGraphics = new XGraphics().FromPdfPage(oPage)
oGraphics.DrawString([ :s = "Sales report, page " + nPage, :font = oTitleFont, :brush = oBlack, :x = 50, :y = 60 ])
oGraphics.DrawLine([ :pen = oPen, :x1 = 50, :y1 = 72, :x2 = 400, :y2 = 72 ])
nY = 100
for aProduct in aProducts
cLine = aProduct[1] + " " + aProduct[2] + " x " + aProduct[3]
oGraphics.DrawString([ :s = cLine, :font = oTextFont, :brush = oBlack, :x = 50, :y = nY ])
nY += 22
next
oGraphics.Dispose()
next
oDocument.Save(cFile)
oDocument.Close()
cBytes = new File().ReadAllBytes(cFile)
? "1. written: " + (left(cBytes,4) = "%PDF") + ", " + (len(cBytes) > 1000)
# 2. Read the file back (the mode "Import" opens it for reading its pages)
oRead = new PdfReader().Open([ :path = cFile, :openmode = "Import" ])
? "2. the file has " + oRead.PageCount + " pages, the title is '" + oRead.Info.Title + "'"
new File().Delete(cFile)1. written: 1, 1
2. the file has 2 pages, the title is 'Sales report'How it works#
Drawing#
oGraphics.DrawString([ :s = ..., :font = ..., :brush = ..., :x = 50, :y = 60 ]) writes a text with its baseline at y. DrawString has several versions, so it takes a list of the names of its parameters, and so does DrawLine. The program writes the rows of a Ring list with a loop that moves nY down by 22 points each time. A page of a real report would also check that nY does not pass the bottom of the page (about 800) and add another page when it does.
Fonts#
A font is made with the name of a family and a size: dnNew("PdfSharp.Drawing.XFont",[ :familyName = "Arial", :emSize = 22 ]). The font must exist on the computer that makes the file: Windows has Arial, and other systems have other fonts. Check how the file looks on the system where the program will run, and not only on the one where you wrote it. The program was run on Windows and on Linux, and both wrote a PDF that the program could read back. I did not look at the pages on Linux, so a program that depends on the look of a page has to be tried there.
The title of the file#
oDocument.Info.Title = "Sales report" puts a title in the information of the file, the text that a viewer shows in its title bar. Info is an object of the document, and Title is a property of it.
Closing and reading#
Save(cFile) writes the file and Close() ends the document. To check the result the program opens the file again with PdfReader.Open in the mode "Import" and asks for PageCount and the title. PDFsharp is for making PDF files and for changing and joining them, not for reading the text of a page: to search the text of a PDF you need another package.
Before you use it in a real program#
- Look at the license of a PDF package. Some are free for any use, others are free only for a small business or for open source. It is on the page of the package at nuget.org.
- Text that is long has to be cut into lines by the program, or by a helper class of the package (PDFsharp has a text formatter for it).
- Many small drawing calls are many calls over the bridge. A report of a few pages is no problem.
What you learned#
- a PDF page is measured in points, from the top left corner,
- a document has pages, and an
XGraphicsdraws on a page, - fonts, brushes and pens are objects;
dnNewwith parameter names makes a font, - a file can be opened again to check its pages and title,
- check the fonts and the license before a real use.
Exercises#
- Change the title text and the font size, and add a third page.
- Draw a rectangle around the title:
XGraphicshasDrawRectangle; look at the names of its parameters inPdf/classes/PdfSharp.Drawing.classes.ring. - Write the rows of a list of 40 products and add a new page when
nYis above 780. - Make a function
makeInvoice(cCustomer, aItems, cFile)that writes a one-page invoice and returns the total.