将WebAPI响应另存为PDF文件

时间:2019-07-26 09:07:43

标签: c# http pdf asp.net-core asp.net-core-webapi

我编写了返回文件的WebAPI GET方法,我检查了SoapUI是否正常工作。现在,我想调用该服务并将文件另存为PDF,然后从本地驱动器中获取响应,但是如何将响应转换为PDF格式的文件?

public async Task<IActionResult> FileIndex()
{
    try
    {
        HttpClientHandler clientHandler = new HttpClientHandler();

        clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };

        HttpClient client = new HttpClient(clientHandler);
        HttpResponseMessage response = await client.GetAsync("https://test-server/api/files");

        if (response.IsSuccessStatusCode)
        {
            var output= await response.Content.ReadAsAsync<byte[]>();
            System.IO.File.WriteAllBytes(@"E:\testpdf.pdf", output);
        }
    }
    catch (Exception ex)
    {
    }

    return View();
}

它引发异常var output...上引发异常

  

读取字节时出错。意外的令牌:StartObject。路径“版本”,   第1行,位置11

SoapUI中的响应

{
   "version":    {
      "major": 1,
      "minor": 1,
      "build": -1,
      "revision": -1,
      "majorRevision": -1,
      "minorRevision": -1
   },
   "content": {"headers":    [
            {
         "key": "Content-Disposition",
         "value": ["attachment; filename=\"About Us.pdf\""]
      },
            {
         "key": "Content-Type",
         "value": ["application/octet-stream"]
      }
   ]},
   "statusCode": 200,
   "reasonPhrase": "OK",
   "headers": [],
   "requestMessage": null,
   "isSuccessStatusCode": true
}

2 个答案:

答案 0 :(得分:1)

我认为您的主要问题是尝试在extract(r, ptrans) #1529.66 方法中使用ReadAsAsync<byte[]>中的Microsoft.AspNet.WebApi.Client

FileIndex()

这旨在用于JSON响应。有一些链接错误地宣称您可以通过在var output = await response.Content.ReadAsAsync<byte[]>(); 上添加一行来使它与application/octet-stream响应一起使用,例如:

WebApiConfig.cs

我相信建议是有缺陷的,我从来没有使它可行。如果您的项目中有该行,则应将其删除,并在config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream")); 方法中使用以下内容:

FileIndex()

这是一个完整的控制台应用程序,它使用Web API方法中的var output = await response.Content.ReadAsByteArrayAsync(); 流并将其保存到磁盘(在TestClient.exe文件旁边的TestClient / bin / Debug文件夹中):

application/pdf

这是我实现的一个控制器,该控制器演示了如何使用正确的MIME类型和其他元数据信息将PDF文件返回给客户端:

using System.Net.Http;
using System.Threading.Tasks;

namespace TestClient
{
    class MainClass
    {
        public static async Task FileIndex()
        {
            HttpClientHandler clientHandler = new HttpClientHandler();

            var requestUri = "http://localhost:8080/api/files";

            //var requestUri = "https://test-server/api/files";
            //clientHandler.ServerCertificateCustomValidationCallback =
            //    (sender, cert, chain, sslPolicyErrors) => { return true; };

            HttpClient client = new HttpClient(clientHandler);
            HttpResponseMessage response = await client.GetAsync(requestUri);

            if (response.IsSuccessStatusCode)
            {
                var output = await response.Content.ReadAsByteArrayAsync();
                //var path = @"E:\testpdf.pdf";
                var path = @"testpdf.pdf";
                System.IO.File.WriteAllBytes(path, output);
            }
        }

        public static void Main(string[] args)
        {
            FileIndex().Wait();
        }
    }
}

希望这会有所帮助!

答案 1 :(得分:-1)

您可以使用此示例来解释您的需求。

public void GeneratePdf(string htmlPdf)
{
   var pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
   var htmlparser = new HTMLWorker(pdfDoc);
   using (var memoryStream = new MemoryStream())
   {
       var writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
       pdfDoc.Open();

       htmlparser.Parse(new StringReader(htmlPdf));
       pdfDoc.Close();

       byte[] bytes = memoryStream.ToArray();
       File.WriteAllBytes(@"C:\file.pdf", bytes);

       memoryStream.Close();
}

}