Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File not found when inserting image file into PDF using itext

How to add images and design header, footer to pdf using itext? I have written this ,but getting exception file not found.

Image image = Image.getInstance("\resources\image.gif");

thanks

like image 809
sudo Avatar asked Jan 17 '12 08:01

sudo


2 Answers

I used the following code to insert an image from the classpath. Typically useful when you need to include an image that is not accessible from a public url.

Image img = Image.getInstance(getClass().getClassLoader().getResource("MyImage.jpg"));

In my case, I use maven, so I put MyImage.jpg in src/main/resources

like image 187
gizit Avatar answered Oct 20 '22 16:10

gizit


take a look at this example

import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;

public class CreatePDF{
    public static void main(String arg[])throws Exception{
      try{
                Document document=new Document();
                FileOutputStream fos=new FileOutputStream("C:/header-footer.pdf");
                PdfWriter writer = PdfWriter.getInstance(document, fos);
                document.open();
                Image image1 = Image.getInstance("C:/image1.jpg");
                Image image2 = Image.getInstance("C:/image2.jpg");

                image1.setAbsolutePosition(0, 0);
                image2.setAbsolutePosition(0, 0);

                PdfContentByte byte1 = writer.getDirectContent();
                PdfTemplate tp1 = byte1.createTemplate(600, 150);
                tp1.addImage(image2);

                PdfContentByte byte2 = writer.getDirectContent();
                PdfTemplate tp2 = byte2.createTemplate(600, 150);
                tp2.addImage(image1);

                byte1.addTemplate(tp1, 0, 715);
                byte2.addTemplate(tp2, 0, 0);

                Phrase phrase1 = new Phrase(byte1 + "", FontFactory.getFont(FontFactory.TIMES_ROMAN, 7, Font.NORMAL));
                Phrase phrase2 = new Phrase(byte2 + "", FontFactory.getFont(FontFactory.TIMES_ROMAN, 7, Font.NORMAL));

                HeaderFooter header = new HeaderFooter(phrase1, true);
                HeaderFooter footer = new HeaderFooter(phrase2, true);
                document.setHeader(header);
                document.setFooter(footer);
                document.close();
                System.out.println("File is created successfully showing header and footer.");
                }
                catch (Exception ex){
                    System.out.println(ex);

                }
            }
        }
like image 27
CloudyMarble Avatar answered Oct 20 '22 16:10

CloudyMarble