Creating Advanced PDF documents in VB


This VB tutorial builds off the last and demonstrates how you can create more advanced PDF files. It teaches you how to create a multi-page document, with page headers, footers, page numbers, shapes, and images.

In the previous tutorial we looked out how to create a simple PDF document that was one page and was only text. If you've seen many PDF documents on the web or elsewhere you know that they usually include more than just text. Fortunately we are able to do these things as well. In this VB PDF tutorial we're going to look at how to further use the mjwPDF class accomplish what we need. By the end of the tutorial you should be able to create a multi-page document that has headers, footers with page numbers, shapes, graphics, and web links.If you want, you can download the source code for this VB PDF tutorial and follow along with it.

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:

Private Sub Command1_Click()
    ' Create a simple PDF file using the mjwPDF class
    Dim objPDF As New mjwPDF
    ' Set the PDF title and filename
    objPDF.PDFTitle = "Test PDF Document"
    objPDF.PDFFileName = App.Path & "\test.pdf"
    ' We must tell the class where the PDF fonts are located
    objPDF.PDFLoadAfm = App.Path & "\Fonts"
    ' View the PDF file after we create it
    objPDF.PDFView = True
    ' Begin our PDF document
        ' Set the font name, size, and style
        objPDF.PDFSetFont FONT_ARIAL, 15, FONT_BOLD
        ' Set the text color
        objPDF.PDFSetTextColor = vbBlue
        ' Set the text we want to print
        objPDF.PDFTextOut "Hello, World! From mjwPDF ("
    ' End our PDF document (this will save it to the filename)
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.

    ' We must tell the class where the PDF fonts are located
    objPDF.PDFLoadAfm = App.Path & "\Fonts"
    ' Set the file properties
    objPDF.PDFSetLayoutMode = LAYOUT_DEFAULT
    objPDF.PDFFormatPage = FORMAT_A4
    objPDF.PDFOrientation = ORIENT_PORTRAIT
    objPDF.PDFSetUnit = UNIT_PT
    ' View the PDF file after we create it
    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:

    ' Begin our PDF document
        ' Set the font name, size, and style
        objPDF.PDFSetFont FONT_ARIAL, 15, FONT_BOLD
        ' Set the text color
        objPDF.PDFSetTextColor = vbBlue
        ' Set the text we want to print
        objPDF.PDFTextOut "Hello, World! From mjwPDF ("
    ' End our PDF document (this will save it to the filename)

And add these lines of code in their place:

' Lets add a heading
objPDF.PDFSetDrawColor = vbRed
objPDF.PDFSetTextColor = vbWhite
objPDF.PDFSetAlignement = ALIGN_CENTER
objPDF.PDFSetFill = True
objPDF.PDFCell "A centered heading", 15, 15, _
    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.

        ' Lets draw a dashed red square
        objPDF.PDFSetLineColor = vbRed
        objPDF.PDFSetFill = True
        objPDF.PDFSetLineStyle = pPDF_DASHDOT
        objPDF.PDFSetLineWidth = 1
        objPDF.PDFSetDrawMode = DRAW_NORMAL
        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:

        ' Lets draw an ellipse
        objPDF.PDFSetDrawColor = vbYellow
        objPDF.PDFSetLineColor = vbBlack
        objPDF.PDFSetLineStyle = pPDF_DASHDOT
        objPDF.PDFSetLineWidth = 1.25
        objPDF.PDFSetDrawMode = DRAW_DRAWBORDER
        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.

' Adds the page number to the current page
Private Sub AddPageNumber(objPDF As mjwPDF, pageNumber As Integer)
    Dim sPageInfo As String
    Dim fontSize As Double
    Dim margin As Double

    fontSize = 10       'Size of font to use
    margin = 40         'Size of margin (left, right, bottom)
    ' Set what we want to print for page info
    sPageInfo = "Page " & pageNumber
    ' Should save these settings and change them back for more robust code
    objPDF.PDFSetTextColor = vbBlack
    objPDF.PDFSetAlignement = ALIGN_RIGHT
    objPDF.PDFSetFont FONT_ARIAL, Conversion.CInt(fontSize), FONT_NORMAL
    objPDF.PDFSetFill = False

    ' Uncomment the below line if you want to see how our formatting works
    'objPDF.PDFSetBorder = BORDER_ALL
    ' Draw the page number at the bottom of the page to the right
    objPDF.PDFCell sPageInfo, margin,  _
        objPDF.PDFGetPageHeight - margin - fontSize, _
        objPDF.PDFGetPageWidth - (margin * 2), fontSize

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.

    ' Lets us set see the bookmark pane when we view the PDF
    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.

        'Lets add a bookmark to the start of page 1
        objPDF.PDFSetBookmark "A. Page 1", 0, 0
        'Now a bookmark half way down page 1
        objPDF.PDFSetBookmark "A1. Page 1 Halfway down", 1, 300
        'Now one at the end page 1
        objPDF.PDFSetBookmark "A2. End of Page 1", 1, 500
        'Another one a little further down and shows nesting
        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.

        'Start page 2
        'Lets add an image to page 2
        objPDF.PDFImage App.Path & "\logo.jpg", _
            15, 15, 50, 50, ""

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.

Why would I buy a PDF control?

This is a common question. Although the mjwPDF class does allow you to do some pretty cool things you still may wish to buy a control for one or more of the reasons below:

  • You need to add other images besides JPGs on the fly.
  • You want to compress or encrypt your pdf file.
  • You need code that is more optimized for memory space or processor speed.
  • You need support from a reputable company.
  • You just like spending money for fun

If you get to a point where you do need to buy a PDF control I can probably recommend one to you. Send me an email and I can help you out. Otherwise if the mjwClass works for you feel free to use it. I would still ask you to send me an email just so I know what your using it for. Thanks.

Note: The original source code for this class (before modifications) can be found here.

If you enjoyed this post, subscribe for updates (it's free)

using the "Screen.MousePointer" and mjwpdf

I am using this class successfully to generate PDFs. I have a problem. I am pulling data from a database adding customer information and parts information together forming the PDF to send to a customer. Depending on network traffic and server speed, it can take 30 seconds or more for the PDF to be generated. I need to halt and inform the user of my program that it is busy making the PDF. I tried using the "Screen.MousePointer = vbHourglass" to change the mouse pointer on the control that lanched the Class. It works on other forms but using mjwpdf, it changes to an I Bar cursor which confuses my users. Please help

Printing multiple pages

I hope someone has had the same problem and has a solution. I have checked all the posts here and have not found a solution.

I am generating a PDF report using a database from Access. I am running VB6 in Vista. All the lines are created using PDFtextOUT string,1. When I get to the end of my page I do a PDFEndPage and PDFNewPage. However, when the report is done and I do a PDFEndDoc, it aborts with a
'Run-time error '9': Subscript out of range' during one of the Subroutines in PDFEndDoc. I have been able to get it down to it only happens when I get the number of pages > 2.

Can anyone help?

Might be a fix...

I added:
And that seems to fix it for me

Class Updates

I used your code and added inches for page layouts. I was wondering if you have updated it further since posting it? There seems to be issues if you choose a unit of measure other than UNIT_PT, but I am having some trouble debugging it. I'd also like to create a function to create tables. If this is something you have already done, I'd love to see what you have.

Pdf Watermark

Hi anybody knows how to add image as watermark in pdf. plz let me know if this can be done.

Create ReadOnly PDF Files

Your vb code is just amazing. Thanks.
I have some questions about the generated PDF file (multipage files) :
- when I open one I'm always on the last page. Why ?
- on closing I always receive a question from Adobe Reader : "do you want to save your changes ?" I don't unsderstand why because I don't make any change..
Can you help me please ?

How to make a character ěščřžýáíéůú ?


How to make a character ěščřžýáíéůú ?


Need coding

Hi! all i need some coding on how to generate a invoice using VB and access data base.

thanks in advance.


Reply to comment (VB6)

If you would like to grow your experience simply keep
visiting this web site and be updated with the newest gossip posted here.

table in pdf

how to create simple table / grid in mjwPDF class??
| code | name |
| | |


Cool Stuff

Just Browsing to fine great code for my reporting stuff.

PDFSetLineWidth & PDFDrawRectangle / AdobePath

with starting the project or with a new page the 1st rectangle is drawn with LineWidth of about 1.
the lines between the text (datagrid) with PDFDrawHorLine will be hairlines.
the final rectangle will be also hairlined even with the command PDFSetLineWidth = 1.
a test with PDFDrawHorLine changes the LineWidth for that line and also for the following rectangle.
my idea would be: bold headerframe and overall rectangle and fine lines for the internal grid.

why is this, what can i do without unwanted lines in between?


the other thing is about the path of the Adobe-Reader; with different language for Windows the path for programs where different, so the default path for the searching procedure will not match.

is there a other possibility to locate the "acroRD32.exe" located at different systems at different locations?

acroRD32.exe location error

One way to fix acroRD32.exe location error, is replacing in Public Sub PDFEndDoc()

' PDFScanRepAdobe "C:\Program Files\", 0
' If wsPathAdobe <> "" Then
' iRet = Shell(wsPathAdobe & " " & PDFGetFileName, vbMaximizedFocus)
' End If


Dim oShell As Object
Set oShell = CreateObject("Shell.Application")
oShell.ShellExecute PDFGetFileName, , , "open", 1
Set oShell = Nothing

This will open the generated PDFFile with the default windows program to open pdfs

Postscript file to PDF

Awesome class! Is there a way to use it to read in a .ps file and output to a PDF?


Dear Friends,

I have to convert a formatted report into a pdf file. Whenever I am trying to add a new line, the last line is being displayed. I am giving you an example of what I am trying.
Name Address Age
Sam India 41
Vib US 32

Please help me out.

Links in PDF

How do you create text that links to another page within the PDF?



Set oRep = Fso.GetFolder(sPathBegin)
error!! is not the path.

find the line

find the line [PDFScanRepAdobe "C:\Program Files\", 0] and replace with [PDFScanRepAdobe App.Path, 0] or another address of folder


Nice stuff.

Went thru' the entire discussion but cud not find anything on "line break". How do I force a text string output to the next line if the str length is more than can be accommodated in a single line.

Much appreciated.

Good code thanks a lot!!!

Good code thanks a lot!!!

fonts in making PDF's

It's great to finaly found a way to make pdf's within vb6.
But i've got a question.
Are there more fonts available. In the directory wich was shipped by te class i only saw e few.
The strange thing however was that ik could use objPDF.PDFSetFont FONT_arial, 10, FONT_BOLD
eventhough Arial was not included. And the other way around, i could not use Helvetica, altough it was shipped.
Maybe i'm doing somthing wrong

Hope to hear from you.
André van der Plas

You should read in deeply the code

in this function
Public Sub PDFSetFont(str_Fontname As PDFFontNme, in_FontSize As Integer, Optional str_Style As PDFFontStl)

the author check the name of constant then convert to exactly file name with .afm files in the \fonts folders.
let see more or contact me for understanding

microsoft access convert to pdf and word

I have a project that ask me to make a system that allow the microsoft access to export document to pdf or word.. but in that document every page will have different ID I need to export then make it automatically seperated to its own id number then save to the chosen file..anyone know how can i do this in visual basic? please help me..

Improve PDF generation performance

I need this in order to modify a legacy application that uses Adobe Printer and it's not as fast as I expect. The application is a PDF invoice creator.

Does anyone has experience creating thousands of PDF per hour? Does this code allows me to do that?

Thanks in advance.

problems for multiline text Or Text file


This code is working fine but there is problem When i Add

objPDF.PDFTextOut "Hello, World! From mjwPDF ( fsdfksdflsdkldflfkldfldkldfdlflgsdgsdkgjsdkgjsdgsdgsdrttrutyfddgddddddddddtwey8ddddddddddwetwetyddddddddgdsgdsg"
large string

In pdf file it shows only one line text And it is up to 40 characters it does not shows remaining character

will u please help me

Thank's in Advanced


Hi, thanks for the great work on this class.
I want to know if is there any way to put a background Image on the PDF?

error 70 with windows 7

Listings in PDF work fine with Windows XP but run the program with windows 7 gives error 70, and breaks the program. Please .. help me

Multi-Line (why the extra line space)

So I am feeding multi-lines. When I send each line to the PDFTextOut sub, I am seeing an extra line of space. Does anyone know why there is an extra line of space??

Line 1

Line 2

Line 3

re: Multi-Line (why the extra line space)

So how did you feed Multi-Lines? if it is by using the y axis of the page, then just reduce the space between them.

For example:
objPDF.PDFTextOut "this is line one", 100, 50
objPDF.PDFTextOut "this is line two", 100, 70
objPDF.PDFTextOut "this is line three", 100, 90

If the 20 points are much then make that smaller.

Get picture from imagebox

Is there a way to get a picture from an imagebox and put it on the PDF?

Multiple Lines on the pdf

My head hurts... I cant figure out how to fetch the data from a list box and write them to a pdf in multiple lines like they appear in the list.
The line remains one, and goes outside the page. No vbCrLf has worked or anything. Can anyone please help?

*edit: Solved it. I just didn't read the listbox data correct.

Nope. still nothing.

I got the lines from the listbox, but from a multiline text box i cant figure it out. The line stays the same and the text goes outside the pdf document. Any help?


Good Day,

does anyone have a sample of how the watermark work?

Page "turning"


I need my application to launch and page through a PDF file. I am able to launch but not page through. Can you help with that?

Thank you very much....

Inserting Form Fields


When I create the PDF - Files I don't have all the information to put in, this have to be done later by the user. Is it possible to create form fields with your class?


Put data in a PDF using Visual Basic 2010

Can somebody tell me if his possible put data in a PDF using Visual Basic??
I have a program with a "Clients" DataBase, and i want to put the client name and adress in a PDF almost created.
His possible???
Hi opened the PDF using the "OpenFileDialog"

Put data in a PDF using Visual Basic 2010

Can somebody tell me if his possible put data in a PDF using Visual Basic??
I have a program with a "Clients" DataBase, and i want to put the client name and adress in a PDF almost created.
His possible???
Hi opened the PDF using the "OpenFileDialog"

pdf file doesnt work

I ran the basic example and when I try to open the created file in adobe reader it tells me that the file is either of the wrong type or is damaged.

Anyone else have this problem and hopefully a solution for it?

View Start at first page

How to set the PDF Document Start View at First Page, Now it start with last page.


image problem

Hi, I want to add a picture to my pdf file but it says:
Invalid JPEG marker
Cannot add image to PDF file.

Whats the problem?

PDFPrinter.PDFImage App.Path

PDFPrinter.PDFImage App.Path & "\Testing.jpg", 15, 220, 150, 100, ""

App.Path & "\Testing.jpg" is position of picture

How to draw curves using the class mwjPDF

I would like to draw simple curves. Plz. help me how to, using this class giving the piece of code.



Creating Annotation at specific position

Hi, First of all let me thank you for sharing such wonderful library. I have one request and I guess you can help me out. How can i add annotation to existing PDF at specified position? Lets say for example if i want to create a annotation at 100,100 position with size 200, 200. How can i do that? Thanks in advance.

Swiftprint code and your class

Hi There,

I created an application a while ago using Swiftprint and all was well - if was pretty complex to figure out and elaborate page manipulation ensured that I can provide all the printing the client wanted. Client phoned asking if we can store the printput to PDF... I am thinking of using your application/class to achieve this but see myself having to re-write all of that code. Is there an easier way?

Inserting Page Number and Filename at the bottom of Each Page

I would like to be able to insert a footer on each page of an existing PDF, with the file path, file name and the page number as page ## of ##.

The code above shows how insert page number on one page. Can it work through each page in the document. I am running the code from a microsoft access data base.

Thanks in advance for your help.


Page Number

PDFPrinter.PDFTextOut "Page " & PDFPrinter.PDFPageNumber ,
PDFPrinter.PDFGetPageWidth / 2 - PDFPrinter.PDFGetStringWidth("Page " & PDFPrinter.PDFPageNumber), _
PDFPrinter.PDFGetPageHeight - PDFPrinter.PDFTextHeight

Re: Inserting Page numbers

I would like to know this, too.

jump to bookmark

great job you have done. your code is very nice. But i have a question how to jump to specific bookmark whenever i open pdf file.

printform to pdf

How Do i send Form layout directly to PDF

How to convert crystal report 8.5 to PDF using VB6

hi all,

am developing a vb application that uses crystal control to show the report.on the same time i need to export the report to pdf file.


while printing invoice each copy of invoice it will add in to one pdf file.

pls help its urgent

URGENT!word file to pdf

please help me to create pdf from word file.

need urgent help..

thanks in advance

go to the microsoft website

go to the microsoft website and look for DOC to PDF converter. They have a free addin that you can add to your microsoft word. Go to and check their website. It's a free converter and very good.

Google pdfcreator.

Google pdfcreator.

help regarding vb6?

dear experts,
i wan to know whether i can upload doc files,pdf files,images etc to the database.... using vb6 as front end and back end as MS Access database.... if so plz explain me how to do it wit simple im beginner to vb6... thanks in advance... do reply if u know....

How to print PICTUREBOX

Very good class library but missing image from pictureBox. I have modify this library, but there are the problems. I getting error when i try to add image into PDF, "Insufficient data for an image".

Contact me send Sample

Help me.


Hi All Im also facing the

Hi All

Im also facing the same problem. Can anyone can help me with this? Really appreaciate it if can solve it. Im using adobe reader 9.3.


How to print PICTUREBOX

Very good class library but missing image from pictureBox. I have modify this library, but there are the problems. I getting error when i try to add image into PDF, "Insufficient data for an image".

Contact me, send Sample

Help me.



Hi, may I know anyone replied your request? Because I am also facing the same problem.

same here. any news on this

same here. any news on this one?

Other types of images?

Hi. I store images in a sql table wich are later saved to the local disk for use in VB. However, when I store these images in the DB, they lose their format, wich means even if they were originally jpgs, they become (apparently) BMPs once i call them, so i cant use this class to print said images. Is there a way to transform these files to jpg through VB? or what would i need to be able to print these images?

Hope you can help. Thanks

Image handling enhancement

I'm sending plain raw images to a PDF without text and so I needed to make sure the image was fit to the page. In the existing code, if the image size was larger than the page, the edges would be cut off. I added some code so that if the image width and height were unspecified (ie. 0), then the image would be resized to fit to the page dimensions:

In the PDFImage sub, change the following code from this:

    If w = 0 And h = 0 Then
        w = ArrInfo(0) / in_Ech
        h = ArrInfo(1) / in_Ech
    End If

to this:

    If w = 0 And h = 0 Then
        w = ArrInfo(0) / in_Ech
        h = ArrInfo(1) / in_Ech
        If w > PDFCanvasWidth(in_Canvas) Then
            w = PDFCanvasWidth(in_Canvas)
            h = w * ArrInfo(1) / ArrInfo(0)
        End If
        If h > PDFCanvasHeight(in_Canvas) Then
            h = PDFCanvasHeight(in_Canvas)
            w = h * ArrInfo(0) / ArrInfo(1)
        End If
    End If

I also added this code for centering, but it may have other undesired effects, such as not allowing an image to start off the left of the page:

Right after the following code in PDFImage:

If w = 0 Then w = h * ArrInfo(0) / ArrInfo(1)
If h = 0 Then h = w * ArrInfo(1) / ArrInfo(0)

put this code:

    If y < 0 Then y = (PDFCanvasHeight(in_Canvas) - h) / 2
    If x < 0 Then x = (PDFCanvasWidth(in_Canvas) - w) / 2

When you want to add a full page, centered image use the following command:

    objPDF.PDFImage sFilename, -1, -1

If you want to use the command like it was before, just specify the other parameters:

    objPDF.PDFImage sFilename, 0, 0, 50, 50

run-time error when using PDFSetBorder = BORDER_BOTTOM

I have the following lines of code in my project:

objPDF.PDFSetFont FONT_ARIAL, 6, FONT_normal
objPDF.PDFSetDrawColor = vbWhite
objPDF.PDFSetTextColor = vbBlack
objPDF.PDFSetAlignement = ALIGN_LEFT
objPDF.PDFSetFill = True
objPDF.PDFCell "0000000", 329, 35, 70, 9

And am getting the following error at run-time:
Run-time error 13: Type mismatch

The error is occurring on this line in the mjwPDF class module:
If PDFstrTempBorder = "LRTB" Or PDFstrTempBorder = 1 Then

And I find that if I change my pdfsetborder property to either BORDER_NONE or BORDER_ALL, the run-time error disappears, but if it is set to BORDER_LEFT, BORDER_RIGHT, BORDER_TOP, or BORDER_BOTTOM, I get the run-time error.

Any idea what would cause this? Is this is a program bug?


run-time error when using PDFSetBorder = BORDER_BOTTOM

I had the same problem. I solved it by changing PDFStrTempBorder fron string to variant. I had to do this for all these border constants.

Thank you that fixed it for

Thank you that fixed it for me as well - I changed the PDFStrTempBorder to variant, and also changed the tBorder variable to a variant type, and then all the borders worked as you would expect them to. Thanks.

Great stuff

I have a question though. How can one access an already existing pdf and pull out text and pictures. Is it just the reverse of opening it and trying to read the text or is there something else?


how to write pdf file using sql query record set

how to write pdf file using sql query record set

thanks in advance

Vikas Verma

add data of a TEXT-BOX to PDF

how do i add the data of a TEXT-BOX,in vich which the user will write a PDF file..
plzzz help man..mail me the soln.
thanks in advance

Other fonts for PDF file creation

Truly great tutorial and example for learning about creating DPF files in VB. Is there, or would you consider writing, some tutorial on how other fonts could be used for creating PDF files?

I have spent a considerable time researching available documentation on the PDF file format specifications and experimenting with your code, but so far I've had no luck (I consider myself to be a quite advanced VB expert, although real professionals would likely consider me a diletant).

Default Page

Hello, I think you have done a fantastic job with this class. I have one question though that I have not seen asked here. I am making multi-page PDF documents, but when they are opened in the acrobat reader it always opens to the end of the document. I didn't see any obvious functions to make it open to page 1. I would appreciate any help you can give me as it is very important that the document opens to page 1. Thank you, I appreciate it

Default Page Solution

Default Page Solution :


Dans la procédure PDFSetCatalog, j'ai remplacé les instructions :
"/OpenAction [3 0 R ..."
par les instructions :
"OpenAction [1 0 R ..."
et cela fonctionne ...

Congratulations to mjwPDF Class !

very good

Thank you Sergel!

Default Page Solution

Would someone please translate this to English and fill in the "....". Thanks.

Default Page Solution

I've figured it out. In the Class Module find the PDFSetCatalog Sub. In the code for PDFZoomMode you will see four statements that have "/ OpenAction [3 0 R ......" in them. Change the 3 to 1 in all four statements.

This resolved the situation. The displayed document now begins at page 1, both within the VB application and when the file is opened directly with Adobe Acrobat.

As an aside, why would the default ever be to display the document beginning with the last page?

Thank you Tom! I was going

Thank you Tom! I was going to try and figure out this out today and you saved a ton of time!

Hi ! "Thank you Tom !

Hi !
"Thank you Tom ! ..."
And no thanks for SergeL ???

Adding code 32 font

I need write PDFs with barcodes, i found the code39 afm file and put it in the Font directory, but i don't know very well how can i add the font to the project to use it.

I was reading the class methods and i think that only can use the default fonts. I modify some lines of the class to add the new font but the method PDFGetStringWidth launch this error: "Runtime error '9', subscript out of range" in the line "ArrFNT(aAsc(1)) = Int(aWX(1))".

May be the code39.afm not correct?

Please Help me !!!


Did you ever figure out how to add more fonts? We need to have a lot more font options but I have not been able to add any yet.

windows Vista

I tried your class in several examples, and has always worked, since I'm using Vista does not work anymore! crashes in this part of code:

Private Sub PDFEndStream()

Dim TempSize As Long

TempStream = TempStream & sTempStream
If dTempStream <> "" Then TempStream = TempStream & dTempStream
sTempStream = ""
dTempStream = ""

PDFOutStream TempStream, "endstream"
PDFOutStream TempStream, "endobj"
PDFOutStream sTempStream, "%FIN_OBJ/%"

StreamSize2 = 6

PDFAddToOffset Len(TempStream)
Strm.WriteLine TempStream '***** ERROR!! "Permission denied".

TempSize = Len(TempStream) - StreamSize1 - StreamSize2 - Len("Stream") - Len("endstream") - 6
ContentNum = CurrentObjectNum
CurrentObjectNum = CurrentObjectNum + 1
TempStream = ""

PDFOutStream sTempStream, "%DEBUT_OBJ/%"
PDFOutStream TempStream, CurrentObjectNum & " 0 obj"
PDFOutStream TempStream, CStr(TempSize)
PDFOutStream TempStream, "endobj"
PDFOutStream sTempStream, "%FIN_OBJ/%"

PDFAddToOffset Len(TempStream)
Strm.WriteLine TempStream

End Sub

and tells me "Permission denied".
The same code on Win XP works fine!
Do you have experience of this case?

Vista is troublesome - Get Windows 7

Where are you saving your files i.e. which folders?

Vista is notoriously troublesome because they have blocked every access by the user except the Administrator.

If you have written an application that save data to the typical windows directory i.e. such as "program files" then you may have this permission problem.

My suggestion, try saving your application to "common files" folder.

extract the fonts en the file PDF

youyou have can extracting fonts the file PDF .... PDF to Fonts..? think you.

This is helpful. But how do

This is helpful. But how do i open the current(saved) pdf file and write into it? help is much appreciated

Very nice information

Very nice information manMelissa, this article realy help me. Thanks it really looks promising! Your blog is one of the most wonderful places to visit.

Help pls, to open a pdf file and print it programatically?

Can someone help me please. Assuming I have 2 printers setup on mydesktop. Printer1 is a Black and white and Printer 2 is Color. Printer1 is the default printer. I wanted my VB Program to open the pdf file and automatically select Printer2 (Color) for printing? I am using Microsoft Print Dialog reference in my project to bring up the printer dialog box.

converting pdf file to word document in vb

Dear friends,
i need help to convert a pdf file to a word document using vb, pls can anyone help me to do this,
if so pls mail me on

Using a diferent Font

I'm using the class to create a PDF report. It works fine while I use the fonts provided with the sample code. I used TTF2PT1 utility to convert the Calibri.ttf Font to an afm file. It seems to work good. I create the PDF report well but when I open it, a message saying "The Calibri.afm Font contains an erroneous /Bbox" Of course I did the corrections to the code for it. Can anyone help what to do for solve this? I'll appreciate your best help.

Query for multiple lines in pdf

hello, ur code is great. but it writes only 1 line to pdf file. howdo i write entire vb6 form in pdf? pls guide me.


hello, ur code is great. but it writes only 1 line to pdf file. howdo i write entire vb6 form in pdf? pls guide me.

Restricting editing

Hi, I'm trying to find out how to restrict editing of the PDF.
I need this because I convert an Access Report that is A Quotation for a customer to a PDF file.I don't want someone to be able to modify the PDF file by using a PDF writer version.


Restricting editing of PDF

Restricting editing of PDF documents is mostly a waste of time if you also allow the document to be printed - as someone can simply print the document to a PDF driver and edit the resulting PDF.
The same applies to people that prevent you copying from a PDF but allow it to be printed - where is the logic in that??

To writte text into existing pdf file using VB6 platform

Could any one can help me in writting the text into a existing pdf file. I mean it to open pdf file and wriiting/ stamping a text and then saving using Visual basic 6.0 platform.


Writing to a pdf file

Assuming your pdf form allows fill-in, first open the pdf form using Adobe Reader (or other PDF reader), then populate it with unique text strings (i.e., WQPKXZ) as placeholders where you want your real text to go. Then, in your VB6 code, open the file as a binary file and replace the dummy text strings with your VB string variables. Finally, write to (create) a new PDF file containing your changes. Good luck. Example code is shown below:

'------------- below code is to populate & open a PDF Form

Open "C:\Program Files\My Application" & "\Sample_Form" & ".pdf" For Binary As #22
strBytes = Space$(LOF(22))
Get #22, 1, strBytes
'strBytes = StrConv(strBytes, vbUnicode)
Close #22
strBytes = Replace(strBytes, "WQXZName", strName)
strBytes = Replace(strBytes, "WQXZAge", strAge)

Open "C:\Program Files\My Application" & "\Sample_FormFilled" & ".pdf" For Binary As #23
Put #23, , strBytes
Close #23

'Call Shellexecute to open & display PDF form
strFile = "C:\Program Files\My Application" & "\Sample__FormFilled" & ".pdf"
strAction = "OPEN"
lngResult = ShellExecute(0, strAction, strFile, "", "", vbNormalFocus)

'------------- end of code to populate & open Form 4797 pdf

Writing to a PDF

This code is perfect except my PDF document will not allow me to save changes made to the highlighted fields. It only allows you to print a copy. Any ideas? CJF



How can i add password encryption in my pdf?
Pls. help.. thanks.

password protection

Did you get the password for PDF file


Mulit Line?

I dont know whats wrong with this class but it seem as soon as you pass any text to PDFTextoutput the class ignore or cant handle more text.

When I was tying to print a multi line text it was all one line that the PDF doesnt reconize vba.vbCrLf Vbnewline or any other type of letc.

So I tried this.

Dim MyTmpSting() as String, I as Long
MyPDFString = "Hello from mars " & VBA.vbCrLf & "How are you today? " & VBA.vbCrLf
MyTmpSting = VBA.Split(MyPDFString, VBA.vbCrLf, -1, vbTextCompare)

For I = 0 to 2
On error goto hell
objPDF.PDFTextOut MyTmpSting(i)
next i

Just an example

Still can only get the One line ""Hello from mars" all other text in the array is ignored.

So is the problem in the class or PDF ?

Does the string need a C+ Return \n ?

Anyone have any ideas?


I hope I can help with a simplified example. Without looping, here is an example of multiple lines *not* printing subsequent lines (i.e. prints only the first line)

objPDF.PDFTextOut "This is the 1st line"
objPDF.PDFTextOut "This is the 2nd line"
objPDF.PDFTextOut "This is the 3rd line"

It seems the reason is that by default objPDF will not overwrite a line that's already been written to. The solution is to tell objPDF to go down to the next line.

objPDF.PDFTextOut "This is the 1st line", 15, 1
objPDF.PDFTextOut "This is the 2nd line", 15, 2
objPDF.PDFTextOut "This is the 3rd line", 15, 3

The 2nd parameter "15" is the distance to the edge of the page. Our concern here is the 3rd param which is the line number, it increments by 1 line after every TextOut. You can now make a loop that increments the 3rd param after each objPDF.PDFTextOut.

Thanks to the author of this class. mjwPDF is trully a one of a kind gem!

Thank u so much.Thanks to the

Thank u so much.Thanks to the author of this class

RichtextBox to PDF

Hey there
Thanks a lot for such a wonderful stuff you provide.
I'm making a small software wherein I have a RichTextBox. The user's gonna write anything in the RTB, any sort of content.

Now What I need is that the user should be able to save the RTB content into a PDF file, on click of a button.
Also, I don't want the pdf to open automatically, instead it should just save at a particular location provided.

Can you pls pls help me with it....

Thanks in anticipation

Email me at:

Hi your codes are great

Hi your codes are great however I am just wondering on how to fully justify the text on the cell?
I have used the left, right and center, is there a way to justify it on both left and right?. Thanks.

Cutting dependancy on fonts

This works great. within in seconds it was just what I need and very neat.

I have just one question is it possible to cut out the dependancy on the fonts provided. I notice that Arial is not one of the .afm files provided but everything still works fine when it's called, and this is the only font I need. I'm looking to distribute my file in an excel .xla with as few external files as possible.


How to create bookmark using bookmark root


I have problem with creating bookmarks in pdf file.
I am using below code to create from word document pdf file and want to get bookmarks in pdf based on headers.

Set AcroApp = CreateObject("AcroExch.App")
'Create an instance of a doc
Set ADoc = CreateObject("AcroExch.PDDoc")
'create another instance, which will be used to store the new docs.
Set ADocNew = CreateObject("AcroExch.PDDoc")
Set AvDoc = CreateObject("AcroExch.AVDoc")

'open the first PDF
b = AvDoc.Open(sDirPDF & "\" & aPDFs(0), "")
Set ADocNew = AvDoc.GetPDDoc
'set viewmode to show bookmarks (3=PDUseBookmarks)
AvDoc.setviewmode (3)
'set initial value of bookmarkindex
nIndex = 0

For i = 1 To UBound(aPDFs())
'open next pdf
b = ADoc.Open(sDirPDF & "\" & aPDFs(i))
'get number of pages of the new PDF
iPgLen = ADocNew.getnumpages - 1
'insertpages (after_which_page,what_to_insert,startpg,endpg,???)
b = ADocNew.insertpages(iPgLen, ADoc, 0, ADoc.getnumpages, 0)
'Get JavaScript object
Set jso = ADocNew.GetJSObject
'Set the root of the bookmark tree
Set BMR = jso.BookmarkRoot

BMR.PDFSetBookmark Left(aPDFs(i), Len(aPDFs(i)) - 4), "this.pageNum=" & ADocNew.getnumpages - ADoc.getnumpages, Index
'increase bookmarkindex
nIndex = nIndex + 1
'close the last PDF that was opened - we don't need it anymore
'get the filename of the next PDF
Next i

Table of Content in word document will look like:
1. Chapter Name Specific
1.1 Under Chapter Name
1.1.1 Under Chapter Name
1.1.2 Under Chapter Name
And in pdf file should be avalaible to click on bookmark accordingly.

Do you have any idea how to solve my problem...?
Thank you and regards.

Alternative Image Support

Great tool!
I have created a system to automatically generate PDF data reports, emailed to the client before he/she gets to work :). The graphical data plots are, of course, JPGs. And so the client wants more. I am now encountering an issue where the PDF is getting to be too large! Does anyone have code to provide GIF image support? A GIF image is probably a tenth of the byte size of a JPG. Is this possible?


Hello, I am wondering what the command is for a "next" kind of button like for instance you have a game and when you click a certan button a box will come up (not a small msgbox a box that would be the same size as the main program

Please please send me the script asap

PDF in VB6

How do you take a form created in VB6 and dump it in to PDF?
My application uses a form setup as a full A4 page and is used to create invoices etc. I need to save these as PDF

Brillianr, but, how can I......

Brilliant, the answer to my problems, but there are a few things that seem logical to me but I can't find out how to do them.
1. The main problem is the time it takes to create the pdf file, is there any way to speed it up? It takes 15-25 seconds to display. Only an annoyance really not a major problem.
2. When using pdfcell with border_all the text wraps way before the end of the cell leaving masses of white space and consequently uses more lines than necessary to display the text. I got around it by turning off the border and using the polygon to draw the box. Ok but I have to fix the height of the polygon instead of it dynamically growing.
3. Leading on from 2. above, is there any way to determine how high or rather how far down the page text entered using pdfcell has gone? I need this to do 2 things, firstly determine where to place the next polygon and secondly to determine when I need to create a new page. Using pdfcell which wraps is far easier for my purposes than pdftextout.

Any pointers on the above much appreciated.

Again, a really usefull tool, thanks for your efforts.


Sending generated pdf to printer?

Does anyone know how to send the generated pdf of this class, onto a physical printer (it doesn't matter if it's the system default one).
Currently im using ShellExecute, but even if i change system default printer by hand, it ALWAYS goes to Adobe PDF printer, don't know why.

Plz help!!

pd: if your answer is, buy a control, forget it!


can anybody tell me
How to read pdf file in VB so that i can Store/insert it into database?

tables in PDF

Can any one share code for tables in PDF using this class. I need it urgent

Open pdf file in another pdf file Programatically

Hi All,
We have a requirement in our project. We want to open the PDF document which is contained by another PDF document using VB or VBScript or JS ( the Master document contains several other PDF documents).

Thanks in advance...!!!


Very good this code.

Dear ..

Congratulations... this code it's very easy to use.. simple and efficient. How I create in format PFD/A, it's possible?

Best regards.




Adding a Barcode

Can anyone tell me how to add a Barcode to the PDF? I do it in VB normally by specifying the appropriate font which is a TTF. This project uses fonts with .AFM extension. Does anyone know where i can get .AFM barcode fonts?


contact me for your solution

PDF File Creation

Thanks for the great tutorial on creating PDF files. I have created the files i want but tha last thing i need to do is add a Barcode. I have the barcode font which is a True Type font. How do i use other fonts than those provided with the Tutorial?
Thanks Again

create link to another file


Firstly, I have to say that this class it's great!!!! Congratulations!!!
But I don't know how to create a link in a PDF file to another PDF file, saved in a specific location (for example: C:\TEST.pdf)
Thanks in advance.

Ignasi From Barcelona

unable to add fonts folder in access vb editor

unable to add fonts folder in ms access vb editor, can anyone throw some light on this issue.


Questions on pdf. and VB

Qn 1:
I have Adobe Acrobat 9.0 Standard. I have a whole bunch of pdf. documents which I'd like to make interactive (or accessible). Can I do this with Adobe Acrobat 9.0 pro? If not what other software (of the Adobe Acrobat family) do I need to do this?

Can anybody tell me what program software developers use to develop Tax software? Can I do this with Visual Basic?

How to print PictureBox

Very good article and helpful. Can you just explain how to include image from pictureBox in the existing app to PDF


How can I convert a html code to PDF


I have a html document with some images bound with. How can I convert that to PDF using mjwPDF classs.

Any suggestion will be appreciated.

extend message to 2nd page

i have a long message around 1 & half pages and i want to write it into PDF.
how can i do that? Because it still appeare in 1 page.

Multi-line document

I get the same result. How can I get the long text stationed in different lines? It's staying on the same line, and.... cutting off info.


We need to create an A/P check that includes the MICR line. The question is can we use this class to print the check number, transint number and account number using the Eflring MICR font on the check we propose to produce?

truetype font and ansi characters


Is it possible to use a TrueType font ?
Is it possible tu use a font with ansi characters (dos characters) ?

Add image in PDF

Hi, I getting error when i try to add image into PDF.

I'm getting errror "Insufficient data for an image".

Anyone can help? Thank you.

Hi, Is it possible to use a


Is it possible to use a TrueType font ?
Is it possible tu use a font with ansi characters (dos characters) ?

Thank you

This is a fabulous plugin, thank you so much - you have no idea how much time this has saved.
I just spent a week trying to output vb to rtf and html and it was a nightmare.
In one evening all my outputs are pdf, brilliant.


How do i set password protection?


I've been wracking unsuccessfully for a week now to find and use a simple control or simple methods to merely programmatically convert an RTF file to PDF. Even this class doesn't do it. The best I could come up with is to send the file to my 'printer' which prints into pdf but that still opens the Save As dialog. All I want, all I need, is an object in which I pass in the fully qualified RTF filename and the object converts the rtf file to pdf format. I can even go with passing in a FileListBox that contains the list of files. Any suggestions anyone?

Do it yourself

RTF is a published spec. Read it in line by line into an array, convert as you go and smoosh it out to PDF. Certainly less than a week's work...

Bad Assumption

I'm glad this is here, it really saved my ass. But I did find a bug. On my computer Adobe is installed to drive e:\ and this software assumed it is installed to c:\program files\adobe ... instead of reading the actual install location out of the registry. I made a workaround myself using the registry, but it would be great if the author of this code could add the fix.


Change the path accordingly,

Change the path accordingly, check AppPath in the program.

I need to buy PDF Control


I need to know how can i buy PDF Control because i have trouble to convert TIFF images into PDF with BookMarking. Your Earlier response is appreciateable.

PDF Control

There is no control such like that so dont email again and again .

Convert Tiff images to PDF

I am in trouble to convert tiff images to pdf. I need your help to give me a PDF Class in VB6 that converts tiff images into PDF. I hope that u will give me a help for that.
Thanks a lot


This is great, but I do have

This is great, but I do have a question. It may just be my program but when using PDFCell routine, does it indent the first line of the paragraph automatically? and if so where in the code can I turn this off? it Seems to be happening to me.

Thanks again.


Excelent job! This is just perfect for me. It worked wonderfully!
If you dont mind i would like to use it on my program, i work in a software house in Brasil.
Thanks a lot for your code!!!


This is great, but I do have a question. It may just be my program but when using PDFCell routine, does it indent the first line of the paragraph automatically? and if so where in the code can I turn this off? it Seems to be happening to me.

Thanks again.

Word wrapping attempt

This code seems to work pretty well for me.
Also see the "multiline in a cell" reply for the required variables and how the rows and columns are handled.

Mr Admin,
Can I post my little project, which is based on this tutorials source code.
I think it'll resolve some questions that are posted. If not, maybe some else is interested.
Please email me. You have my address.

Private Sub InsertInvoiceRemarks()
Dim strRem() As String
Dim strTempRem() As String
Dim strOrigRem As String
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim Start As Integer
Dim MaxLen As Integer

i = 0
j = 0
k = 0
Start = 1

blnShowBorder = True

' max 80 chars per line
MaxLen = 40

strOrigRem = "12345 67890123456789012345 6789012345 " & _
vbCrLf & vbCrLf & _
" 6789012345 67890123456789012345 6789012345 6789012345 " & _
"6789012345 6789012345 6789012345 67890123456789012345 6789012345 67890" & _
vbCrLf & "Some more text"

'split the string at the spaces
strTempRem() = Split(strOrigRem, " ", -1, vbTextCompare)
ReDim strRem(1)
For j = 0 To UBound(strTempRem)
'check if the total line length doesn't excede your limit
If Len(strRem(i)) + Len(strTempRem(j)) + 1 <= MaxLen Then
'check for crlf
If InStr(strTempRem(j), vbCrLf) > 0 Then
Do While InStr(Start, strTempRem(j), vbCrLf) > 0
k = InStr(Start, strTempRem(j), vbCrLf)
'add the first part to the line to the new array item
strRem(i) = strRem(i) & " " & Left(strTempRem(j), k - 1)
i = i + 1
ReDim Preserve strRem(i)
Start = k
k = k + 1
'remove the first part old array item
strTempRem(j) = (Right(strTempRem(j), Len(strTempRem(j)) - k))

strRem(i) = strRem(i) & " " & strTempRem(j)
strRem(i) = strRem(i) & " " & strTempRem(j)
End If
'if it's too long then start on the next line
i = i + 1
Do While Left(strTempRem(j), 1) = " "
strTempRem(j) = Right(strTempRem(j), Len(strTempRem(j)) - 1)
ReDim Preserve strRem(i + 1)
strRem(i) = strTempRem(j)
End If
Next j

' table 1

'Resize the array
ReDim tCol(2)

'set colum proerties
b = 0
tCol(b).Left = btLeftMargin
tCol(b).Width = 75
tCol(b).FonTStyle = "B"
tCol(b).FontColor = vbMediumGray

b = b + 1
tCol(b).Left = tCol(b - 1).Left + tCol(b - 1).Width
'stretch to the maximum available width
tCol(b).Width = 500 'objPDF.PDFGetPageWidth - 15 - tCol(b).Left
tCol(b).FonTStyle = "N"
tCol(b).FontColor = vbBlack

'Row 1
objPDF.PDFSetAlignement = ALIGN_Left
'If blnShowBorder Then objPDF.PDFSetBorder = BORDER_All
b = 0
tCol(b).Txt = "Remarks"
'SetFont BaseFont, BaseFontSize, tCol(b).FonTStyle, tCol(b).FontColor
objPDF.PDFCell tCol(b).Txt, tCol(b).Left, intLineH, tCol(b).Width, btFont10

b = b + 1
For i = 0 To UBound(strRem)
If strRem(i) <> "" Then
If i > 0 Then intLineH = intLineH + btFont10

'If blnShowBorder Then objPDF.PDFSetBorder = BORDER_All
tCol(b).Txt = strRem(i)
'SetFont BaseFont, BaseFontSize, tCol(b).FonTStyle, tCol(b).FontColor
objPDF.PDFCell tCol(b).Txt, tCol(b).Left, intLineH, tCol(b).Width, btFont10
End If
Next i

intLineH = intLineH + btFont10

End Sub

Making several PDF files


I'm using your class in my program but getting a 'Subscript out off range" when i try to maken several PDF files after echtother.
I do have the objPDF.PDFinit used in my code but i still get the errors.

Is there a why to avoid this problem ?

Many thanks


multiline in a cell


is there a way to crate a multiline inside a cell or aside from wordwrapping, how to create a next line(pressing enter would cause you to type in the next line)?

here is the scenario: i am creating a manual using vb6 for my project in school and i want to convert or transfer the contents of my textbox to pdf format.

multiline in a cell

You can split your string at crlf into an array then cycle through the array(s).
I try to build table like constructions in my pdfs.
Although you can't use it as is, I hope this helps you or someone else use this fantastic PDF creator class.

'This code allows you to insert array items in to columns.
'Code is to make table like structures (HTMLish, rows then each column).
'Hopefully this code makes things easier by allowing your to copy and paste. 
'Allows me to break up my pdfs into reusable sections
Dim objPDF As New mjwPDF
'Column definitions (Not all HAVE to be used)
Private Type PDFCols
    Left As Integer
    Width As Integer
    Txt As String
    Font As String
    FontSize As Byte
    FontColor As Variant
    FonTStyle As String
    Align As String
    Border As String
End Type
'Toggle border when trying to get the layout right
Dim blnShowBorder As Boolean
'Row sizes for different size fonts. Font size + 2
Dim btFont8 As Byte
Dim btFont10 As Byte
Dim btFont12 As Byte
Dim btfont16 As Byte
'jsut to make copy'pasting code a bit easier
Dim BaseFont As PDFFontNme
Dim BaseFontSize As Integer
Dim btLeftMargin As Byte
Dim intLineH As Integer
Dim btLineSpace As Byte
'Array of above declared type
Dim tCol() As PDFCols
'array index for columns
Dim b As Byte
'Arrays to hold split strings with crlf 
Dim strMN() As String
Dim strQty() As String
Dim strType() As String
Dim strDescr() As String
Dim strKgs() As String
Dim strCbm() As String
Private Sub InsertMN()
Dim i As Integer
    'Split string values at CRLF into an array
'table 1
    'Set the amount of columns
    ReDim tCol(6)
   'Define your columns. Remember not everything has to be used.
   'Some times it beneficial to set things like, font style at the row level
'col 1
    tCol(b).Left = btLeftMargin
    tCol(b).Width = 135
'col 2
   b = b + 1
    tCol(b).Left = tCol(b - 1).Left + tCol(b - 1).Width
    tCol(b).Width = 40
'col 3
    b = b + 1
    tCol(b).Left = tCol(b - 1).Left + tCol(b - 1).Width
    tCol(b).Width = 80
'col 4
   b = b + 1
    tCol(b).Left = tCol(b - 1).Left + tCol(b - 1).Width
    tCol(b).Width = 205
'col 5
   b = b + 1
    tCol(b).Left = tCol(b - 1).Left + tCol(b - 1).Width
    tCol(b).Width = 55
'col 6
   b = b + 1
    tCol(b).Left = tCol(b - 1).Left + tCol(b - 1).Width
    tCol(b).Width = 50
' Row 1    
    'Whole row is bold and gray
    'objPDF.PDFSetBorder = BORDER_All
    'Borders are turned on when playing around with the layout
    objPDF.PDFSetTextColor = vbred
'col 1
    b = 0
   'show border when formating
    If blnShowBorder Then objPDF.PDFSetBorder = BORDER_All
    'set the column text
    tCol(b).Txt = "Marks & Numbers"
    'Enter the cell
    objPDF.PDFCell tCol(b).Txt, tCol(b).Left, intLineH, tCol(b).Width, btFont10
'col 2 
    If blnShowBorder Then objPDF.PDFSetBorder = BORDER_All
    objPDF.PDFSetAlignement = ALIGN_Right
    b = b + 1
    tCol(b).Txt = "Qty"
    objPDF.PDFCell tCol(b).Txt, tCol(b).Left, intLineH, tCol(b).Width, btFont10
'col 3  
    If blnShowBorder Then objPDF.PDFSetBorder = BORDER_All
    objPDF.PDFSetAlignement = ALIGN_Left
    b = b + 1
    tCol(b).Txt = "Colli"
    objPDF.PDFCell tCol(b).Txt, tCol(b).Left, intLineH, tCol(b).Width, btFont10
'col 4   
    If blnShowBorder Then objPDF.PDFSetBorder = BORDER_All
    b = b + 1
    tCol(b).Txt = "Description"
    objPDF.PDFCell tCol(b).Txt, tCol(b).Left, intLineH, tCol(b).Width, btFont10
'col 5
    If blnShowBorder Then objPDF.PDFSetBorder = BORDER_All
    objPDF.PDFSetAlignement = ALIGN_Right
    b = b + 1
    tCol(b).Txt = "Kgs"
    objPDF.PDFCell tCol(b).Txt, tCol(b).Left, intLineH, tCol(b).Width, btFont10
'col 6    
    If blnShowBorder Then objPDF.PDFSetBorder = BORDER_All
    b = b + 1
    tCol(b).Txt = "Cbm"
    objPDF.PDFCell tCol(b).Txt, tCol(b).Left, intLineH, tCol(b).Width, btFont10
'Row 2
   'set the font that you want to use with the lines
    objPDF.PDFSetFont FONT_ARIAL, 10
    objPDF.PDFSetTextColor = vbBlack
For i = 0 To GetBiggestArray("MN")
    On Error Resume Next
    'set the line height
    intLineH = intLineH + btFont10
'col 1     
    If blnShowBorder Then objPDF.PDFSetBorder = BORDER_All
    objPDF.PDFSetAlignement = ALIGN_Left
    b = 0
    If strMN(i) <> "" Then
        tCol(b).Txt = strMN(i)
    Else: tCol(b).Txt = " "
    End If
    objPDF.PDFCell tCol(b).Txt, tCol(b).Left, intLineH, tCol(b).Width, btFont10
' col 2     
    If blnShowBorder Then objPDF.PDFSetBorder = BORDER_All
    b = 1
    If strQty(i) <> "" Then
        tCol(b).Txt = strQty(i)
        objPDF.PDFSetAlignement = ALIGN_Right
    Else: tCol(b).Txt = " "
    End If
    objPDF.PDFCell tCol(b).Txt, tCol(b).Left, intLineH, tCol(b).Width, btFont10
'col 3   
    If blnShowBorder Then objPDF.PDFSetBorder = BORDER_All
    b = b + 1
    If strType(i) <> "" Then
        tCol(b).Txt = strType(i)
        objPDF.PDFSetAlignement = ALIGN_Left
    Else: tCol(b).Txt = " "
    End If
    objPDF.PDFCell tCol(b).Txt, tCol(b).Left, intLineH, tCol(b).Width, btFont10
'col 4   
    If blnShowBorder Then objPDF.PDFSetBorder = BORDER_All
    b = b + 1
    If strDescr(i) <> "" Then
        tCol(b).Txt = strDescr(i)
    Else: tCol(b).Txt = " "
    End If
    objPDF.PDFCell tCol(b).Txt, tCol(b).Left, intLineH, tCol(b).Width, btFont10
'col 5 
    If blnShowBorder Then objPDF.PDFSetBorder = BORDER_All
    b = b + 1
    If strKgs(i) <> "" Then
        tCol(b).Txt = strKgs(i)
        objPDF.PDFSetAlignement = ALIGN_Right
    Else: tCol(b).Txt = " "
    End If
    objPDF.PDFCell tCol(b).Txt, tCol(b).Left, intLineH, tCol(b).Width, btFont10
'col 6   
    If blnShowBorder Then objPDF.PDFSetBorder = BORDER_All
    b = b + 1
    If strCbm(i) <> "" Then
        tCol(b).Txt = strCbm(i)
    Else: tCol(b).Txt = " "
    End If
    objPDF.PDFCell tCol(b).Txt, tCol(b).Left, intLineH, tCol(b).Width, btFont10
Next i
   'set the line height for your next table
    intLineH = intLineH + btFont10
End Sub
Private Sub FillArrays()
Dim i  As Integer
' record set vaules into arrays
'    strMN = Split(rsADO!MN, vbCrLf, -1, vbTextCompare)
'    strQty = Split(rsADO!MNQty, vbCrLf, -1, vbTextCompare)
'    strType = Split(rsADO!MNVerp, vbCrLf, -1, vbTextCompare)
'    strDescr = Split(rsADO!MNOmschr, vbCrLf, -1, vbTextCompare)
'    strKgs = Split(rsADO!MNKG, vbCrLf, -1, vbTextCompare)
'    strCbm = Split(rsADO!MNCBm, vbCrLf, -1, vbTextCompare)
   'generate some rows
    ReDim strMN(6)
    For i = 0 To 5
        strMN(i) = "MN Line " & i
    Next i
    ReDim strQty(2)
    For i = 0 To 1
        strQty(i) = i + 1
    Next i
    ReDim strType(2)
    'For i = 0 To 5
        strType(0) = "cartons"
    'Next i
    ReDim strDescr(9)
    For i = 0 To 8
        strDescr(i) = "Decription Line " & i
    Next i
    ReDim strKgs(1)
    'For i = 0 To 5
        strKgs(0) = "1000.00"
    'Next i
    ReDim strCbm(1)
    'For i = 0 To 5
        strCbm(0) = "5.321"
    'Next i
End Sub
Public Function GetBiggestArray(ArrayType As String) As Byte
Dim b As Byte
    'Compare arrays to figure which one is longest.
    'Use the longest one for the FOR NEXT statement
    If ArrayType = "MN" Then
        b = UBound(strMN)
        If b < UBound(strQty) Then b = UBound(strQty)
        If b < UBound(strType) Then b = UBound(strType)
        If b < UBound(strDescr) Then b = UBound(strDescr)
        If b < UBound(strKgs) Then b = UBound(strKgs)
        If b < UBound(strCbm) Then b = UBound(strCbm)
    End If
    GetBiggestArray = b
End Function

log and text

It works wonderfully, but i have some problem with it. I want that at the beginning of the Pdf document a log should come, and then all the data which is in text1.text box, should come iin the pdf document in oder that is in text box, not only the first line.

how to print text to an existing PDF file

I have a file lmtemp.pdf (which I created in OpenOffice) that contains some data, I would like to print some text using VB to it, how can I do this so that the existing data does not get erased ??


cannot add page number

Thank you for share this wonderful code for us.
I encounter a problem while I try to add page number using your function above, but after the PDF file is created, I cannot see any page number created, I use the following code to read a text file line by line:

Open fileName For Input As #1
While Not EOF(1)
Line Input #1, StrIn
If LineCtr > 20 Then ' 85adjust for the number of lines to print per page
pageNumber = pageNumber + 1
Call AddPageNumber(objPDF, CInt(pageNumber))
LineYPos = 1
LineCtr = 1
End If
' here's the magic
objPDF.PDFTextOut CStr(StrIn), 1, CInt(LineYPos)
LineYPos = LineYPos + 1# '0.33
LineCtr = LineCtr + 1
What's wrong of my codes?


testing the above code

we appreciate your code . we tried and it worked well

Thank you ! ! !

Tks for sharing

This class is great.
Tanks for sharing your code.
Best Regards,

write output to pdf


Thanks a lot for the gr8 tutorial

I need some help. I want to write the output of my vbcode ( which includes text and numericals, like temperature: 60C) to the pdf file in different lines. could you plz tell me how to do it. can I convert excel output file to pdf file using mjwpdf


Have not tried it yet but by the comments this looks very good. I would like the following if it works.

I have a code that would allow to load the contents of the a RichTextbox to the clipboard and paste it to a VB6 created Word document (newer VB version has a custom designed to do this but i have VB6). Is there a similar posibility to do this with this creator? That will do away with a lot of formatting.

sample code

Dim sRTF As String
sRTF = "{\rtf1\ansi\ansicpg1252\deff0\deftab720{\fonttbl" & _
"{\f0\fswiss MS Sans Serif;}{\f1\froman\fcharset2 Symbol;}" & _
"{\f2\froman\fprq2 Times New Roman;}}" & _
"{\colortbl\red0\green0\blue0;\red255\green0\blue0;}" & _
"\deflang1033\horzdoc{\*\fchars }{\*\lchars }" & _
"\pard\plain\f2\fs24 Line 1 of \plain\f2\fs24\cf1" & _
"inserted\plain\f2\fs24 file.\par }"

sRTF = rt1.TextRTF 'rt1 = RichTextBox

'Copy the contents of the Rich Text to the clipboard
Dim lSuccess As Long
Dim lRTF As Long
Dim hGlobal As Long
Dim lpString As Long
lSuccess = OpenClipboard(Me.hWnd)
lRTF = RegisterClipboardFormat("Rich Text Format")
lSuccess = EmptyClipboard
hGlobal = GlobalAlloc(GMEM_MOVEABLE Or GMEM_DDESHARE, Len(sRTF))
lpString = GlobalLock(hGlobal)

CopyMemory lpString, ByVal sRTF, Len(sRTF)
GlobalUnlock hGlobal
SetClipboardData lRTF, hGlobal
GlobalFree hGlobal

'Paste into a new Word document
Dim oWord As Object
Dim oDoc As Object
Set oWord = CreateObject("word.application")
Set oDoc = oWord.Documents.Add
oWord.Visible = True