문제

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