Java IText 7-如何通过Rest Api发送PDF而不存储文件?
这是我第一次使用iText 7库。 我想发送通过我的Java IText 7-如何通过Rest Api发送PDF而不存储文件?,java,pdf,itext7,Java,Pdf,Itext7,这是我第一次使用iText 7库。 我想发送通过我的@Gethttp响应生成的pdf,而不将文件存储在我的服务器上。 我试过这个: @GET @Path("/generatePDF") @Produces({MediaType.APPLICATION_OCTET_STREAM}) public Response generatePDF() { try { String text ="This is the text of my pdf"; ByteArr
@Get
http响应生成的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();
}
}
但我面临以下错误:
GRAVE[http-nio-8080-exec-4]org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteToMessageBodyWriter未找到媒体类型=应用程序/八位字节流,类型=类java.io.ByteArrayOutputStream,genericType=类java.io.ByteArrayOutputStream
你知道怎么做吗?我在文档中没有找到任何内容。
Response
期望InputStream
而不是OutputStream
。因此,只需将字节重新包装到InputStream
中,然后发送响应:
ByteArrayInputStream pdfStream = new ByteArrayInputStream(baos.toByteArray());
return Response.ok().entity(pdfStream);
您是否尝试过使用
Response.ok().entity(baos.toByteArray())…
而不是Response.ok().entity(baos)…
?没有更多错误。非常感谢你!也谢谢:)我直接使用baos.toByteArray()来避免创建临时对象:)