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.

<%@ Page Language="C#" AutoEventWireup="true" %>

<%@ Import Namespace="Persits.PDF" %>
<script runat="server" language="c#">
void Page_Load(Object Source, EventArgs E)
{
  // Create instance of the PDF manager.
  PdfManager objPDF = new PdfManager();

  // Create new document.
  PdfDocument objDoc = objPDF.CreateDocument();

  // Specify title and creator for the document.
  objDoc.Title = "AspPDF Chapter 3 Hello World Sample";
  objDoc.Creator = "John Smith";

  // Add a page to document.
  PdfPage objPage = objDoc.Pages.Add();

  // Obtain font.
  PdfFont objFont = objDoc.Fonts["Helvetica"];

  // Draw text using this parameter string:
  string strParams = "x=0; y=650; width=612; alignment=center; size=50";
  objPage.Canvas.DrawText("Hello World!", strParams, objFont);

  // Save, generate unique file name to avoid overwriting existing file.
  string strFilename = objDoc.Save(Server.MapPath("hello.pdf"), false);
  txtResult.Text = "Success! Download your PDF file <A TARGET=_new HREF=" + strFilename + ">here</A>";
}

</script>

<html>

<body>
<form id="form1" runat="server">
<asp:Label ID="txtResult" runat="server"/>
</form>
</body>
</html>
<%@ Page Language="vb" AutoEventWireup="true" %>

<%@ Import Namespace="Persits.PDF" %>

<script runat="server" language="vb">

Sub Page_Load(Source As Object, E As EventArgs)
  ' Create instance of the PDF manager.
  Dim objPDF As PdfManager = New PdfManager()

  ' Create new document.
  Dim objDoc As PdfDocument = objPDF.CreateDocument()

  ' Specify title and creator for the document.
  objDoc.Title = "AspPDF Chapter 3 Hello World Sample"
  objDoc.Creator = "John Smith"

  ' Add a page to document.
  Dim objPage As PdfPage = objDoc.Pages.Add()

  ' Obtain font.
  Dim objFont As PdfFont = objDoc.Fonts("Helvetica")

  ' Draw text using this parameter string:
  Dim strParams As string = "x=0; y=650; width=612; alignment=center; size=50"
  objPage.Canvas.DrawText("Hello World!", strParams, objFont)

  ' Save, generate unique file name to avoid overwriting existing file.
  Dim strFilename As string = objDoc.Save(Server.MapPath("hello.pdf"), False)
  txtResult.Text = "Success! Download your PDF file <A TARGET=_new HREF=" + strFilename + ">here</A>"
End Sub </script> <html> <body> <form id="form1" runat="server"> <asp:Label ID="txtResult" runat="server"/> </form> </body> </html>

The first line creates an instance of the PdfManager object, AspPDF.NET'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.NET will generate a random one automatically. The document ID argument is rarely used.

objDoc.Title = "AspPDF Chapter 3 Hello World Sample";
objDoc.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.

PdfPage objPage = objDoc.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.

PdfFont objFont = objDoc.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.

string strParams = "x=0; y=650; width=612; alignment=center; size=50";
objPage.Canvas.DrawText( "Hello World!", strParams, objFont );

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.

string strFilename = objDoc.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:

row["FileBlob"] = objDoc.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.

...

// Build OLE DB connection string
string strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("..\\db\\asppdf.mdb");

// If you use SQL Server, the connecton string must look something like this:
// strConnect = "Provider=SQLOLEDB;Server=MYSRV;Database=master;UID=sa;PWD=xxx"

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;

// Add a new row
rowImage = tblImages.NewRow();
tblImages.Rows.Add( rowImage );

rowImage.BeginEdit();
// Save PDF file blob and in row

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

rowImage.EndEdit();
// Without this line, Update will fail.
OleDbCommandBuilder myCB = new OleDbCommandBuilder(myDataAdapter);
myDataAdapter.Update( myDataSet, "pdffiles" );

lblResult.Text = "Success! File was successfully saved in the AspPDF.mdb database.";
...

' Build OLE DB connection string
Dim strConnect As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _
Server.MapPath("..\\db\\asppdf.mdb")

' If you use SQL Server, the connecton string must look something like this:
' strConnect = "Provider=SQLOLEDB;Server=MYSRV;Database=master;UID=sa;PWD=xxx"

Dim myConnection As OleDbConnection = New OleDbConnection( strConnect )
myConnection.Open()

Dim myDataAdapter As OleDbDataAdapter = _
New OleDbDataAdapter ("select * from pdffiles", myConnection)
Dim myDataSet As DataSet = new DataSet()
myDataAdapter.Fill( myDataSet, "pdffiles" )

Dim tblImages As DataTable = myDataSet.Tables("pdffiles")
Dim rowImage As DataRow

' Add a new row
rowImage = tblImages.NewRow()
tblImages.Rows.Add( rowImage )

rowImage.BeginEdit()

' Save PDF file blob and in row
rowImage("FileBlob") = objDoc.SaveToMemory()

rowImage.EndEdit()

' Without this line, Update will fail.
Dim myCB As OleDbCommandBuilder = new OleDbCommandBuilder(myDataAdapter)
myDataAdapter.Update( myDataSet, "pdffiles" )

lblResult.Text = "Success! File was successfully saved in the AspPDF.mdb database."

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.NET environment but not in a stand-alone .NET app. Also, make sure your ASP.NET script contains no HTML tags whatsoever to avoid HTTP stream corruption.

The following code samples are almost identical to 03_hello.cs/03_hello.vb.aspx except that they contain no HTML headers and use objDoc.SaveHttp instead of objDoc.Save.

...

// Save document to HTTP stream
objDoc.SaveHttp("attachment; filename=hello.pdf");
...

' Save document to HTTP stream
objDoc.SaveHttp("attachments; filename=hello.pdf")

Click the links below to run this code sample: