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

PDF file turns 0 kb when image is added in IText

我正在尝试创建一个 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();
        }
}
}

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

打印 url 你的图像
System.out.print(img.getUrl());

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