Web API генерирует пустой PDF

#c# #pdfsharp

#c# #pdfsharp

Вопрос:

У меня есть веб-API .NET Swagger, с помощью которого я пытаюсь сгенерировать и загрузить PDF-документ с помощью PDFsharp.
Я получаю PDF-файл из API, но файл PDF полностью пустой.

Приведенный ниже код — это то, что у меня есть в данный момент, я создаю PdfDocument , сохраняю его в a MemoryStream и преобразую в a ByteArray , который будет возвращен в Content of HttpResponseMessage .

При возврате я вижу информацию о файле, такую как the Title и the Author , но сам PDF-файл пуст.

РЕДАКТИРОВАТЬ: следуя URL-адресу запроса в браузере (а не в пользовательском интерфейсе swagger), я загружаю PDF-файл для меня и работает, однако загрузка PDF-файла из ссылки в теле ответа после вызова API дает мне пустой PDF-файл. В чем разница между ними?

 MemoryStream stream = new MemoryStream();
       
// Create a new PDF document 
PdfDocument document = new PdfDocument();
document.Info.Title ="Certificate";
document.Info.Author = "My Author";
document.Info.Subject = "My Subject.";

// Create an empty page 
PdfPage page = document.AddPage();
page.Width = 419;
page.Height = 595;
page.Orientation = PdfSharp.PageOrientation.Landscape;

// Get an XGraphics object for drawing 
XGraphics gfx = XGraphics.FromPdfPage(page);

// Draw background    
string pdfTemplate = HttpContext.Current.Server.MapPath("~/Content/Images/CertificateBackground.png");
gfx.DrawImage(XImage.FromFile(pdfTemplate), 0, 0, 595, 419);           

// Save the document to stream
document.Save(stream, false);
        
HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);

httpResponseMessage.Content = new ByteArrayContent(stream.ToArray()); 
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = document.Info.Title;
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");

return httpResponseMessage;
  

Ответ №1:

Вы пробовали просто загрузить существующий PDF-файл с видимым содержимым, чтобы проверить, остается ли документ пустым?

Я скопировал ваш код в консольное приложение и изменил его, чтобы сохранить на диске. Кажется, он работает правильно. Я думаю, проблема в том, как вы обрабатываете сохраненную часть pdf.

         MemoryStream stream = new MemoryStream();

        // Create a new PDF document 
        PdfDocument document = new PdfDocument();
        document.Info.Title = "Certificate";
        document.Info.Author = "My Author";
        document.Info.Subject = "My Subject.";

        // Create an empty page 
        PdfPage page = document.AddPage();
        page.Width = 419;
        page.Height = 595;
        page.Orientation = PdfSharp.PageOrientation.Landscape;

        // Get an XGraphics object for drawing 
        XGraphics gfx = XGraphics.FromPdfPage(page);

        // Draw background    
        string pdfTemplate = @"C:downloadsimage.jpg";
        gfx.DrawImage(XImage.FromFile(pdfTemplate), 0, 0, 595, 419);

        // Save the document to stream
        document.Save(stream, false);
        //document.Close();

        HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
        //httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);

        httpResponseMessage.Content = new ByteArrayContent(stream.ToArray());
        httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        httpResponseMessage.Content.Headers.ContentDisposition.FileName = document.Info.Title   ".pdf";
        httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");

        ContentDispositionHeaderValue contentDisposition = httpResponseMessage.Content.Headers.ContentDisposition;
        var fileName = contentDisposition != null ? contentDisposition.FileName : "unknown.dat";
        using (var fs = new FileStream(@"C:downloads"   fileName, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            Task.WaitAll(httpResponseMessage.Content.CopyToAsync(fs));
        }