If you use iText, you create a PDF document in 5 steps"
- Create a
Document
instance
- Create a
PdfWriter
instance
- Open the document
- Add content
- Close the document
In your question, you do not create the PdfWriter
instance (unless it's a global variable). In your comment, you do not open the document (you've skipped step 3 and this step is essential in the document creation process).
Take the code from your comment, and add the following line at the appropriate place:
document.open();
The appropriate place is after the line where you create the PdfWriter
instance and before you start using the writer
instance.
Update
In your comment, you are now sharing some code that contains a logical error.
Your main method pdfGeneration()
(probably) contains the five steps in the creating process:
- You create a
Document
instance
- You create a
PdfWriter
instance that writes bytes to a file My First PDF Doc.pdf
- You open the document
- You call a method
setPara()
that is supposed to add content
- You close the document (not visible in your code)
The logical error can be found in the setPara()
method. In this method, you repeat the five steps. You create a new Document
instance (there's no need to do this) and you create a new PdfWriter
instance that creates a new file My First PDF Doc.pdf. This throws an exception, because that file is already in use!
You should change setPara()
like this:
public void setPara(PdfContentByte canvas, Phrase p, float x, float y) {
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase, x, y, 0);
}
You should call this method from your main method like this:
setPara(writer.getDirectContent(), new Phrase(text), x, y);
Of course: as the setPara()
method is little more than a reduced version of the showTextAligned()
method that already exists in iText, you may want to use that method directly. For instance: use this in your main method, instead of introducing a setPara()
method:
Phrase phrase = new Phrase("Some text", new Font());
PdfContentByte canvas = writer.getDirectContent();
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase, 20, 20, 0);