2017-04-11 24 views
0

所以我刚刚听说有关称为iText的API,我并不真正熟悉它的使用。用servlet写一个pdf文件(模板)

所以我现在的问题是我想写一个现有的PDF文件(模板)在jsp形式提供的信息。 我尝试了一些在互联网上找到的代码,它工作正常,但没有在servlet上。 谢谢。

编辑这里是我发现并试图放入servlet的代码。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 


      Document document = new Document(PageSize.A4); 
      try { 

       PdfWriter.getInstance(document, new FileOutputStream(new File(
         "test.pdf"))); 
       document.open(); 
       String content = request.getParameter("aa"); 
       Paragraph paragraph = new Paragraph(content); 
       document.add(paragraph); 

      } catch (DocumentException e) { 
       e.printStackTrace(); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } finally { 
       document.close(); 
      } 
     } 
+0

你可以分享你的尝试吗? – soorapadman

+0

_I尝试在互联网上找到一些代码_ - 告诉我们你在哪里找到该代码,以便我们也可以尝试。 –

+0

我相应地更新了我的帖子。 –

回答

0

我看看你的servlet和我看到:

new FileOutputStream(new File("test.pdf")) 

这意味着,你写你的服务器上的文件到文件系统。我没有看到你发送任何字节到response对象,所以没有显示在浏览器中。

您声称iText“不能在servlet中工作”,但这是不正确的:如果没有异常抛出,则在服务器端的工作目录中创建一个名为“test.pdf”的文件。这不是很聪明,因为越多的人使用您的servlet,更多的PDF将被保存在服务器上。你可能不希望这样。您可能想要在内存中创建PDF,并将PDF字节提供给浏览器。

简短的回答你的问题,是你应该写的PDF到response对象的OutputStream,而不是到FileOutputStream

public class Hello extends HttpServlet { 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
     response.setContentType("application/pdf"); 
     try { 
      // step 1 
      Document document = new Document(); 
      // step 2 
      PdfWriter.getInstance(document, response.getOutputStream()); 
      // step 3 
      document.open(); 
      // step 4 
      document.add(new Paragraph("Hello World")); 
      document.add(new Paragraph(new Date().toString())); 
      // step 5 
      document.close(); 
     } catch (DocumentException de) { 
      throw new IOException(de.getMessage()); 
     } 
    } 
} 

但是,为了避免这种方法已知的问题,您应该还阅读官方文件。搜索关键字 “的servlet”,你会发现这些常见问题的条目:

既然你是新的iText的,它是令人惊讶的是,您选择使用iText 5而不是更新的iText 7,iText 7与iText 5不兼容;它是对图书馆的完全重写。我建议您使用的iText 7,因为我们已经停止了对iText的积极发展5.

更新:“该文件有没有网页”

称为错误表示您正在尝试创建没有任何内容的文档。

替换:

String content = request.getParameter("aa"); 
Paragraph paragraph = new Paragraph(content); 
document.add(paragraph); 

有了:

document.add(new Paragraph("Hello")); 

我的猜测是,出事了,而获取的参数"aa",没有造成内容被添加到文档中。

+0

嗨,感谢您的广泛响应:D 我试过你提到的,它的工作原理, 非常感谢。 –