Home > Blockchain >  How do I render a pdf in the browser generated from DynamicPDF Cloud API?
How do I render a pdf in the browser generated from DynamicPDF Cloud API?

Time:07-22

Using DynamicPDF's Cloud API, instead of generating a pdf back to the local file system, I would like it to directly open in another browser tab to be available for printing immediately. How do I accomplish that?

The method I am using (.NET Core 6 / Blazor) is below:

public async Task CallDynPDFCloudAPI()
    {
  var basePath = @"JSONFiles\";
  var apiKey = "foo";
  var cloudPath = "bar.dlex";
  Pdf pdf = new Pdf();
  pdf.ApiKey = apiKey;
  LayoutDataResource layoutDataResource = new LayoutDataResource(basePath   "FooBar.json");
  pdf.AddDlex(cloudPath, layoutDataResource);
  PdfResponse pdfResponse = pdf.Process();
  if (pdfResponse.IsSuccessful)
  {
    File.WriteAllBytes(basePath   "Manifest_"   manifestBranch   ".pdf", pdfResponse.Content);
  }
  else
  {
    Console.WriteLine(pdfResponse.ErrorJson);
  }
}

CodePudding user response:

Reread article on https://docs.microsoft.com/en-us/aspnet/core/blazor/file-downloads?view=aspnetcore-6.0

@page "/file-download-1"
@using System.IO
@inject IJSRuntime JS

<h1> File Download Example</h1>

<button @onclick = "DownloadFileFromStream" >
    Download File From Stream
</button>

@code {

    private Stream CallDynPDFCloudAPI()
    {
        var basePath = @"JSONFiles\";
        var apiKey = "foo";
        var cloudPath = "bar.dlex";
        Pdf pdf = new Pdf();
        pdf.ApiKey = apiKey;
        LayoutDataResource layoutDataResource = new LayoutDataResource(basePath   "FooBar.json");
        pdf.AddDlex(cloudPath, layoutDataResource);
        PdfResponse pdfResponse = pdf.Process();
        if (pdfResponse.IsSuccessful)
        {
            return new MemoryStream(pdfResponse.Content);
        }
        else
        {
            throw new Exception("");
        }
    }


    private async Task DownloadFileFromStream()
    {
        var fileStream = CallDynPDFCloudAPI();
        var fileName = "file.pdf";

        using var streamRef = new DotNetStreamReference(stream: fileStream);

        await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
    }
}

CodePudding user response:

You won't be able to access the PDF content for this request from another browser tab. I'd recommend opening the new tab before making the call and then streaming it there. If you're using an 'a href' link, you can accomplish this by setting the 'target="_blank"' property of the 'a href'. If this is a form submission, you can set the 'target="_blank"' property of the 'form'.

The other option would be to store the PDF somewhere temporarily (as a file, in a DB or in BLOB storage) then stream it to the other tab once it's opened.

  • Related