【问题标题】:PDF base64 string FilenamePDF base64 字符串文件名
【发布时间】:2017-04-19 16:21:44
【问题描述】:

我对 PDF base64 字符串有疑问,我不知道为什么文件名没有出现在 pdf 查看器中,而不是文件名我有一组我认为与字节数组相关的字符。

服务器端

    @RequestMapping(value = "/report", produces = "application/pdf")
    public @ResponseBody HttpEntity<byte[]> reportPdf(HttpServletRequest request, HttpServletResponse response)
    ...
    byte[] document = report.getBytes(StandardCharsets.UTF_8);
    ...
    HttpHeaders header = new HttpHeaders();
    header.setContentType(new MediaType("application", "pdf"));
    header.set("Content-Disposition", "inline; filename=asdfasdfasdf.pdf");
    header.setContentLength(document.length);

    return new HttpEntity<byte[]>(document,header);

我正在通过 JavaScript 应用程序调用此 REST 服务,但我不知道如何控制此文件名。

谁能给我任何线索?在这种情况下可以更改这个新文件名吗?

问候!

【问题讨论】:

    标签: java spring rest pdf


    【解决方案1】:

    对文件名进行 url 编码更安全。

    String fileName = "asdfasdfasdf.pdf";
    URLEncoder.encode(fileName, "utf-8");
    HttpHeaders header = new HttpHeaders();
    header.setContentType("application/pdf");
    header.set("Content-Disposition", "inline; filename=" + fileName);
    

    或者您甚至可以尝试将文件名放在双引号 "" 之间

    HttpHeaders header = new HttpHeaders();
    header.setContentType("application/pdf");
    header.set("Content-Disposition", "inline; filename=\"asdfasdfasdf.pdf\"");
    

    【讨论】:

    • 它不起作用,你知道数据URI中是否包含标题信息吗?
    【解决方案2】:

    最后我找到了这样的解决方法:

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    
            //Setting up Jasper print
            JasperPrint print = getJasperPrint(REPORTS_PATH + reportPath, result, params);
    
            //Setting up Exporter configuration
            SimplePdfExporterConfiguration pdfExportConfiguration = new SimplePdfExporterConfiguration();
            pdfExportConfiguration.setMetadataTitle(title);
    
            //Setting up Jasper exporter
            JRPdfExporter exporter = new JRPdfExporter();
            exporter.setExporterInput(new SimpleExporterInput(print));
            exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));
            exporter.setConfiguration(pdfExportConfiguration);
    
            //Exporting pdf
            exporter.exportReport();
    enter code here
    

    使用 SimplePdfExporterConfiguration,您将在报告中添加额外信息,因此 PDF 查看器会显示正确的名称而不是字节数组代码。

    【讨论】:

      猜你喜欢
      • 2022-12-04
      • 1970-01-01
      • 2021-01-23
      • 2021-12-12
      • 1970-01-01
      • 2016-04-14
      • 2015-04-18
      • 2017-01-29
      • 1970-01-01
      相关资源
      最近更新 更多