سؤال

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??

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top