5.1 Tutorial

This tutorial will teach you how to create your first PDF document with Polybios. The PDF document will contain two pages, one with a circle and one with a "Hello World" text.

First, you need to create a document object. This is done by calling pdf.CreateDocument() which creates a document object for you. The document object handle which is returned by pdf.CreateDocument() is then used in the following steps.

 
doc = pdf.CreateDocument()

As a second step you can set some document attributes. For example, here we set compression, encryption, page mode, and a password:

 
; set compression mode
doc:SetCompressionMode(#HPDF_COMP_ALL)

; set page mode to use outlines
doc:SetPageMode(#HPDF_PAGE_MODE_USE_OUTLINE)

; set password
doc:SetPassword("owner", "user")

After setting document attributes call doc:AddPage() to add a page to the document. The page handle returned is used in later operations on the page.

 
page1 = doc:AddPage()

To insert a new page before an existing page, doc:InsertPage(). For example, to insert page0 before page1, do the following:

 
page0 = doc:InsertPage(page1)

After creating a new page, you can set some page attributes if necessary. Here we set the page size to B5 and the orientation to landscape:

 
page1:SetSize(#HPDF_PAGE_SIZE_B5, #HPDF_PAGE_LANDSCAPE)

Now that we have set up everything we can start adding content to the page. For example, this is how we add a "Hello World" text to the page:

 
font = doc:GetFont("Times-Roman")
page0:SetFontAndSize(font, 24)
page0:BeginText()
page0:TextOut(60, 60, "Hello World!")
page0:EndText()

We can also draw graphics primitives to the page, for example a filled circle:

 
page1:SetRGBFill(1.0, 0, 0)
page1:MoveTo(100, 100)
page1:LineTo(100, 180)
page1:Circle(100, 100, 80)
page1:Fill()

When you're done adding content to your pages, you'll probably want to save the PDF document to disk. This is possible by using the doc:SaveToFile() function. Here is how to save our PDF document:

 
doc:SaveToFile("test.pdf")

Now that we are finished, we have to free all resources belonging to the document object. This is done by calling the doc:Free() method, like so:

 
doc:Free()

Note that now that we have freed the document and all of its resources, we must no longer use any handles belonging to this document. In our case this means that we must no longer access the following handles: doc, page0, page1, and font. Thus, it is a good idea to set them to Nil so that Hollywood's garbage collector can kill them:

 
doc = Nil
page0 = Nil
page1 = Nil
font = Nil

Of course, you can also declare them as local variables and then they will be eaten by the garbage collector automatically once they become inaccessible.

That's it, congratulations, you have just created your first PDF document with Polybios!


Show TOC