C# render pdf in browser using MVC

C# render pdf in browser using MVC

In this code sample we will be using the PDF Rasterizer package in a MVC context to render specific PDF pages in a browser.

To begin, create a new MVC project in Visual Studio. We can now add a new controller, called RasterizerController. Add the following code to it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Diagnostics;
using System.IO;
using TallComponents.PDF.Rasterizer;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace RenderPDF.Controllers
{
    public class RasterizerController : Controller
    {

        //show the form
        public ActionResult Index()
        {
            return View();
        }

        //render the PDF page given the selected pagenumber
        public ActionResult Render(string number)
        {
            foreach (string upload in Request.Files)
            {
                if (!HasFile(Request.Files[upload])) continue;
                //get the path of the PDF on the server
                string path = AppDomain.CurrentDomain.BaseDirectory;
                string filename = Path.GetFileName(Request.Files[upload].FileName);
                string total = Path.Combine(path, filename);
                //save the PDF
                Request.Files[upload].SaveAs(total);

                //open the pdf and render the selected page
                using (FileStream fs = new FileStream(total, FileMode.Open, FileAccess.Read))
                {
                    Document d = new Document(fs);
                    int p = Convert.ToInt32(number);
                    if (p >= d.Pages.Count())
                    {
                        return Content("You have selected page " + p + " but there are only " + (d.Pages.Count() - 1) + " pages available.");
                    }
                    Page page = d.Pages[p];
                    using (Bitmap bitmap = new Bitmap((int)page.Width, (int)page.Height))
                    {
                        Graphics graphics = Graphics.FromImage(bitmap);
                        graphics.SmoothingMode = SmoothingMode.AntiAlias;
                        page.Draw(graphics);

                        //for rendering, an ActionResult is required as a result, so convert the image to bytes and return it (stating it should be rendered as a JPEG)
                        byte[] byteArray = ImageToByte(bitmap);
                        return File(byteArray, "image/jpeg");
                    }
                }
            }
            return Index();
        }

        public static byte[] ImageToByte(Image img)
        {
            ImageConverter converter = new ImageConverter();
            return (byte[])converter.ConvertTo(img, typeof(byte[]));
        }

        //check if the file exists
        public static bool HasFile(HttpPostedFileBase file)
        {
            return (file != null && file.ContentLength > 0);
        }

    }
}

The Index() function will return a new webform (which we will create shortly) and the Render function is called when the user presses the “Submit” button on the online form. Then, the selected PDF page will be rendered on-screen. Now that the controller has been made, it is time to make the view for the user: this will contain a webform where the user can upload a PDF and select the page he wants to be rendered. On the right side, you will see several folders: open the “Views” folder and create a new view in the “Shared” subfolder and call it “Index” (deselect the “Select Master Page” option).

Now add the following code to it:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!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>PDF Renderer</title>
</head>
<body>
    <%using (Html.BeginForm("Render", "Rasterizer", FormMethod.Post, new { enctype = "multipart/form-data" })) %>
    <% { %>
    <table>
        <tr>
            <td>
                <input type="file" name="FileUpload" /><br />
            </td>
        </tr>
        <tr>
            <td>
                page number:
            </td>
            <td>
                <%= Html.TextBox("number") %>
            </td>
        </tr>
    </table>
    <input type="submit"/>
    <% } %>
</body>
</html>

Note that the Render function is set at the start of the form, which means that the data will be sent to that function. Together the View and the Controller will handle the PDF rendering, we now only have to connect them to each other. Open the “Global.asax” file and set the Controller to “Rasterizer” and the action to “Index”. Now when you run the project the HTML form will be shown and after pressing “Submit”, the specified page will be rendered in the browser.