pdf生成器Itext和JAX-RS

pdf生成器Itext和JAX-RS,itext,jax-ws,Itext,Jax Ws,我想知道如何创建使用Itext生成pdf的类,并使用JAX-RS使用@GET和@products注释将其发送到web浏览器。下面是我的解决方案,简化后适合这里。我在generate方法中使用JDK 8 lambda,如果不能,只需返回一个实现StreamOutput的匿名内部类即可 @Path("pdf") @Produces(ContractResource.APPLICATION_PDF) public class PdfResource { public static final

我想知道如何创建使用
Itext
生成pdf的类,并使用
JAX-RS
使用
@GET
@products
注释将其发送到web浏览器。

下面是我的解决方案,简化后适合这里。我在
generate
方法中使用JDK 8 lambda,如果不能,只需返回一个实现StreamOutput的匿名内部类即可

@Path("pdf")
@Produces(ContractResource.APPLICATION_PDF)
public class PdfResource {

    public static final String APPLICATION_PDF = "application/pdf";

    @GET
    @Path("generate")
    public StreamingOutput generate() {
        return output -> {
            try {
                generate(output);
            } catch (DocumentException e) {
                throw new IOException("error generating PDF", e);
            }
        };
    }

    private void generate(OutputStream outputStream) throws IOException, DocumentException {
        Document document = new Document();
        PdfWriter.getInstance(document, outputStream);
        document.open();
        document.add(new Paragraph("Test"));
        document.close();
    }
}

模拟解决方案,在浏览器上提供PDF文件,而无需使用JAX-RS和IText 5 Legacy在服务器端存储文件

@Path("download/pdf")
public class MockPdfService{

@GET
@Path("/mockFile")
public Response downloadMockFile() {
    try {
        // mock document creation
        com.itextpdf.text.Document document = new Document();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        com.itextpdf.text.pdf.PdfWriter.getInstance(document, byteArrayOutputStream);
        document.open();
        document.add(new Chunk("Sample text"));
        document.close();

        // mock response
        return Response.ok(byteArrayOutputStream.toByteArray(), MediaType.APPLICATION_OCTET_STREAM)
                .header("content-disposition", "attachment; filename = mockFile.pdf")
                .build();
    } catch (DocumentException ignored) {
        return Response.serverError().build();
    }
}
}