Sabtu, 20 Desember 2008

Creating Advanced PDF documents in VB

If you haven't read the introductory tutorial about Creating a PDF document using Visual Basic. Please do so first. This VB tutorial builds off the previous one. In fact to start with lets look at the code we created before:

  1. Private Sub Command1_Click()
  2. ' Create a simple PDF file using the mjwPDF class
  3. Dim objPDF As New mjwPDF
  4. ' Set the PDF title and filename
  5. objPDF.PDFTitle = "Test PDF Document"
  6. objPDF.PDFFileName = App.Path & "\test.pdf"
  7. ' We must tell the class where the PDF fonts are located
  8. objPDF.PDFLoadAfm = App.Path & "\Fonts"
  9. ' View the PDF file after we create it
  10. objPDF.PDFView = True
  11. ' Begin our PDF document
  12. objPDF.PDFBeginDoc
  13. ' Set the font name, size, and style
  14. objPDF.PDFSetFont FONT_ARIAL, 15, FONT_BOLD
  15. ' Set the text color
  16. objPDF.PDFSetTextColor = vbBlue
  17. ' Set the text we want to print
  18. objPDF.PDFTextOut "Hello, World! From mjwPDF (www.vb6.us)"
  19. ' End our PDF document (this will save it to the filename)
  20. objPDF.PDFEndDoc
  21. End Sub
Great. With this code we've done all the initializing and created a basic file. Now lets add some formatting options. Right after we set the fonts folder lets add a few lines of code that tell mjwPDF what the document layout should be like.

  1. ' We must tell the class where the PDF fonts are located
  2. objPDF.PDFLoadAfm = App.Path & "\Fonts"
  3. ' Set the file properties
  4. objPDF.PDFSetLayoutMode = LAYOUT_DEFAULT
  5. objPDF.PDFFormatPage = FORMAT_A4
  6. objPDF.PDFOrientation = ORIENT_PORTRAIT
  7. objPDF.PDFSetUnit = UNIT_PT
  8. ' View the PDF file after we create it
  9. objPDF.PDFView = True

This code sets up a standard page (letter size) in portrait orientation and our units of measure as points.

Next lets do something fun. Often times you want to add a heading to a PDF document such as "Very Important Report Blah Blah" Lets figure out how to add a heading such as this to our document. Delete the bold lines of code below:


  1. ' Begin our PDF document
  2. objPDF.PDFBeginDoc
  3. ' Set the font name, size, and style
  4. objPDF.PDFSetFont FONT_ARIAL, 15, FONT_BOLD
  5. ' Set the text color
  6. objPDF.PDFSetTextColor = vbBlue
  7. ' Set the text we want to print
  8. objPDF.PDFTextOut "Hello, World! From mjwPDF (www.vb6.us)"
  9. ' End our PDF document (this will save it to the filename)
  10. objPDF.PDFEndDoc
And add these lines of code in their place:

  1. ' Lets add a heading
  2. objPDF.PDFSetFont FONT_ARIAL, 15, FONT_BOLD
  3. objPDF.PDFSetDrawColor = vbRed
  4. objPDF.PDFSetTextColor = vbWhite
  5. objPDF.PDFSetAlignement = ALIGN_CENTER
  6. objPDF.PDFSetBorder = BORDER_ALL
  7. objPDF.PDFSetFill = True
  8. objPDF.PDFCell "A centered heading", 15, 15, _
  9. objPDF.PDFGetPageWidth - 30, 40

Let me explain what these mean. You should recognize the first line of code. It just sets the font info. Next we set the DrawColor (which in this case will be the highlight or inside color of our box). Next the text color is set and our alignment and border. The PDFSetFill=true tells mjwPDF to fill this box in when it prints out our text. The next line is what displays it all.

