Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Write PDF using Java

Tags:

java

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)
                    {}
            }
    }

}
like image 838
user2255885 Avatar asked Apr 11 '13 09:04

user2255885


People also ask

How do PDF files work in Java?

Step 1: Create a content handler. Step 2: Create a PDF file locally in the system one is using. Step 3: Now, create a FileInputStream that has the same path where the created PDF file is residing. Step 4: For the PDF file, create a content parser with the help of the metadata type object.

How do I add a paragraph to a PDF in Java?

The following Java program demonstrates how to create a PDF document and add a paragraph to it using the iText library. It creates a PDF document with the name addingParagraph. pdf, adds a paragraph to it, and saves it in the path C:/itextExamples/. Save this code in a file with the name AddingParagraph.

How do I convert a string to a PDF in Java?

Let's look at how we insert a new file with “Hello World” text into a pdf file: Document document = new Document(); PdfWriter. getInstance(document, new FileOutputStream("iTextHelloWorld. pdf")); document.


1 Answers

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.

like image 134
Jesper Avatar answered Sep 28 '22 14:09

Jesper