Tomuke
Tomuke

Reputation: 877

Opening PDF in browser at a specific page

I am using a custom html helper @Html.ActionLink to find and return a PDF file to the browser and open in a new tab. The issue I am now having is when I am trying to open the PDF on a specific page.

The file is found, returned and opened just fine when NOT trying to specify a page parameter for the PDF to open on. Therefore, there must be some issue with my approach to setting the parameter.

According to Adobe documentation, #page=? parameters can be appended to the end of a URL to open a PDF at a specific page. However, my approach for doing so is not working.

See Adobe documentation on the subject here.

Razor helper in use:

@Html.FileLink("Document Link", "\\MyLocation\\MyDocument.pdf", "4", new { @target = "_blank" })

Helper method:

public static MvcHtmlString FileLink(this HtmlHelper helper, string LinkText, string FilePath, string PageNumber, object htmlAttributes = null)
{
    return helper.ActionLink(LinkText, "ShowFile", "Home", new { path = System.Uri.EscapeDataString(FilePath), page = PageNumber }, htmlAttributes);
}

ShowFile method:

public ActionResult ShowFile(string path, string page)
{
    // My attempt at passing and setting the page parameter!
    path = System.Uri.UnescapeDataString(path + "#page=" + page);

    // Get actual path to file, file name
    var filePath = string.Format("{0}{1}", ConfigurationManager.AppSettings["DocumentsRoot"], path);

    // Get MIME type
    var contentType = MimeMapping.GetMimeMapping(path);

    // Return file
    return File(filePath, contentType);
}

Upvotes: 2

Views: 2329

Answers (1)

Richard
Richard

Reputation: 30618

The page parameter in the adobe documentation is an anchor tag (e.g. #page=5), not a query string parameter (?page=5). You can use a different ActionLink override to specify this at the same time:

Html.ActionLink(LinkText, "ShowFile", "Home", null, null, "page=" + PageNumber, 
    new { path = System.Uri.EscapeDataString(FilePath) }, null)

This will generate a link which looks like...

/Home/ShowFile?path=myfilename.txt#page=5

instead of

/Home/ShowFile?path=myfilename.txt&page=5

You can then remove the page parameter from your ShowFile method, because it is only needed on the client side.

Upvotes: 3

Related Questions