Home > Mobile >  How can I open a pdf in a new tab with Blazor
How can I open a pdf in a new tab with Blazor

Time:04-14

The following code should work with plain html

<a href="pdf/foo.pdf" target="_blank">Open pdf</a>

It also works with Blazor (WebAssembly) but only from localhost. A new tab is opened with address https://localhost:[...]/pdf/foo.pdf. In production, the browser tries to open https://[...]/pdf/foo.pdf and I get the error

Sorry, there's nothing at this address.

Is there a solution for Blazor?

Edit 2

I deleted my first edit, because with the following new information, I think it is not relevant anymore.
Since I thought, it was a problem with deploying pdfs on netlify, I asked in their forum: https://answers.netlify.com/t/how-can-i-deploy-a-pdf/54897. (Sorry, the short links syntax [][] does not seem to work in edits.) I created a demo page (https://beautiful-snickerdoodle-bb5389.netlify.app/) and found out, it is not working on my PC and several laptops, but on my smartphone. A user in the netlify forum was able to display the pdf in Chrome but not Safari. So, I think, it is not a problem with netlify but there is something wrong with my page. Any help is greatly appreciated.

CodePudding user response:

The problem I see is that you need <a ... target="_blank"> to get a new tab but you need NavigationManager.NavigateTo(..., forceLoad:true); to bypass the routing.

You can do so with a Redirect component (page).

@page "/redirect/{document}"
@inject NavigationManager Navigation

@code {
    [Parameter]
    public string Document { get; set; } = null!;

    protected override void OnInitialized()
    {
        Navigation.NavigateTo($"pdf/{Document}.pdf", forceLoad:true);
    }
}

and then use it like

    <a href="redirect/foo" target="_blank">Open pdf</a>

Baking in the path and the .pdf extension is for security and to avoid encoding issues.

This isn't perfect, if it works you will see your app loading first and then the PDF.

Using a bare layout with an IFrame might be another option.

I only tested this locally, so give it a try.

CodePudding user response:

How you serve a download is your choice, how it is handled is the users choice,

enter image description here

there are two recommended methods,

  1. offer <a href="absolute fab.pdf" download>download this fab pdf, I promise its safe to run</a>

  2. If you cant see anything in this blank iFrame your browsers exploit security is perfect.

enter image description here

CodePudding user response:

Your path to "pdf/foo.pdf" denotes that there is a pdf folder in wwwroot folder of your website, make sure this folder also exists in your prod environment and has pdf file you are trying to open, also make sure this folder has read/write rights for IIS_IUSRS

  • Related