jax ws - pdf生成器文本和jax - rs



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

下面是我的解决方案,简化到适合这里。我在generate方法中使用JDK 8 lambdas,如果你不能,只需返回一个实现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();
    }
}

}

最新更新