在IText中添加图像时,PDF文件变为0 kb

时间:2015-03-25 06:48:37

标签: pdf pdf-generation itext itextpdf

我正在尝试创建一个显示姓名,停止号码和票价的pdf文件。代码编译并运行完美,但当我尝试在其中添加图像时,它创建的pdf文件为0 kb并且已损坏。我已经被困在这里几个小时了,仍然无法找到我的代码中的错误。我只是想在我的pdf文件上添加一个图像。任何帮助,将不胜感激。感谢。

public class PDFDisplay {

public static void generatePDF(PassengerBean passengerBean) throws DocumentException, MalformedURLException, IOException {
     Document document = new Document();

     try {
         final Chunk NEWLINE = new Chunk("\n");
          PdfWriter.getInstance(document,
              new FileOutputStream("C:\\sample.pdf"));

          document.open();

          Image img = Image.getInstance("image/mrt.jpg");
            document.add(new Paragraph("Sample 1: This is simple image demo."));
            document.add(img);


          String hr = "-----------------------------------------------------------";
          String spacer = " ";
          String name = "Passenger Name: " + passengerBean.lname + "," +  " " + passengerBean.fname;
          String dest = "Destination: " + passengerBean.dest + " STATION";
          String stopno = passengerBean.stop;
          double fare = passengerBean.fare;
          String fare1 = "Fare: PHP" + " " + String.valueOf(fare);
          String ccnum = "CREDIT CARD NUMBER: " + " " + "************" + passengerBean.ccnum.substring(Math.max(0, passengerBean.ccnum.length() - 4));

            Paragraph para8 = new Paragraph(32);
            para8.setSpacingBefore(100);
            para8.setSpacingAfter(10);
            para8.add(new Chunk(spacer));
            document.add(para8);

            Paragraph para9 = new Paragraph(32);
            para9.setSpacingBefore(100);
            para9.setSpacingAfter(10);
            para9.add(new Chunk(hr));
            document.add(para9);

            // Setting paragraph line spacing to 32
            Paragraph para1 = new Paragraph(32);
            para1.setSpacingBefore(5);
            para1.setSpacingAfter(10);
            para1.add(new Chunk(name));
            document.add(para1);

            Paragraph para2 = new Paragraph();
            para2.setSpacingAfter(10);
            para2.add(new Chunk(dest));
            document.add(para2);

            Paragraph para3 = new Paragraph();
            para3.setSpacingAfter(10);
            para3.add(new Chunk(stopno));
            document.add(para3);

            Paragraph para4 = new Paragraph();
            para4.setSpacingAfter(10);
            para4.add(new Chunk(fare1));
            document.add(para4);

            Paragraph para5 = new Paragraph();
            para5.setSpacingAfter(10);
            para5.add(new Chunk(ccnum));
            document.add(para5);


          document.close();



        } catch (DocumentException e) {
          e.printStackTrace();
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        }
}
}

1 个答案:

答案 0 :(得分:1)

您可能无法获得图像。 尝试使用

打印图像的网址
System.out.print(img.getUrl());

我已经将您的代码测试到我的本地,并在输出中提供了正确的pdf文件。