Following JAVA code will enable us to write PDF files using JAVA API.
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package com.milind.word.to.pdf; | |
import com.itextpdf.text.BadElementException; | |
import com.itextpdf.text.BaseColor; | |
import com.itextpdf.text.Chunk; | |
import com.itextpdf.text.Document; | |
import com.itextpdf.text.DocumentException; | |
import com.itextpdf.text.Element; | |
import com.itextpdf.text.Font; | |
import com.itextpdf.text.List; | |
import com.itextpdf.text.Paragraph; | |
import com.itextpdf.text.pdf.PdfWriter; | |
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
/** | |
* | |
* @author milind | |
*/ | |
public class WritePdf { | |
public static void main(String[] args) throws DocumentException, BadElementException, IOException { | |
try { | |
File file = new File("D:\\mypdf.pdf"); | |
FileOutputStream fileout = new FileOutputStream(file); | |
Document document = new Document(); | |
PdfWriter.getInstance(document, fileout); | |
document.addAuthor("Milind"); | |
document.addTitle("My PDF File"); | |
document.open(); | |
Chunk chunk = new Chunk("Milind Jagre"); | |
Font font = new Font(); | |
font.setStyle(Font.UNDERLINE); | |
font.setStyle(Font.ITALIC); | |
chunk.setFont(font); | |
chunk.setBackground(BaseColor.CYAN); | |
document.add(chunk); | |
Paragraph paragraph = new Paragraph(); | |
paragraph.add("Hello World"); | |
paragraph.setAlignment(Element.ALIGN_CENTER); | |
document.add(paragraph); | |
List list = new List(true, 15); | |
list.add("Bangalore"); | |
list.add("Nagpur"); | |
document.add(list); | |
document.close(); | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
And following is the pom.xml I am using for achieving this.
<?xml version="1.0" encoding="UTF-8"?> | |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | |
<modelVersion>4.0.0</modelVersion> | |
<groupId>com.milind</groupId> | |
<artifactId>word-to-pdf</artifactId> | |
<version>1.0</version> | |
<packaging>jar</packaging> | |
<properties> | |
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | |
<maven.compiler.source>1.7</maven.compiler.source> | |
<maven.compiler.target>1.7</maven.compiler.target> | |
</properties> | |
<dependencies> | |
<dependency> | |
<groupId>com.itextpdf</groupId> | |
<artifactId>itextpdf</artifactId> | |
<version>4.2.2</version> | |
</dependency> | |
</dependencies> | |
</project> |
Following image will show the way my pdf file looks.
