Chapter 3: Your First AspPDF Application

Contents

3.1 OpenContext and OpenContextEx Methods

Our first application will create a one-page PDF document, set its Title and Creator properties, and draw the phrase "Hello, World!" in large Helvetica letters across the page.

Set Pdf = Server.CreateObject("Persits.Pdf")
Set Doc = Pdf.CreateDocument

Doc.Title = "AspPDF Chapter 3 Hello World Sample"
Doc.Creator = "John Smith"

Set Page = Doc.Pages.Add

Set Font = Doc.Fonts("Helvetica")

Params = "x=0; y=650; width=612; alignment=center; size=50"
Page.Canvas.DrawText "Hello World!", Params, Font

Filename = Doc.Save( Server.MapPath("hello.pdf"), False )

Response.Write "Success! Download your PDF file <A HREF=" & Filename & ">here</A>"
IPdfManager objPdf = new PdfManager();
IPdfDocument objDoc = objPdf.CreateDocument(Missing.Value);

objDoc.Title = "AspPDF Chapter 3 Hello World Sample";
objDoc.Creator = "John Smith";

IPdfPage objPage = objDoc.Pages.Add(Missing.Value, Missing.Value, Missing.Value);
IPdfFont objFont = objDoc.Fonts["Helvetica", Missing.Value];

String strParams = "x=0; y=650; width=612; alignment=center; size=50";

objPage.Canvas.DrawText( "Hello World!", strParams, objFont );
String strFilename = objDoc.Save( Server.MapPath("hello.pdf"), false );

lblResult.Text = "Success! Download your PDF file <A HREF=" + strFilename + ">here</A>";

The first line creates an instance of the PdfManager object, AspPDF's top-level object. The following line creates an empty PdfDocument object. The Pdf.CreateDocument method accepts a single optional argument, a document ID string. If no ID is specified, AspPDF will generate a random one automatically. The document ID argument is rarely used.

Doc.Title = "AspPDF Chapter 3 Hello World Sample"
Doc.Creator = "John Smith"

These two lines set the document's Title and Creator. These values can be viewed in Acrobat Reader under File/Document Properties/Summary. Other document properties that can be set via the PdfDocument object include Subject, Author, Keywords, Producer, CreationDate and ModDate.

Set Page = Doc.Pages.Add

This line adds a new page to the document. The Pages.Add method accepts three optional arguments: Width, Height (in PDF units, 1 unit equals 1/72 of an inch) and InsertBefore which controls the location of the new page among existing page (not applicable if the document is initially empty).

By default, the page width and height are 612 and 792, respectively, which corresponds to the standard 8.5" x 11" size.

If InsertBefore is omitted, the new page is added to the end of the document. If present, it must be a 1-based index of an existing page in the document.

Set Font = Doc.Fonts("Helvetica")

This line queries the Doc.Fonts collection for a desired font. The default parameterized Fonts.Item property expects a font name as the first parameter, and a CharSet code as the second optional parameter. Font management is described in detail in Chapter 6.

Params = "x=0; y=650; width=612; alignment=center; size=50"
Page.Canvas.DrawText "Hello World!", Params, Font

These two lines display the text "Hello World!" in size 50 Helvetica on the page. (The auxiliary string variable Params is used for readability purposes only. The second argument to Canvas.DrawText could also be an initialized PdfParam object.)

Besides the text and font arguments, five numeric arguments are being passed to the DrawText method. X and Y are always required, the others are optional in most cases. In this case, text alignment is set to center which makes the Width parameter required as well.

Filename = Doc.Save( Server.MapPath("hello.pdf"), False )

This line saves the document to disk. The first argument is required and must be set to a full file path. The second argument is optional. If set to True or omitted, it instructs the Save method to overwrite an existing file. If set to False, it forces unique file name generation. For example, if the file hello.pdf already exists in the specified directory and another document is being saved under the same name, the Save method tries the filenames hello(1).pdf, hello(2).pdf, etc., until a non-existent name is found. The Save method returns the filename (without the path) under which the file was saved.

Click the links below to run this code sample:

3.2 Alternative Save Options

In addition to the Save method looked at in the previous section, the PdfDocument object provides two more save methods: SaveToMemory and SaveHttp.

3.2.1 Saving to Memory

The SaveToMemory method does the same as Save but it produces a memory array as opposed to disk file. This memory array can be saved directly in the database as a BLOB by simply assigning the return value of SaveToMemory to a recordset object, as follows:

rs("FileBlob").Value = Doc.SaveToMemory

The following code sample does the same as the previous one, except that it saves a resultant PDF file in the database as a BLOB. For the sake of brevity, only the bottom portion of the code is shown.

...

Connect = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" & Server.MapPath("..\db\asppdf.mdb")
Set rs = Server.CreateObject("adodb.recordset")
rs.Open "PDFFILES", Connect, 2, 3
rs.AddNew
rs("FileBlob").Value = Doc.SaveToMemory
rs.Update
...
String strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("..\\db\\asppdf.mdb");
OleDbConnection myConnection = new OleDbConnection( strConnect );
myConnection.Open();

OleDbDataAdapter myDataAdapter = new OleDbDataAdapter ("select * from pdffiles", myConnection);

DataSet myDataSet = new DataSet();
myDataAdapter.Fill( myDataSet, "pdffiles" );

DataTable tblImages = myDataSet.Tables["pdffiles"];
DataRow rowImage;
rowImage = tblImages.NewRow();
tblImages.Rows.Add( rowImage );

rowImage.BeginEdit();
rowImage["FileBlob"] = objDoc.SaveToMemory();
rowImage.EndEdit();

OleDbCommandBuilder myCB = new OleDbCommandBuilder(myDataAdapter);
myDataAdapter.Update( myDataSet, "pdffiles" );

Click the links below to run this code sample:

3.2.2 Saving to HTTP Stream

Yet another option is to save to an HTTP stream via the SaveHttp method. This method enables your Web application to send a PDF document directly to the client browser without creating a temporary copy on the server's hard drive for better performance and security.

The SaveHttp method takes two arguments, a value for the Content-Disposition header, and optionally a value for the Content-Type header. The latter value is "application/pdf" by default.

The Content-Disposition header contains the name of the PDF file as displayed to the user in the File Save As dialog box. The format for this header is:

"filename=myfile.pdf"

or

"attachment;filename=myfile.pdf"

The second version makes a browser prompt the user to save the file to disk instead of opening it in-place.

SaveHttp can only be used in an ASP/ASP.NET environment as it calls the Response.BinaryWrite method internally. If you use this method from an ASP.NET application, you must enable classic ASP compatibility mode, as follows:

<%@ Page aspCompat="True" other attributes %>

Also, make sure your ASP/ASP.NET script contains no HTML tags whatsoever to avoid HTTP stream corruption.

The following code samples are almost identical to 03_hello.asp/.aspx except that they contain no HTML headers and use Doc.SaveHttp instead of Doc.Save. Click the links below to run this code sample: