简体   繁体   中英

Generate PDF in server (Asp.Net Core) and retrieve in Browser (Angular)

I'm using Asp.Net Core and ItextSharp to generate a PDF report and sending to the Browser.

[HttpGet]
public async Task<IActionResult> GetStream(string ids)
{
  try
        {
            List<int> labRequestIds = JsonConvert.DeserializeObject<List<int>>(requestIds);
            MemoryStream ms = new MemoryStream();
            Document doc = new Document(PageSize.A4, 30f, 30f, 30f, 30f);
            PdfWriter writer = PdfWriter.GetInstance(doc, ms);
            doc.Open();
            await CreatePlateDoc(labRequestIds, doc);
            doc.Close();
            writer.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/pdf");
         }
}

Then using angular (typescript) I get the response in the browser like that: Service:

getStream(requestIds: Array<number>) {
    return new Promise((resolve, reject) => {
        this.http.get(AppConfig.LrmApiUrl + '/fileGenerator/plates'
            + '?requestIds=' + JSON.stringify(requestIds)
            , { headers: this.authService.getHeaders() })
            .subscribe((data:any) => {
                console.log(data);
                if (data) {
                    resolve(data._body);
                }                 
            },
            err => reject(Tools.handleResponseError(err))
        );
    });
}

and in the controller try to download the PDF created with Filesaver.js like that:

downloadClick() {      
    this._fileGeneratorService.getPlateStream(this.selectedRequestIds)
        .then(data => {
            let saveAs = require('file-saver');
            let name = this.selectedRequests.map(function (x) {
                return x.code;
            }).join();
            let blob = new Blob([data], { type: 'application/pdf });
            saveAs(blob, name);
        })
        .catch(err => console.log(err));
}

But it is not working. The pdf downloaded is empty but has information on it.

At the end I solved it like that:

  public async Task<IActionResult> CreatePlatePdf(string dto)
    {
        try
        {
            List<int> dto= JsonConvert.DeserializeObject<List<int>>(dto);
            MemoryStream ms = new MemoryStream();
            Document doc = new Document(PageSize.A4, 30f, 30f, 30f, 30f);
            PdfWriter writer = PdfWriter.GetInstance(doc, ms);

            doc.Open();
            await this.CreateDoc(dto, doc);
            doc.Close();
            writer.Flush();
            byte[] byteInfo = ms.ToArray();
            ms.Write(byteInfo, 0, byteInfo.Length);
            ms.Seek(0, SeekOrigin.Begin);
            return this.File(ms, "application/pdf", fileName.pdf);
        }
}

and calling it in the client like that:

downloadPlatesClick() 
{
    window.location.href = url_pdf;
}

So right now the only problem that I have is that you can call it without authorization. So anyone knows how to add an authorization (header) in the calling of my srvice?¿

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM