2

I want to create a PDF file from java code. And this is what I have written so far-

public class IOExp  {
    public static void main(String args[]) throws java.io.IOException   {
        java.io.FileOutputStream fout=new java.io.FileOutputStream("MyFile.pdf");

        byte [] arr=("Hello World.\n"+"My name is Prateek Mathur, and I am  a great programmer.\n").getBytes();
        fout.write(arr);
    }
}

MyFile.pdf gets created without any problem, but on opening it, Adobe Reader displays the following message-

'Abode Reader can not open 'MyFile.pdf' because it is either not a supported file
 type or because the file has been damaged (for example, it was sent as an email
 attachment and wasn't correctly decoded.'

I am already familier with iText API, and want to know how to create PDF files manually.

What is the problem with my code, and what changes need to be introduced to successfully create the PDF file??

Kara
  • 6,115
  • 16
  • 50
  • 57
  • If you want to create PDF file manually you need to read the PDF format specs in order to output the needed header bytes and how a PDF file is internally structured. You can take a look at this page for a starter (since the spec is hard to read) http://www.planetpdf.com/developer/article.asp?ContentID=navigating_the_internal_struct – Alex Sep 07 '13 at 12:23
  • Why? Why can't you use a library that already does it? If you don't like iText for some unstated reason, there are others. – user207421 Sep 16 '13 at 00:48

2 Answers2

2

I don't think you can create a pdf by simply creating a file with .pdf extension. Creating a valid pdf requires valid header and content bytes in a particular format. Rather than re-inventing the whee, you can use a framework such as Apache PdfBox, ItextPdf etc.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
2

PDF files are totally different from simple plain text files. What you created is a plain text file. Change the extension to .txt and you will see literally the text when opened with a plain text editor. Use a library for that like PDFBox.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287