1

I have a string like 0x255044462D312E330D0A312030206F626A0D0 and I've tried to convert it to a PDF.

Code:

var inputStr="my hex string";
pdfFile = Encoding.Unicode.GetBytes(inputStr).ToArray();
return new FileContentResult(pdfFile, "application/pdf");

It's not working ( "Failed to load PDF document" is the message I get ). What am I doing wrong? I've also tried to change response:

Response.ClearHeaders();
Response.Clear();
Response.AddHeader("Content-Type", "application/pdf");
Response.AddHeader("Content-Length", pdfFile.Length.ToString());
Response.AddHeader("Content-Disposition", "inline; filename=sample.pdf");
Response.BinaryWrite(pdfFile);
Response.Flush();
Response.End();

Update

I don't know how the string was initially encoded

Update 2

So I'm receiving "-2" because of someone who thought this questions is a duplicate ( he deteled his answer by the way ) ? Thank you

Cosmin
  • 2,184
  • 21
  • 38

2 Answers2

2

Assuming your hex string is actually a valid pdf file you need to convert it into a byte array like this:

var inputStr = "0x255044462D312E330D0A312030206F626A0D0";
var hex = inputStr.Substring(2);

int NumberChars = hex.Length / 2;
byte[] pdfFile = new byte[NumberChars];
using (var sr = new StringReader(hex))
{
    for (int i = 0; i < NumberChars; i++)
        pdfFile[i] = Convert.ToByte(new string(new char[2]{(char)sr.Read(), (char)sr.Read()}), 16);
}
Magnus
  • 45,362
  • 8
  • 80
  • 118
1

You will need to use some kind of API to create a PDF document. PDF files are complicated file formats and what you have created is basically just a text file.

I'm assuming the error "Failed to load PDF document" is from whatever software is trying to open the PDF file. It is getting the mime header that you have specified saying it is a pdf file but when it looks it doesn't find a pdf file, just a text file.

As an example of this try changing the mime type from "application/pdf" to "text/plain" and you should find it will give you a text file with your input text in it.

Although closed as off topic Creating pdf files at runtime in c# has discussions on APIs that can be used to create PDFs.

Community
  • 1
  • 1
Chris
  • 27,210
  • 6
  • 71
  • 92