Skip to content

Instantly share code, notes, and snippets.

@migueldoctor
Created November 4, 2022 08:52
Show Gist options
  • Save migueldoctor/bfe850b82d41cc8a79f9c5d7788a70f0 to your computer and use it in GitHub Desktop.
Save migueldoctor/bfe850b82d41cc8a79f9c5d7788a70f0 to your computer and use it in GitHub Desktop.
Sample 3 Fonts and Paragraphs
package com.kesizo.java.pdf.sample;
import java.awt.*;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.PdfWriter;
public class Main {
public static void main(String[] args) {
Document myPDFDoc = new Document();
// Define a string as title
String title = "Learning OpenPDF with Java";
// Define a paragraph
String lorenIpsum1 = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo"+
" ligula eget dolor. Aenean massa.Cum sociis natoque penatibus et magnis dis" +
" parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec," +
" pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim"+
" Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu."+
" In enim justo, rhoncus ut, imperdiet a, venenatis vitae,"+
" justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt."+
" Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.";
try {
FileOutputStream pdfOutputFile = new FileOutputStream("./sample1.pdf");
final PdfWriter pdfWriter = PdfWriter.getInstance(myPDFDoc, pdfOutputFile);
myPDFDoc.open(); // Open the Document
/* Here we add some metadata to the generated pdf */
myPDFDoc.addTitle("This is a simple PDF example");
myPDFDoc.addSubject("This is a tutorial explaining how to use openPDF");
myPDFDoc.addKeywords("Java, OpenPDF, Basic sample");
myPDFDoc.addCreator("Miguel and Kesizo.com");
myPDFDoc.addAuthor("Miguel Doctor");
/* End of the adding metadata section */
// Create a Font object
Font titleFont = new Font(Font.COURIER, 20f, Font.BOLDITALIC, Color.BLUE);
// Create a paragraph with the new font
Paragraph paragraph = new Paragraph(title,titleFont);
// Element class provides properties to align
// Content elements within the document
paragraph.setAlignment(Element.ALIGN_CENTER);
myPDFDoc.add(paragraph);
// Adding an empty line
myPDFDoc.add(new Paragraph(Chunk.NEWLINE));
// Include the text as content of the pdf
myPDFDoc.add(new Paragraph(lorenIpsum1));
myPDFDoc.close();
pdfWriter.close();
} catch (IOException de) {
System.err.println(de.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment