Home > Software engineering >  c# reading a pdf from request body and writing to file
c# reading a pdf from request body and writing to file

Time:01-25

I want to read a pdf from the request body and write it to a file.

Basically the raw request body looks something like this:

%PDF-1.7
4 0 obj
(Identity)
endobj
5 0 obj
(Adobe)
endobj
8 0 obj
<<
/Filter /FlateDecode
/Length 33775
/Length1 81256
/Type /Stream
>>
stream
...
%%EOF

I wont post the whole request body as it is quite big.

In my code I read it as the following

 var content = (HttpContent)new StreamContent(Request.Body);
 var bytes =  await content.ReadAsByteArrayAsync();

Then write the bytes to a file

using (FileStream file = new FileStream(fileName, FileMode.Create, System.IO.FileAccess.Write))
{
   file.Write(bytes, 0, bytes.Length);
}

However, the text in that pdf is not getting written to the file. It's just a blank PDF. The pdf is suppose to show the text "test".

EDIT:

New findings.

When testing my code through postman, I found using the postman body binary section to upload a pdf works just fine but when sending the same pdf raw content through the postman body raw section it does not work. Is it because some information is loss when copying the raw content of the pdf directly to postman?

CodePudding user response:

You can copy the stream directly to a file.

using (FileStream file = new FileStream(fileName, FileMode.Create, System.IO.FileAccess.Write))
{
   Request.Body.CopyTo(file);
}

Make sure that neither other code nor the debugger reads from the body before you copy it to the file.

In case this doesn't help, please provide a full example including the code that makes the request.

CodePudding user response:

You may have a look at iTextSharp and sample code I have used that for some projects and worked well for me.

  • Related