Let me break it down. The first parameter is simply the text we want displayed. Next we tell it how far over from the left we want the box (or cell) in our case we said 15 points over from the left. The next parameter is 15 points down from the top. Next we have to specify how wide the box is going to be. We want it to stretch all the way over to the right side of the page (minus the 15 point right border). To accomplish this we can use the mjwPDF classes PDFGetPageWidth function. This will give us the full width of the page we then subtract 30 off of it (15 for the left border and 15 for the right border), the last parameter is the height of the cell, 40 will be plenty high to accommodate our text.

If you run the code you should see your PDF pop up with a beautiful header at the top of the page.

Another fun thing is to create shapes in your PDF files. This can be used to create bar graphs or to highlight certain areas. Here is some sample code that creates a square.

  1. ' Lets draw a dashed red square
  2. objPDF.PDFSetLineColor = vbRed
  3. objPDF.PDFSetFill = True
  4. objPDF.PDFSetLineStyle = pPDF_DASHDOT
  5. objPDF.PDFSetLineWidth = 1
  6. objPDF.PDFSetDrawMode = DRAW_NORMAL
  7. objPDF.PDFDrawPolygon Array(300, 150, 400, 150, 400, 250, 300, 250)

Most the settings are self explanatory. Notice that you can specify the line style and the line width. Also notice that there is no draw square function. Instead there is a draw polygon function. It takes one parameter, but that parameter is an array of points specified in x y coordinates. X being how far from left to right to draw the point and Y being how far from top to bottom. So in our example we are specifying 4 points (the four corners of the square).

  • Point 1 is 300 pixels to the right, 150 pixels from the top
  • Point 2 is 400 pixels to the right, 150 pixels from the top
  • Point 3 is 400 pixels to the right, 250 pixels form the top
  • Point 4 is 300 pixels to the right, 250 pixels from the top.

Next lets draw an ellipse. An ellipse is simply a circle that can be squeezed either vertically or horizontally. To define it correctly we have to use some mathematical terms. If you remember from geometry class a circle has a radius. The radius is the distance from the center of the circle to the edge of the circle. An ellipse has two radiuses. One is horizontal the other is vertical. So the code for our ellipse is this:

  1. ' Lets draw an ellipse
  2. objPDF.PDFSetDrawColor = vbYellow
  3. objPDF.PDFSetLineColor = vbBlack
  4. objPDF.PDFSetLineStyle = pPDF_DASHDOT
  5. objPDF.PDFSetLineWidth = 1.25
  6. objPDF.PDFSetDrawMode = DRAW_DRAWBORDER
  7. objPDF.PDFDrawEllipse 300, 150, 75, 25
All the parameters should make sense by now. The new line is the PDFDrawEllipse call. Its a very simple call except that many times you think the x and y coordinates would correspond to the center of the circle. However, you would be wrong. Instead the first to parameters correspond to the upper left corner of the square that bounds the ellipse. The next two parameters specify the horizontal radius and the vertical radius respectively. If this seems confusing just run the program and you will see what I mean. The x & y parameters for our ellipse are the same as the x & y parameters for our first point in the square so you will see how it works. If you run the program you should see this:

Lets step back to text manipulation in PDF documents again. One thing you usually see in a professional document is the header like we did above. Another thing is usually page numbers in the footer. We can use the same logic we used for our header to add page numbers. I would like to add the numbers in the footer of the page on the right side, like most documents have. I'm not going to walk through how you can do this step by step, but here is the code for a visual basic subroutine that adds the page number to the bottom right corner of your PDF document.

  1. ' Adds the page number to the current page
  2. Private Sub AddPageNumber(objPDF As mjwPDF, pageNumber As Integer)
  3. Dim sPageInfo As String
  4. Dim fontSize As Double
  5. Dim margin As Double
  6. fontSize = 10 'Size of font to use
  7. margin = 40 'Size of margin (left, right, bottom)
  8. ' Set what we want to print for page info
  9. sPageInfo = "Page " & pageNumber
  10. ' Should save these settings and change them back for more robust code
  11. objPDF.PDFSetTextColor = vbBlack
  12. objPDF.PDFSetAlignement = ALIGN_RIGHT
  13. objPDF.PDFSetFont FONT_ARIAL, Conversion.CInt(fontSize), FONT_NORMAL
  14. objPDF.PDFSetFill = False
  15. ' Uncomment the below line if you want to see how our formatting works
  16. 'objPDF.PDFSetBorder = BORDER_ALL
  17. ' Draw the page number at the bottom of the page to the right
  18. objPDF.PDFCell sPageInfo, margin, _
  19. objPDF.PDFGetPageHeight - margin - fontSize, _
  20. objPDF.PDFGetPageWidth - (margin * 2), fontSize
  21. End Sub

