Cookbook/PDF files
< Cookbook
Jump to navigation
Jump to search
Revision as of 14:16, 18 August 2009 by Lenny222 (talk | contribs) (→Creating an empty PDF file: translate OO-slang :))
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
For the following recipes you need to install HPDF, a pure Haskell PDF generation library.
Creating an empty PDF file
runPdf generates a PDF file in the file system. You need to pass it four things:
- a name for the PDF file
- document information, of type PDFDocumentInfo. You can use the data generated by standardDocInfo.
- the default page size, of type PDFRect.
- a PDF Action
Let's create an empty PDF file with the name "test1.pdf". We use addPage to add an empty page.
import Graphics.PDF
main :: IO ()
main = do
let pdfFileName= "test1.pdf"
let documentInfo = standardDocInfo
let defaultPageSize = PDFRect 0 0 200 300
runPdf pdfFileName documentInfo defaultPageSize $ do
addPage Nothing
Pages with different sizes
If you pass "Nothing" to addPage, the default page size will be used for the size of the new page. We can pass it a different size (an instance of PDFRect).
Let’s create three pages, the last two pages with different dimensions:
import Graphics.PDF
main :: IO ()
main = do
let pdfFileName = "test2.pdf"
let documentInfo = standardDocInfo
let defaultPageSize = PDFRect 0 0 200 300
runPdf pdfFileName documentInfo defaultPageSize $ do
addPage Nothing
addPage $ Just $ PDFRect 0 0 100 100
addPage $ Just $ PDFRect 0 0 150 150
Drawing a simple text
To draw a simple text you need to take the following steps:
- convert the text to a PDFString using toPDFString
- create a PDFFont, passing it
- a FontName
- a font size
- create a PDFText using text, passing it
- the PDFFont from above
- a x,y-coordinate
- the PDFString from above
- create a Draw action using drawText and the PDFText from above
- draw on a given page using drawWithPage and the Draw action from above
Example:
import Graphics.PDF
main :: IO ()
main = do
let pdfFileName = "test3.pdf"
let documentInfo = standardDocInfo
let defaultPageSize = PDFRect 0 0 200 300
let pdfString = toPDFString "Hello World!"
let pdfFont = PDFFont Times_Roman 32
let pdfText = text pdfFont 10.0 10.0 pdfString
runPdf pdfFileName documentInfo defaultPageSize $ do
page <- addPage Nothing
drawWithPage page $ do
drawText pdfText