Print to file

I have a VB app which produces a rather complicated printed page, with a mixture of graphics and text.  I would like to "print to a file" instead of directly to the printer.
Prior to all references to the printer object, I have:

CommonDialog1.PrinterDefault = True

And the dialog comes up with the "print to file" check box visible.  I check the box, the program continues, but still prints to the printer.

I would expect to be asked for a file name.

What is the correct way to do this?  I appreciate your help. -- Norm

Who is Participating?
Dave_GreeneConnect With a Mentor Commented:
This might help...

OpenAsTextStream Method


Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.


object.OpenAsTextStream([iomode, [format]])

The OpenAsTextStream method syntax has these parts:

Part Description
object Required. Always the name of a File object.
iomode Optional. Indicates input/output mode. Can be one of three constants: ForReading, ForWriting, or ForAppending.
format Optional. One of three Tristate values used to indicate the format of the opened file. If omitted, the file is opened as ASCII.


The iomode argument can have any of the following settings:

Constant Value Description
ForReading 1 Open a file for reading only. You can't write to this file.
ForWriting 2 Open a file for writing. If a file with the same name exists, its previous contents are overwritten.
ForAppending 8 Open a file and write to the end of the file.

The format argument can have any of the following settings:

Constant Value Description
TristateUseDefault ?2 Opens the file using the system default.
TristateTrue ?1 Opens the file as Unicode.
TristateFalse   0 Opens the file as ASCII.


The OpenAsTextStream method provides the same functionality as the OpenTextFile method of the FileSystemObject. In addition, the OpenAsTextStream method can be used to write to a file.

The following code illustrates the use of the OpenAsTextStream method:

Sub TextStreamTest
    Const ForReading = 1, ForWriting = 2, ForAppending = 3
    Const TristateUseDefault = -2, TristateTrue = -1,
TristateFalse = 0
    Dim fs  As  FileSystemObject
    Dim f, ts, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    fs.CreateTextFile "test1.txt"            'Create a file
    Set f = fs.GetFile("test1.txt")
    Set ts = f.OpenAsTextStream(ForWriting, TristateUseDefault)
    ts.Write "Hello World"
    Set ts = f.OpenAsTextStream(ForReading, TristateUseDefault)
    s = ts.ReadLine
    MsgBox s
End Sub

This link has some good info

Take Control of the Printer
You may be able to control this behavior by

Settin the PrinterDefault to False

Before opening CommonDialog1
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

The common dialog you are using is a means of getting information from the user about their intentions for the print job.  One reason for the commondialog is to allow the user to make selections specific to each print device.

The CommonDialog then stores the information that the user selected.  I beleive that you are to take some of that information and write code to allow for the user selections.

For example, if the user decides to print only pages 1 and 2 of a 5 page report.  The CommonDialog will collect the information, but then you will have to tell the printer to only print pages 1 and 2.

In the same way, you need to see if the user checked the 'Print to file' box, and if so, write code to print it to file.

The above posted link is a good reference.

npnpAuthor Commented:
Thank you both for your comments.  I am hung up on what to do if the "PrintToFile" is checked:
CommonDialog1.Flags = cdlPDPrintToFile Or etc etc ---
--other CommonDialog things go here
If cdlPDPrintToFile = True Then
-------what goes here????
   ' all my existing stuff, as for instance:
   Printer.Line (x1, y1)-(x2, y2)
   ' and such
End If
I need help at the "what goes here" place, above.
The intention is to create a file (Word document best choice??) that I can send to somebody else via an e-mail attachment.

I'm thinking a better way would be:
If cdlPDPrintToFile = True Then
    printer object is replaced by a "destination" file
   just use the printer object as is.
End If
Can that be done?
-- Norm
Sure, looks fine.  That link I gave you has something very similar.  I would look there for reference.

npnpAuthor Commented:
Here is a little test.  The two code lines which are incorrect are indicated.  What is the right way to do this please?
Private Sub Command1_Click()
   Dim strOutFile As String
   Dim myFSO As Object
   strOutFile = "C:\junk\try.doc"
   CommonDialog1.Flags = cdlPDPrintToFile
   CommonDialog1.PrinterDefault = True

   If cdlPDPrintToFile = True Then ' INCORRECT: this is a constant. How do I tell
                                                                                        if the PrintToFile box is checked?

      Set myFSO = CreateObject(strOutFile) ' INCORRECT.  How is this done?
      Set my FSO = Printer
   End If

   myFSO.currentX = and so forth and so forth

   Set myFSO = Nothing
Ok for the FSO

You want to add this 'Reference' to your project

Goto Project > References and check the box for..

"Microsoft Scripting Runtime"

Then in code...

Dim objFSO As FileSystemObject
So tell me how you are getting the data for the file...?
Here is one solution:

If CommonDialog1.flags = cdlPDPrintToFile Then
    MsgBox "Print To File"
End If
npnpAuthor Commented:
"how am I getting data for the file":
As the user progresses through the application, a number of various files are generated.  The printing process gathers all these together, and after the user enters some options, the program computes a rather complex layout which includes a lot of "line(x,y)-(x,y)" and a lot of "currentX/currentY" computed coordinates where some text is printed after some complicated formatting, the details of which are also computed.

The whole thing works just fine, and is being used by a growing number of interested people.  Now, a publisher is getting tired of using the old paste pot on the printed sheet I mail to her, and is asking for it "electronically", as for instance an e-mail attachment.  This means I must print to a file, instead of printing to a printer.

That's what I do not know how to do.  It would seem straightforward to simply replace one object (the printer) with another (the output file).  But it is more complicated than I had anticipated.
-- Norm
Just a thought....
For email you may find that generating an HTML document is an option. e.g.

dim fh as long

open "C:\YourFile.HTM" for output as #fh

' open document
print #fh,"<HTML><BODY>"

print #fh, "Print your text"; ' hold line open with ;
print #fh, " add more to a line."

print #fh, "Include graphics <img src='yourpic.jpg'>"

'close document
print #fh,"</BODY></HTML>"
close fh
Richie_SimonettiIT OperationsCommented:
npnpAuthor Commented:
Thanks to everyone.
Actually - I have come to realize that a printer object and a file are not the same kind of object, and hence my naive idea of setting my own object name to one or the other will not work.

I wanted to avoid duplicating a rather large block of printing code, one version writing to a printer, and the other version writing to a file.

I have decided to come at the problem from the other direction.  I will print to something like a pdf or jpeg file.  After which, the user can print the thing, e-mail it, or wave it at the pelicans.

I am always glad to learn something about a nook and cranny of VB I have not gotten into before.
Thanks again. -- Norm
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.