-2

I am trying to create a pdf file from a byte array as

string str = "Hello World";
byte[] byteArray = Encoding.ASCII.GetBytes(str);
using(FileStream fs = new FileStream(path, FileMode.OpenorCreate, FileAccess.ReadWrite, FileShare.None))
 {
     fs.Write(byteArray, 0, byteArray.Length);
 }

It creates the file. However, when I try to open the file, I get the following error:

adobe reader could not open file because it is not a supported file type

I can open other pdf files just fine. What is causing this error?

Kara
  • 6,115
  • 16
  • 50
  • 57
user544079
  • 16,109
  • 42
  • 115
  • 171
  • Are you sure your byte array is a complete pdf file? – Mike Precup Jun 28 '13 at 19:27
  • please see my edits. I am converting the string into a byte array – user544079 Jun 28 '13 at 19:29
  • In your code example you are writing a regular string to a file. Are you trying to open up that file, which contains no "pdf" information? – gunr2171 Jun 28 '13 at 19:33
  • 1
    Are you really trying to convert "Hello World" to a PDF file, or it's just a placeholder for the real PDF data? – Pierre-Luc Pineault Jun 28 '13 at 19:33
  • 1
    What you save here is ASCII file not PDF. Just adding .pdf extension doesn't make it PDF. Like giving .jpg extension and writing "Amanda Peet" doesn't make it a picture of Amanda Peet. – Milosz Krajewski Jun 28 '13 at 19:38
  • Take a look into itextsharp, it's a great open source library designed for creating or editing pdf files. It can turn byte arrays into pdfs like you want. – ovaltein Jun 28 '13 at 19:54

2 Answers2

3

The pdf format is more than a simple "Hello World". It contains large amounts of information about the formatting and the file itself. You'd need to look into libraries that help you create pdf files instead of writing out "Hello World". This is kind of like writing something in a txt file and opening it in photoshop - it won't be a valid file.

Mike Precup
  • 4,148
  • 21
  • 41
1

If you want to create a Hello World file in PDF, you need a library to do so.

For instance: this Java HelloWorld example creates this hello.pdf. Download hello.pdf and open it in a text editor, and you'll see that it contains much more than the bytes "Hello World".

I see that you're a C# programmer. You can find the C# port of the HelloWorld example here. iText is only one of the many libraries, I'm mentioning it because I'm the original developer of iText. A simple search for PDF libraries will reveal more options.

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165