G2DDrawStringPDF.java Source code

Java tutorial

Introduction

Here is the source code for G2DDrawStringPDF.java

Source

import java.awt.Graphics2D;
import java.io.FileOutputStream;

import com.lowagie.text.Document;
import com.lowagie.text.FontFactory;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;

public class G2DDrawStringPDF {
    public static void main(String[] args) {
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("G2DDrawStringPDF.pdf"));
            document.open();
            DefaultFontMapper mapper = new DefaultFontMapper();
            FontFactory.registerDirectories();
            mapper.insertDirectory("c:\\windows\\fonts");

            int w = 150;
            int h = 150;
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate(w, h);
            Graphics2D g2 = tp.createGraphics(w, h, mapper);

            g2.drawString("text", 20, 20);

            g2.dispose();
            cb.addTemplate(tp, 50, 400);

        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        document.close();
    }

}