iText is a Java library for creating and manipulating PDF documents.
Common usage steps and examples are as follows:
1. Add dependencies
If using the Maven project,Add the following dependencies to the file:
<dependency> <groupId></groupId> <artifactId>itextpdf</artifactId> <version>5.5.13.2</version> </dependency>
2. Create a simple PDF document
Here is a simple Java code example for creating a PDF document containing text:
import ; import ; import ; import ; import ; import ; public class SimplePDFExample { public static void main(String[] args) { Document document = new Document(); try { (document, new FileOutputStream("")); (); (new Paragraph("Hello, iText! This is a simple PDF document.")); (); } catch (DocumentException | FileNotFoundException e) { (); } } }
In this example:
- Create a first
Document
object, which represents a PDF document. - Then use
PdfWriter
Associate the document with an output stream (here is the output to the namefile).
- After opening the document, use
()
Methods to add content (here is aParagraph
Object, containing the text to be displayed). - Finally close the document.
3. Add more elements
- Add a title:
(new Paragraph("Document Title", new Font(.TIMES_ROMAN, 18, )));
Here a paragraph with a specific font (Times Roman, font 18, bold) is created as the title.
- Add a list:
List list = new List(); (new ListItem("Item 1")); (new ListItem("Item 2")); (list);
This creates an unordered list and adds it to the document.
4. Use the form
PdfPTable table = new PdfPTable(3); // 3 columns table("Column 1"); ("Column 2"); ("Column 3"); (table);
Can create aPdfPTable
Object, and add cells to it to build the table.
5. Set page properties
- Set page size and margins:
Rectangle pageSize = new Rectangle(PageSize.A4); (); (pageSize); (36, 36, 36, 36);
Here the page is set to A4 size, white background, and the page margin is specified.
6. Processing images
try { Image image = (""); (200, 200); // Resize the image (image); } catch (BadElementException | IOException e) { (); }
Images can be read from files and added to documents, and the image can be resized.
These are just some basic usages of iText, and it can also be used for more complex PDF operations such as digital signatures, merging and splitting PDFs, etc. In actual use, it is necessary to further explore and use its rich functions according to specific needs.
This is the article about the steps and examples of Java using iText to generate PDFs. For more related Java iText to generate PDFs, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!