Search code examples
javaspring-mvcpdf-generationitextgraphics2d

How do I draw graphics to PDF using iText?


I am trying to complete an example that draws graphics and writes them to PDF, but I keep getting errors that the PDF has no pages. if I add something simple with document.add() after opening it works fine, I just never see the graphics. Here is my code:

Document document = new Document();
PdfWriter writer = new PdfWriter();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition",
    " attachment; filename=\"Design.pdf\"");

writer = PdfWriter.getInstance(document, response.getOutputStream());

document.open();    
PdfContentByte cb = writer.getDirectContent();
Graphics2D graphics2D = cb.createGraphics(36, 54);
graphics2D.drawString("Hello World", 36, 54);
graphics2D.dispose();   
document.close();

Do I have to do something else to add the graphic to the document or is my syntax incorrect?


Solution

  • Does Document doc = new Document(PageSize.A4); make any difference?

    I don't know if you need to add a Paragraph like this:

    doc.add(new Paragraph(...));
    

    Also we use doc.add(ImgRaw); to add images.