5

I need to write some text in to a PDF document using Java. I wrote a code for that. But i'm unable to open the file. If you guys have some idea please share with me.

public class WritPDF
{

    public static void main(String[] args)
    {
        Writer writer = null;

        try
            {
                String text = "This is a text file";

                File file = new File("C:/Users/PrinterTest/Hi1.pdf");
                writer = new BufferedWriter(new FileWriter(file));;
                writer.write(text);
            } catch (FileNotFoundException e)
            {
                e.printStackTrace();
            } catch (IOException e)
            {
                e.printStackTrace();
            } finally
            {
                try
                    {
                        if (writer != null)
                            {           
                            }
                    } catch (IOException e)
                    {}
            }
    }

}
user2255885
  • 327
  • 3
  • 4
  • 13
  • PDF is not a text file, you cannot open it that way. POI is a good thing, another possibility could be using Velocity templates – iberbeu Apr 11 '13 at 09:19
  • 6
    Apache POI is for working with Microsoft Office documents, not PDF files. – Jesper Apr 11 '13 at 09:23
  • PDF is not a plain text format. With your code it will simply create normal text file. You would need to use PDF libraries like [iText](http://itextpdf.com/) or Apache FOP. There are many more such libraries available. – Bhushan Bhangale Apr 11 '13 at 09:19

1 Answers1

8

Your code is writing a plain text file with the extension .pdf. A PDF file is not a plain text file.

There are several libraries available for working with PDF files in Java, for example iText and Apache PDFBox.

Jesper
  • 202,709
  • 46
  • 318
  • 350