【问题标题】:How do insert itext pdf into database如何将itext pdf插入数据库
【发布时间】:2015-05-25 09:12:28
【问题描述】:

我正在用jsp编码。我已经使用 itext 生成了 pdf。并尝试将文档保存到数据库(mysql)中。

        String filename="patient.pdf";
        response.setContentType("application/pdf");
        Document document = new Document();
        PdfWriter pd= PdfWriter.getInstance(document, new FileOutputStream(filename));
        document.open();
        document.addTitle("Dentistree");
        document.add(new Paragraph("Hello,"+"\n\t"+"Thanks for making an appointment to Dentistree"+"\n\t"+"You have provided case history for your appointment. Here are the details of the appointment\n\t"+"List of the diseases that you are suffering through are as follows:"+di+"\n\n\nAre you pregnant?\t"+pregnant+"\n\n\nAre nursing a child?\t"+nursing+"\n\n\nDo you chew pan-masala?\t"+pan+"\n\n\nDo you smoke?\t"+smoke+"\n\n\nAllergic?\t"+all+"List of the medicines:"+medicines));
        document.close();



        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dentistree","root", "tiger");
        String str="insert into appointment(email,pdf)  values(?,?)";
        PreparedStatement st = con.prepareStatement(str);
        st.setString(1, mail);
        st.setBlob(2,pd);

Java 编码新手。请帮忙

【问题讨论】:

  • 任何问题/错误/异常?请问您有什么问题?
  • 如果您需要将 PDF 作为 BLOB 存储到数据库中,为什么要在文件系统上创建文件?在内存中创建 PDF 作为 ByteArrayOutputStream 并将生成的 byte[] 存储在您的数据库中。
  • 你真的执行了语句吗?

标签: jsp itext


【解决方案1】:

你的问题充满了矛盾。

  1. 您说您要创建一个 PDF 文件(这是一个二进制文件),但您使用的是 JSP。但是,如果您完成了有关 JSP 的课程(而不是在会走路之前尝试跑步),您会发现使用 JSP 创建二进制文件未完成。请改用纯 Java 或 Java Servlet。
  2. 您说您想将 PDF 存储在数据库中,但是,当我查看您的代码时,我看到了 response.setContentType("application/pdf");,这意味着您想将 PDF 发送到浏览器。
  3. 您说要将 PDF 存储在数据库中,同时您尝试将其发送到浏览器,但您没有这样做,而是将 PDF 保存在服务器的文件系统中:new FileOutputStream(filename) .就好像你无法决定你真正想做什么。
  4. 另外:您在打开文档之后为文档添加标题。您应该在打开文档之前添加标题

如我的评论所述,您应该在内存中创建 PDF:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter pd= PdfWriter.getInstance(document, baos);
document.open();
document.add(new Paragraph("Hello");
document.close();

现在您有了baos 对象,您可以从中获取完整的PDF 作为byte[]

byte[] pdf = baos.toByteArray();

这已经在 StackOverflow 上回答过:Save itext pdf as blob without physical existence. 拥有byte[] 后,如果有额外要求,您还可以将 PDF 发送到浏览器。请参阅我对Pdf file not loading properly created by the servlet 的回复,了解它是如何完成的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    相关资源
    最近更新 更多