In this example, I used Apache PDFBox as an example of using maven for managing Java library
1. We create a new project using Netbean:
New Maven project with Netbean |
Input the artifactId and package name |
2. Add code
Declare maven dependenies
4.0.0 com.blogspot.ducnguyen.dev pdfbox-example 1.0-SNAPSHOT jar UTF-8 1.7 1.7 org.apache.pdfbox pdfbox 2.0.0
Add Java Code:
package com.blogspot.ducnguyen.dev.pdfbox.example; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDType1Font; /** * * @author nvduc */ public class Main { public static void main(String[] args) throws IOException { long timestamp = System.currentTimeMillis(); String filename = "test-"+timestamp+".pdf"; String message = "Hello World at : "+ timestamp; PDDocument doc = new PDDocument(); try { PDPage page = new PDPage(); doc.addPage(page); PDFont font = PDType1Font.HELVETICA_BOLD; PDPageContentStream contents = new PDPageContentStream(doc, page); contents.beginText(); contents.setFont(font, 12); contents.newLineAtOffset(100, 700); contents.showText(message); contents.endText(); contents.close(); doc.save(filename); } finally { doc.close(); } } }
3. Running
Before running, we must build project, When we build, maven will get pdfbox library from maven repository
Build project in NetBean |
We can check the result in Files view
Result after choose Run File |
No comments:
Post a Comment