【问题标题】:How to convert byte[] to PDF in java servlet?如何在 java servlet 中将 byte[] 转换为 PDF?
【发布时间】:2016-09-03 02:55:07
【问题描述】:

我正在尝试使用字节数组创建 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。

谢谢

【问题讨论】:

  • 您需要一个第三方库(例如来自 Apache 的 iText)才能编写 PDF。您不能简单地将字节写入文件,除非这些字节来自另一个 PDF。
  • response.reset(); 正在清除您的所有标题。我会删除那条线。
  • @MichaelMarkidis 已删除,但仍然是同样的问题。
  • convert byte[] to PDF - 你的byte[] 包含什么?如果它还没有包含PDF,你想如何设置你的PDF?跨度>
  • @mkl 它包含一个字符串(字符),我成功地 Sysout。

标签: java servlets pdf-generation bytearray


【解决方案1】:

您可以从 JavaPoint 查看此示例。 http://www.javatpoint.com/how-to-write-data-into-PDF-using-servlet

【讨论】:

  • 您的示例未显示如何将字节 [] 转换为 PDF
【解决方案2】:

我不确定我们是否必须为此使用第三方 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();
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-27
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 2011-10-10
    • 2011-01-12
    • 1970-01-01
    相关资源
    最近更新 更多