Now that we know how to add page numbers how do we actually create multiple pages? Its very simple. When you are done with the first page, simply call the PDFEndPage method. Next call the PDFNewPage method to start the next page. Than just call the commands to add your text or shapes to the next page. You can do this as many times as you want. Don't forget to call the AddPageNumber method on each page though.

Another useful feature of PDF documents is adding bookmarks. Bookmarks allow you to jump from section to section in a PDF document easily. When the user views a PDF document with bookmarks, they are able to see a table of contents type tab on the left side of the screen. Note: if you want that pane to be visible by default you should add this line of code to the initializing section of your program.

  1. ' Lets us set see the bookmark pane when we view the PDF
  2. objPDF.PDFUseOutlines = True

Adding a bookmark is very easy in Visual Basic using mjwPDF. For instance lets add four bookmarks to our first page of our document. Call these anywhere in your code before you call the PDFEndPage method.

  1. 'Lets add a bookmark to the start of page 1
  2. objPDF.PDFSetBookmark "A. Page 1", 0, 0
  3. 'Now a bookmark half way down page 1
  4. objPDF.PDFSetBookmark "A1. Page 1 Halfway down", 1, 300
  5. 'Now one at the end page 1
  6. objPDF.PDFSetBookmark "A2. End of Page 1", 1, 500
  7. 'Another one a little further down and shows nesting
  8. objPDF.PDFSetBookmark "A2-Sub1.", 2, 800

The first call to PDFSetBookmark creates a bookmark labeled "A. Page 1". The next parameter is the depth of this bookmark. Note: Start your depth at 0. The last parameter is the y position to where the bookmark will move the page. So the first call created a bookmark titled "A. Page 1" that points to the top of page 1. The next call creates a bookmark titled "A1. Page 1 halfway down". It has a depth of 1 (so it will be a child under our first bookmark) and it will scroll the page 300 points down. If you run the program you will see all the bookmarks created like this screen shows.

Another necessity to learn when creating PDF documents is how to add images to them. The mjwPDF class allows you to add any .jpg images to your PDF document. If the image is in a different format you will need to convert it to .jpg before you will be able to add it to your PDF file. However, if the image is a jpeg it is very easy to add it to the PDF doc. In the sample source code included with this tutorial you will see a logo.jpg file. Below is the code to end our first page and to start our second page. On the second page we add our logo to the upper left corner of the page.

  1. objPDF.PDFEndPage
  2. 'Start page 2
  3. objPDF.PDFNewPage
  4. 'Lets add an image to page 2
  5. objPDF.PDFImage App.Path & "\logo.jpg", _
  6. 15, 15, 50, 50, "http://www.vb6.us"

The highlighted code is what adds the logo. We call the PDFImage function. The first parameter is the path to the jpeg file. The next two parameters are the x and y coordinates for the logo. The next two parameters specify the width and height of the image. These parameters can be left off and then it will just display the picture in its original size. You can also specify just the height or width and it will scale the other side of the picture to keep it in proportion. The last parameter is also optional, but it allows you to specify a web site to go to if someone clicks on the image.

If you run your program now you will see a PDF file that has all the properties of a complete PDF document. Headers, shapes, images, and page numbers. Combining all these techniques you should be able to do just about anything you would want to. Download the Advanced PDF VB Tutorial source code to see the full sample.




Tidak ada komentar: