Creating PDF files in Visual Basic

Level:
Level2

PDF stands for portable document format. It is a format that every operating system on virtually any computer can read. Its become the default standard for transferring and viewing files in an easy way. The problem is that Visual Basic has no built in VB6 PDF functions. Because of this it has been very hard in the past to create PDF files from VB. Hopefully by the end of this Visual Basic Tutorial, PDF creation will be an easy thing for you to understand and do first hand.

PDF is a pretty complex data format. Because, of this usually you have to buy a third party control from someone who's invested a large amount of time in navigating through the PDF format and written an easy way for you to access it. This tutorial explains how you can create a simple PDF file without a third party control. If you run into limitations down the road you might still end up having to purchase a control. However, you will then know exactly what to look for in the control and know how much you are willing to spend to get the functionality you need. Hopefully you won't even need to purchase one. If there is something you are trying to do, add a comment here or in the forum, and we will try to help you with it. Also there is a followup to this tutorial: Creating Advanced PDF files using Visual Basic. It goes a lot more in depth into things like adding pictures, headers, page numbers and bookmarks.

The first thing you will need to do to follow this tutorial is to download the mjwPDF class and the PDF fonts. This class allows you to easily create PDF files and is what we will be using in this Visual Basic Tutorial. PDF creation is a snap once you've downloaded the class. Now copy the class and the fonts folder to the area where you have your project saved.

If you created a default project (Project1.vbp) and didn't change the name of the form it creates (From1.frm) your project folder should look like this once you've copied the mjwPDF class and the Fonts folder.

If this seems confusing, just download this VB PDF tutorial source code. It has everything zipped into one location for you to see how to set it all up.

Now that the fonts folder and mjwPDF class are in the right spot we need to add the mjwPDF class to our project:

  1. Select Project -> Add File from the menu bar (or hit ctrl-D)
  2. Select the mjwPDF class and click Open

Great. Now add a button to your form. Double click on it and add the following code to it:

  1. Private Sub Command1_Click()
  2.     ' Create a simple PDF file using the mjwPDF class
  3.     Dim objPDF As New mjwPDF
  4.    
  5.     ' Set the PDF title and filename
  6.     objPDF.PDFTitle = "Test PDF Document"
  7.     objPDF.PDFFileName = App.Path & "\test.pdf"
  8.    
  9.     ' We must tell the class where the PDF fonts are located
  10.     objPDF.PDFLoadAfm = App.Path & "\Fonts"
  11.    
  12.     ' View the PDF file after we create it
  13.     objPDF.PDFView = True
  14.    
  15.     ' Begin our PDF document
  16.     objPDF.PDFBeginDoc
  17.         ' Set the font name, size, and style
  18.         objPDF.PDFSetFont FONT_ARIAL, 15, FONT_BOLD
  19.        
  20.         ' Set the text color
  21.         objPDF.PDFSetTextColor = vbBlue
  22.        
  23.         ' Set the text we want to print
  24.         objPDF.PDFTextOut _
  25.             "Hello, World! From mjwPDF (www.vb6.us)"
  26.    
  27.     ' End our PDF document (this will save it to the filename)
  28.     objPDF.PDFEndDoc
  29. End Sub

Lets walk through this code so we know what it does. I've added comments to explain each section. First we create the mjwPDF class object. We set a title for the PDF file. This will show up if someone looks at the file properties for this PDF document. Next set where the document will be saved. We are just saving it as test.pdf in the same folder as our program is. Next we tell it where the fonts folder is located. This is why we had to copy that folder to our running directory. The class uses this information to add those fonts to the file when they are needed.

The next line (line 13) is completly optional. By specifying true, our PDF document will be opened once we finish writing to it. Obviously on many applications you simply want to save the document and not show it to the user. If this is the case set this property to false.

Starting at line 16 we get into the meat of this Visual Basic tutorial. PDF file creation is a simple step by step process. First we decide what font we want. What size it is and if we want any special characteristics (like bold or italic). Next we set the color we want our text to be. Lastly we call the PDFTextOut to actually write the text to the PDF file. NOTE: I am saying write the text to the PDF file, but really its simply stored in a buffer until we call PDFEndDoc. We do this next and that is when all of the buffer is actually saved to the filename you specified in line 7. Also, since we set the PDFView property to true the PDF file is then opened for us automatically and we can see a simple file with our text added to it.

Download the VB PDF tutorial source code and have fun! Please leave comments below as to how well this worked for you. Also, I have written another tutorial: Visual Basic and Advanced PDF Documents. It goes a lot more in depth into how to add pictures, shapes, headers, hyperlinks, multiple pages, and page numbers.

Comments

Display image from Picture

Hi,
I want to display image in PDF File not from *.jpg but from obj.Picture. It's possible...

Help-me
Best Regard

Elisio

Can any one help me to make

Can any one help me to make a program to search and open specified files using vb 6.0, c++6.0 or Visual Fox Pro 6.0

alignment prblm in class file

some alignment prblm using arial font

how to solve

Thats great

Thats great

I tried this tutorial and

I tried this tutorial and it's very straight forward I will try the advanced lesson
thank you very much for this.

Stand Alone

Hi there,
Is ghostscript a requirement for the mjwPDF Class to work?
Many thanks...

Invoice Printing In PDF

Creating A invoice to visual basic as output as PDF please help to create them

textbox text into PDF

hello there.)

can some one teach me..how can i make text in the textbox appear in the PDF file..?

hope can help..

sorry my writing..?

Multi-Page PDF File

First of all, thanks for a great tool. I have the following situation. When I create a multi-page PDF file and it's presented for viewing with the Adobe Reader the document is presented at the bottom of the last page instead of at the top of the first page. Is there some way within the VB code to have the document presented at the top of the first page? Thanks.

(Note: I get the same result if I open the file directly with the Acrobat Reader. However, if I open the file directly with the NitroPDF program it is presented starting at the top of the first page.)

Multi-Page PDF File

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?

Error path not found

Hello,
I am getting a path not found error.
The debugger highlights this line:
Set oRep = Fso.GetFolder(sPathAFM)
in the routine:
Property Let PDFLoadAfm(sPathAFM As String)

Can someone help with this?

Please help me.

Hello everyone,

I am so impressed of what i saw on your example. Actually I have a project that have a similarity on your tutorial but then i saw myself so difficult because I am so new on developing a program and gaining some idea for it because i develop the program in web. My problem here is, how can i convert the .jpg file to .pdf file? Please help me sir/mam... and i really appreciate it your kindness...

thanks...

regards
silverstaind

Awesome ~ cheers !!! How

Awesome ~ cheers !!!

How about populate data into PDF template file?

Excellent Tutorials

Thank you for this great tutorial .. I can say that I have checkout many sites related to vb6 but none like this one.. good job

Greetz from Mexico

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

Accents. How?

Hi,

I like to print spanish text like "plátano" but isen't print correctly because dosen't works with accents.

How to solve?

Thanks in advanced,
Oscar.

for pdf convert

Sir, i want to write more than one lines in pdf file,please send me the code of more than one line write on pdf file.

write more than one line on pdf

Write this line in a loop:

For i = 1 To 10

Next i

OR

For Each tmp2 In tmp
objPDF.PDFTextOut _
tmp2
Next

tmp is an array

Create a PDF document with the page in landscape orientation.

Hi, can anyone please help me.
I have read the tutorial and have managed to create a PDF document and insert a JPEG picture in to the document.
This is largely due to the very good tutorial which has been posted.
I have been given a task to create a PDF document and insert numerous JPEG's. The problem is that all the imported JPEGs must be in landscape orientation. I need to change the orientation of the PDF sheetr from portrait to landscape. I have tried to change the orientation property value within the mjwPDF class but this has no effect and the JPEG continues to be in portrait form.

Can anyone shed any light on this issue, on how to change the page orientation using the mjwPDF class.

Thanks a lot.
David Curran.

Can I create a PDF File from a template

Hi

Hope anyone can help me. I wonder if I can create a PDF File using this component, but based on a template, so I just can print some text and preserve de rest of the text from the template.

thanks in advance.

Lenin

Excellent post.I want to

Excellent post.I want to thank you for this informative read, I really appreciate sharing this great post. Keep up your work. great ,thanks

Good

This is a very goo example.

Thanks a lot...

I must salute the efforts you have put into this website... This article is very helpful...

thanks for the tutorials. it

thanks for the tutorials. it helps. its additional info that i could teach to my students

Excellent

Kode-kode yang bagus, terima kasih atas tutorialnya. Sangat membantu sekali.

convert other fonts

how to convert other windows standard fonts to your *.afm format ?
you have any tool for this conversion ?

You are my Mentor Dr.

I have been following your VB tutorial and your explanation is so wonderful. It has never be explained to me like this before. I hope be very good in it with your teachings.
Thanks alot Doc.
Godwin, Nigeria

Thank you

This is very good.

And rather than complain or ask someone else to help sort out the more minor issues - I did it myself.

Great work, fellah!

Sceadugengan...

good , But ...

that is good module
but i modefied some thing on it i made it not open adobe reader after generating the file .

thank you

terima kasih.....

line break in pdf

how to introduce line breaks in the pdf that is created using this code?

database

How do I make my database report to be displayed in pdf format, please help me.

Thanks for your anticipated support,
Vwede

Search capability in pdf file from VB

Hi,
After converting text to pdf file from VB, I need to open pdf file with search option. This gives an error "There was an error opening the document. bad parameter.
Thanks,
Archana

Adding text line by line

This porgram is really good! unfortunately, when i add additional text on the second line and so forth it did not write the value of the . PDFTetOut!
I will create textboxes and pass the value to the PDFTextOut each line but it is not working! I really need help.. Thanks

Reg Use of this class

Hi,

I want to use this class in my VB application to generate PDF reports.
Please let me know if i can use it or not. I will be very thankful to you.
Waiting for ur response.

Thanks,
Abhishek

PDF Draq

Nice Class, it works great.

Having trouble with something. I can write any text with out any trouble but if I Draw some lines and then I start again with text. This last one would not be display in the PDF no error, no massage. It´s like if I haven´t sent any pdftextout.

suggestions?

sir good tecahing in our

sir good tecahing in our people

Figure it out

The problem was with de objpdf.pdfdrawrectangle, if I draw the rectangle with .pdfdrawlinehor and .pdfdrawlinever problem solved

thank anyway.

view PDF as text

i have a question: how to read/preview/convert pdf as text file like some application preview pdf file?

And Format PDF - PDF-A

It's amazing this code...

This file is create in format PDF, of course.

How I do to create in Format PDF-A?

Thanks

Silvio

how to get the path from C:\"my folder name"

hi...i quite impress with your coding..so far i already tested it and it work properly!
i want to apply your code in my program but the problem is i already has word document and once user click button..it will automatic generate the pdf file from that word file.
Can you help and teach me on how to make it work??
thank you for ur co-operation..

Regards,
siti

need help

good day siti..)

i am amature programmer..)..i very need your help to solve this problem..

i do not know why...when i trying to run the program which is create the PDF using VB6, the PDF document did not appear..they did not tell any error on coding, no debug..

i am just follow the whole step by step..unfortunately it is not working..

if you know something wrong somewhere with this..let me know..i appreciate it..

please..

PDF Document

Its fine, Really a nice one. But it doesn't show document in more than one line.
objPDF.PDFTextOut "My Second PDF File" objPDF.PDFTextOut "My Second PDF File"
I have written it two times still it doesn't work
how to solve?

hei there is an error on

hei there is an error on line 24 they say method or data member not found what should i do

Print form to pdf

It is great tool ,

I did it successfully,

My Question is:

I want to print the form to pdf.

Thank you

Database

Hi There,

What a great class!!!! One question.

I have data in a acess database that I want t write to pdf.
I will get my data like this:
Dim rs as New Recordset
rs.open "Select * from Clients", CL, 1, 2
Do while not rs.EOF
this is where I need Help
rs.movenext
loop

Can You Please assist?

Regards,

Gert

I want a c#.net code to read

I want a c#.net code to read text from pdf file can you help me

Coordinates

Hi,
All coordinates in the examples use the top left as 0,0.
I want to use it to produce a graph, so it makes it much simpler if 0,0 is bottom left.
How can I change the default?

Thank you.
jh

its urgent

Gautam here
hi,
its urgent
the tutorial was quite good but an error is occuring while i'm running it
the error is:
User-defineed type not defined

Error 91

I keep getting Error 91, it stoped whenever Strm.WriteLine TempStream is used. Any idea??

Thanks,

Little bug for lacalized computers

Hello

Here, in France, computers use the comma instead the point as the decimal séparator
in the PdfSetPageObject, you shoud use

PDFOutStream TempStream, "<< /Type /Page"
PDFOutStream TempStream, "/Parent " & ParentNum & " 0 R"
PDFOutStream TempStream, "/MediaBox [ 0 0 " & _
Replace(CStr(PageCanvasWidth(CurrentPDFSetPageObject + 1)), ",", ".") & " " & _
Replace(CStr(PageCanvasHeight(CurrentPDFSetPageObject + 1)), ",", ".") & "]"
PDFOutStream TempStream, "/Resources " & ResourceNum & " 0 R"

Thank you for your contribution, dear French friend.

It's not only in France. All the world where French, Spanish, Portuguese and Italian (at least) are spoken, use the comma
as the decimal separator.
This is hundreds of millions of people.

Now, in the age of globalization every programmer must think in terms of world, and not in terms of "home".
That's the reason why Unicode was invented.

By the way, you there, in France, invented the "Meter", "kilogram", "litre", and so on...
All the world accept that immediatly, except the english-speaking contries, who still use
the "yard", "mile", "pound", "foot", "gallon", etc. WHY ?

Your contribution is very useful, bacause in my computer the program didn't work at all, until I read your post, and you
save me hours (if not days) catching a very tiny bug, but that made all the difference.

Thank you

PDF

I would like to know If I can Open existing pdf documents and wright to them.

thanks

thanks for the pdf vb6,appreciate

Opening existing PDF

I'm trying to open an existing PDF, add a page number and print. Some comments above suggest tht mjwPDF can not open existing files. Is this correct. If so, could you please suggest a freeware or commercial VB library that supports this.

Thanks

Displayed PDF File

The generated PDF file is displayed at 37.1%. Is there a way in my code to have it displayed at a higher percentage, say 75% or even 100%. I realize the size can be changed with Adobe Reader once the file is displayed but I'd prefer to have it presented originally at a larger size. Thanks.

BTW, this is a great tool -- great function and very easy to understand and use.

Display PDF File

I've looked at objPDF.PDFSetZoomMode. There are options for FULLWIDTH and REAL which produce a 100% display. However, for my application these create something that is too wide. There doesn't appear to be a capability for setting a percentage such as that in Adobe Reader. I need 50% or 75%. Any way to do that in code?

Display PDF File

It would be beneficial to have something like objPDF.PDFSetZoomMode = ZOOM_PERCENT, X -- where "X" is the desired percentage for the display.. If done I assume that the specified percentage would have to be one of those supported by Acrobat Reader.

Rich Text Content in PDF

I have gone through your tutorial. Nice.
I need to create PDF with Rich Text.
Bold, Italic, Lines etc.,

Im getting "there was an error opening this document"

Hi

Im getting "there was an error opening this document" this file cannot be found...i have saved the pdf class in the same folder where i saved my project file....please give me a solution...im using the VB 6 version.
Thanking u

PDF internal link

Thanks for this class. It will be so usefull.

Is there a way to create a link that points to another page in the same PDF document?

Merci encore,

Daniel

Multiple Line to be printed

Hi,

It is working wonderfully, but i am facing problem while inserting logo in beginning fo the pdf doc and then data in multple lines from a text box.

Else it is perfect.

can you post the pdf file

can you post the pdf file that is created. I got the class to create the file but Acrobat shows there is problem reading the document. I would like to find what the error is by comparing your pdf file with mine.

Thanks for the excellent article.

Never mind. I corrected the

Never mind. I corrected the errors and converted it to VS 2008.

is it possible the contents

is it possible the contents of the pdf are from data in database??
thanks

For text file to PDF

Hi,
I am new to this PDF class that it's what I am looking for. I have two questions:
1: I have a text report created using Notepad, Now I want to open it directly using this PDF class object, how to do it?
2: I have a word file with images inside it, how can I show them in PDF?

Thanks!
Andraw

Hi, I read through the text

Hi,
I read through the text file line by line and write to pdf file, it works fine.
At first I was failed because I tried to open the text file then use READALL to write the whole contents in text file to pdf, the error is overflow.

I have a question, I use LANDSCAPE for page orientation, line space use 1.0, in this condition there are only 20 lines allowed each page. How can I control lines of each page? how can I make sure the pdf file is opened with 100% zoom? now it's 74%.

Thanks!

Neat

Hi. Just to let you know I appreciate your making this code available.
Worked "out ot the box" and I simply modified it slightly to automatically locate the location of the Program folder.
A quick question: does it handle mixing text and graphics in complex arrangements?
Best regards
Howard

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may post block code using <blockcode [type="language"]>...</blockcode> tags. You may also post inline code using <code [type="language"]>...</code> tags.

More information about formatting options