ASP.NET Image to PDF with VB.Net

This tutorial will discuss how to use the PDFSharp library on images. Specifically, it will cover how to do simple JPG to PDF conversion using PDFSharp in VB.NET. This has a lot of applications in ASP.NET implementations, such as converting a document online that contains either a pure image or both text and images.

To catch up, you might want to read the following introductory tutorials on the use of the PDFSharp library in generating PDF documents in ASP.NET using VB.NET language:

“Using the PDFSharp Library in ASP.NET 3.5 with VB.NET” – https://www.aspfree.com/c/a/.NET/ASPNET-35-PDF-Creation-Using-the-PDFSharp-Library-in-VBNET/  

“PDFSharp: HTML to PDF in ASP.NET 3.5 using VB.NET” – https://www.aspfree.com/c/a/.NET/PDFSharp-HTML-to-PDF-in-ASPNET-35-using-VBNET/  

For simplicity, let’s use a JPG image type, although the concept and principles can be extended to other image types. If you are ready, let’s get started.

Case Example: Converting JPG to PDF Web Application

For example, suppose you are planning to develop an ASP.NET application that will let the user upload a JPG image; your application will receive the image, and then convert it to PDF. Then, after conversion, the user can download the link to the PDF file that now contains the JPG image as its content.

The application can be broken down into two stages:

1. The file upload mechanism.

2. A VB.NET script that will use the PDFSharp library to convert the uploaded JPG image into a PDF file.

Once the conversion is complete, the hyperlink will be outputted to the browser so that the user can download it.

Getting Started: Create a Visual Web Developer Web Project

Let’s use Visual Web Developer to create this website. Follow the steps below.

Step 1. Launch Visual Web Developer and then click Create Website: http://www.dotnetdevelopment.net/tutorials/how_to_create_a_project.jpg

Step 2. In the above screen shot that guides you in creating this website project, let’s name the project: jpgtopdf

Then select “File System” for “location” and “Visual Basic” as the language.

Step 3. Let’s create the systems that will let the user upload files. Go to the Default.aspx source code view, and then click and drag “FileUpload” web control, which is found in Toolbox -> Standard

After the file upload code, put in some <br />, and then let’s add a validator that will ensure that the file uploaded is of  the jpg type:

<asp:RegularExpressionValidator ID="FileTypeValidator" runat="server" ErrorMessage="File type not allowed: Accept jpg image type only" ValidationExpression="^.+.((jpg))$" ControlToValidate="FileUpload1"></asp:RegularExpressionValidator>

Finally, drag a submit button control. Below is the complete Default.aspx source code:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <asp:RegularExpressionValidator ID="FileTypeValidator" runat="server" ErrorMessage="File type not allowed: Accept jpg image type only" ValidationExpression="^.+.((jpg))$" ControlToValidate="FileUpload1"></asp:RegularExpressionValidator>
        <br /><br />
        <asp:Button ID="Button1" runat="server" Text="Convert this JPG to PDF" />
    </div>
    </form>
</body>
</html>

Of course, when the user clicks the submit button, the VB.NET script should upload the file. Below is the source code of Default.aspx.vb:

Imports System.Data
Imports System.IO
Imports System.Web
Imports System.Configuration
Imports System.Web.UI
Imports System.Web.Security
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If Page.IsValid Then
Dim filereceived As String = FileUpload1.PostedFile.FileName
Dim filename As String = Path.GetFileName(filereceived)
Dim fileuploadpath As String = "L:aspdotnetprojectsjpgtopdfUploadedImages"
FileUpload1.PostedFile.SaveAs(Path.Combine(fileuploadpath, filename))
End If
End Sub
End Class

Code discussion

Since you are accepting image uploads from the user, and the above script says that the uploaded images are saved to the /jpgtopdf/UploadedImages path in your website, you need to create a new folder in your website called “UploadedImages.” You should also create a folder named “ConvertedtoPDF,” where PDF files are saved after processing. Below are the files and folders in your website:

For details about the discussion regarding the file upload web control in ASP.NET, please refer to this tutorial: https://www.aspfree.com/c/a/ASP.NET/ASPNET-35-File-Upload-Tutorial-Using-VBNET-/  

{mospagebreak title=Integrate PDFSharp Library Files into Your Project}

You need to read this page on how to add the PdfSharp.dll to your existing project: https://www.aspfree.com/c/a/.NET/ASPNET-35-PDF-Creation-Using-the-PDFSharp-Library-in-VBNET/. Just skip the website project creation steps, as they were discussed earlier. Just add the PdfSharp.dll to the project. After adding it, it will appear inside the Bin directory of your website.

Let’s try creating the most basic JPG to PDF processing script using the PDF Library. Go to the Default.aspx.vb source code, then copy/paste the VB.NET script below:

Imports System.Data
Imports System.IO
Imports System.Web
Imports System.Configuration
Imports System.Web.UI
Imports System.Web.Security
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

‘Namespaces required by PDFSharp Library and features

Imports PdfSharp
Imports PdfSharp.Drawing
Imports PdfSharp.Drawing.Layout
Imports PdfSharp.Pdf
Imports System.Diagnostics

Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If Page.IsValid Then
Dim filereceived As String = FileUpload1.PostedFile.FileName
Dim filename As String = Path.GetFileName(filereceived)
Dim fileuploadpath As String = "L:aspdotnetprojectsjpgtopdfUploadedImages"
            FileUpload1.PostedFile.SaveAs(Path.Combine(fileuploadpath, filename))

‘Process uploaded JPG by embedding it to a PDF file
‘Initiate a PDF document

Dim document As New PdfDocument()
Dim page As PdfPage = document.AddPage()

‘Load the Xgraphics class required when working with images

Dim gfx As XGraphics = XGraphics.FromPdfPage(page)

‘Load the uploaded JPG image

Dim image As XImage = XImage.FromFile("L:aspdotnetprojectsjpgtopdfUploadedImages" & filename)

‘Use original dimensions, more details here: http://bit.ly/hbZjiZ  

Dim x As Double = (250 – image.PixelWidth * 72 / image.HorizontalResolution) 2

 

‘Write the image to PDF

gfx.DrawImage(image, x, 30)

‘Define the filename of the PDF

Dim pdffilename As String = "image.pdf"

‘Save the created document to the ConvertedtoPDF folder in your website
            document.Save("L:aspdotnetprojectsjpgtopdfConvertedtoPDF" & pdffilename)

‘Output the download link to the browser

Response.Write("<a href=’/jpgtopdf/ConvertedtoPDF/image.pdf’>Download the PDF File</a>")
End If
End Sub
End Class

Browser testing of the basic JPG to PDF example

Let’s test the application in the web browser. Go to the Default.aspx source code. You should see the upload form, as shown in the screen shot below:

For the sake of testing, download this test JPG image: http://www.dotnetdevelopment.net/tutorials/beautifulsunrise.jpg Try uploading this image to your application, then click the “Convert this JPG to PDF” button.

You should then see the “Download this PDF File” hyperlink. Now try clicking the link; the PDF file will open. You will then see the image being embedded in a PDF document. See the screen shot below:

Now what if you want to center the image on the page?

Centering the JPG Image on the Page in PDFSharp

To center the JPG image in the page, simply replace this line:

gfx.DrawImage(image, x, 30)

With these codes:

‘Center the image in the page, credits: http://bit.ly/g6wVGJ
Dim leftOffset As Double = (gfx.PageSize.Width / 2.0) – (image.PointWidth / 2.0)
Dim topOffset As Double = (gfx.PageSize.Height / 2.0) – (image.PointHeight / 2.0)
‘Write the image to PDF
gfx.DrawImage(image, leftOffset, topOffset)

Then delete the previously uploaded image files and created PDF files in UploadedImages and the ConvertedtoPDF folder. Now repeat the test, using a web browser.

In practical deployment to websites, you should make sure that each file name saved and created is unique, and run a scheduled task to delete the accumulated files.

To avoid complexities for beginners, only the basic functionality is illustrated in this tutorial. You will notice that this time, the image is now centered on the page. See the screen shot below:

You can download the complete project files here: http://www.dotnetdevelopment.net/tutorials/jpgtopdf.zip. Make sure to change the following file paths to your own paths:

L:aspdotnetprojectsjpgtopdfUploadedImages
L:aspdotnetprojectsjpgtopdfConvertedtoPDF 

[gp-comments width="770" linklove="off" ]