Skip to content

Instantly share code, notes, and snippets.

@hacksoldier
Last active October 8, 2015 08:53
Show Gist options
  • Select an option

  • Save hacksoldier/70d9b067e21fbe6f5a9a to your computer and use it in GitHub Desktop.

Select an option

Save hacksoldier/70d9b067e21fbe6f5a9a to your computer and use it in GitHub Desktop.
How to wirte a simple document in PDF format
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import com.itextpdf.text.Element;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.List;
public void createTestPDF () {
Document document = null;
try
{
File file = new File("C:\\dati\\testPDF.pdf");
FileOutputStream fileOutputStream = new FileOutputStream(file);
document = new Document();
PdfWriter.getInstance(document, fileOutputStream);
document.addAuthor("Me");
document.addTitle("PDF test");
document.open();
Chunk chunk = new Chunk("iText test");
Font font = new Font(Font.COURIER);
font.setStyle(Font.UNDERLINE);
font.setStyle(Font.ITALIC);
chunk.setFont(font);
chunk.setBackground(Color.CYAN);
document.add(chunk);
Paragraph paragraph = new Paragraph();
paragraph.add("New paragrapj test");
paragraph.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph);
Image image;
try
{
image = Image.getInstance("C:\\dati\\img.png");
image.setAlignment(Image.MIDDLE);
document.add(image);
}
catch (MalformedURLException mue)
{
mue.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
List list = new List(true, 15);
list.add("ABC");
list.add("DEF");
document.add(list);
}
catch (FileNotFoundException fnfe)
{
log.error("Errore durante l'esecuzione del task", fnfe);
}
catch (DocumentException de) {
de.printStackTrace();
}
finally
{
try
{
if (document != null)
document.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment