如何在java servlet中将byte []转换为PDF?

时间:2016-05-08 11:38:58

标签: java servlets pdf-generation bytearray

我正在尝试用字节数组创建一个PDF文件。在将字节写入文件之前,我将它们打印为字符串并正确打印内容但是当我打开自动下载的PDF文件时,由于文件以某种方式损坏,它不会打开。

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    long logFileId = Long.valueOf(request.getParameter(REQUEST_PARAM_DOCUMENT_ID));
    MappingInfo mapping = documentService.getMapping(logFileId);
    byte[] file = mapping.getImportLogs();

    System.out.println(new String(file));

    response.setContentType("application/pdf");
    response.setContentLength(file.length);

    // response.reset();
    response.setContentType("application/pdf");
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=ImportLog.pdf");
    response.setHeader(headerKey, headerValue);

    OutputStream outStream = response.getOutputStream();
    outStream.write(file);
    outStream.flush();
    outStream.close();
  }

有人可以指出我在这里犯的错误吗?我也试图不使用任何第三方API。

由于

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

我不确定必须为此使用第三方API。我能够使用iText API实现这一目标。可能会帮助别人。

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    long logFileId = Long.valueOf(request.getParameter(REQUEST_PARAM_DOCUMENT_ID));
    MappingInfo mapping = documentService.getMapping(logFileId);
    byte[] file = mapping.getImportLogs();

    OutputStream outStream = response.getOutputStream();
    Document document = new Document();
    try {
      PdfWriter.getInstance(document, outStream);
      document.open();
      document.add(new Paragraph(new String(file)));
      document.add(Chunk.NEWLINE);
      document.add(new Paragraph("a paragraph"));
    } catch (DocumentException e) {
      e.printStackTrace();
    }
    document.close();

    response.setContentLength(file.length);
    response.setContentType("application/pdf");
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=ImportLog.pdf");
    response.setHeader(headerKey, headerValue);

    outStream.write(file);
    outStream.flush();
    outStream.close();
  }