2017-10-19 61 views
0

这是我第一次使用图书馆iText 7. 我想发送通过我的@Get http响应生成的PDF格式,而无需将文件存储在我的服务器上。 我尝试这样做:IText 7 - 如何通过Rest Api发送PDF而不存储文件?

@GET 
@Path("/generatePDF") 
@Produces({MediaType.APPLICATION_OCTET_STREAM}) 
public Response generatePDF() { 
    try { 

     String text ="This is the text of my pdf"; 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     PdfDocument pdfDoc = new PdfDocument(new PdfWriter(baos)); 

     Document doc = new Document(pdfDoc);    
     doc.add(new Paragraph(text)); 
     doc.close(); 
     System.err.println("doc closed"); 


     return Response.ok().entity(baos). 
       header("Content-Disposition", 
       "attachment; filename=\"mypdf - " + new Date().toString() + ".pdf\"") 
       .header("Expires", "0") 
       .header("Cache-Control","must-revalidate, post-check=0, pre-check=0") 
       .header("Pragma", "public") 
       .build(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); 
    } 
} 

但我面临着以下错误:

坟墓[HTTP-NIO-8080-EXEC-4] org.glassfish.jersey.message.internal.WriterInterceptorExecutor $ MediaWriterInterceptor.aroundWriteTo未找到媒体类型= application/octet-stream,type = class java.io.ByteArrayOutputStream,genericType = class java.io.ByteArrayOutputStream。

你有什么想法如何做到这一点?我没有在文档中找到任何内容。

+1

您是否尝试过使用'Response.ok()实体(baos.toByteArray())...',而不是'Response.ok( ).entity(BAOS)...'? – mkl

+0

没有更多的错误与此。非常感谢你 ! – anais1477

回答

1

Response预计InputStream而不是OutputStream。因此,只要重新包装你的字节到InputStream和发送响应:

ByteArrayInputStream pdfStream = new ByteArrayInputStream(baos.toByteArray()); 
return Response.ok().entity(pdfStream); 
+0

也谢谢:) 我直接使用了baos.toByteArray()来避免创建临时对象:) – anais1477

相关问题