开发者

Output PDF using ServletOutputStream

I just want to ask if there is anyway to output PDFs in a webpage using the ServletOutputStream? For example I want to make the PDF still show if there is not Adobe plugin installed or Chr开发者_如何学Come is not used.


The user will have to have some type of PDF viewer installed on their PC to open/read the PDF file, whether it is Adobe Reader or something else. You can send the user a PDF file for either opening in the browser or download (Save as attachment) simply by sending the correct HTTP headers. Specifically:

Content-type: application/pdf
Content-Disposition: attachment; filename=downloaded.pdf
Content-Length: XXX
Content-Transfer-Encoding: base64

The Content-Disposition header is the one that suggests a download vs "open in browser". Once you have sent the headers, send a blank line and then write out your data (often base64 encoded).


Your servlet can output any type of document it wants; however, the browser will only display documents that it knows how to, either natively (e.g. HTML, text, GIF, PNG, JPG, etc.) or via a plugin (PDF, SWF, etc).

If your servlet outputs a valid PDF document and the browser can't display it natively (like Chrome can) or can't load a plugin to render it (like Adobe) then it will probably ask the user to save it or choose a program which might be able to display it.


+1 because is a valid question.

Client Side

You can use pdf.js a javascript library from mozilla to display pdfs as images

Server Side

If your pdf is on the File System modified from here

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String pdfFileName = "pdf-test.pdf";
    String contextPath = getServletContext().getRealPath(File.separator);
    File pdfFile = new File(contextPath + pdfFileName);

    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "inline; filename=" + pdfFileName)
    response.setContentLength((int) pdfFile.length());

    FileInputStream fileInputStream = new FileInputStream(pdfFile);
    OutputStream responseOutputStream = response.getOutputStream();
    int bytes;
    while ((bytes = fileInputStream.read()) != -1) {
        responseOutputStream.write(bytes);
    }
}

If you are generating pdf in memory using libraries like pdfbox

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    int marginTop = 30;
    String title = "HELLO WORLD";

    final PDFont fontData = PDType1Font.HELVETICA;
    final int fontSize = 8;

    //java8 color issue
    System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider");

    final PDPage page = new PDPage();
    final PDFont fontLabel = PDType1Font.HELVETICA_BOLD;
    final int titleFontSize = 12;
    float heightLabelText = fontLabel.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize;

    try (final PDDocument pdf = new PDDocument())
    {
        pdf.addPage(page);
        try (PDPageContentStream stream = new PDPageContentStream(pdf, page)) {
            float top = page.getMediaBox().getHeight() - marginTop;

            float titleWidth = fontLabel.getStringWidth(title) / 1000 * titleFontSize;

            stream.setFont(fontLabel, titleFontSize);
            stream.beginText();
            stream.newLineAtOffset((page.getMediaBox().getWidth() - titleWidth) / 2, top - 25);
            stream.showText(title);
            stream.endText();
        }
        try(ByteArrayOutputStream output = new ByteArrayOutputStream()) {
            pdf.save(output);
            resp.setContentType("application/pdf");
            resp.addHeader("Content-Disposition", "inline; filename=\"yourFile" + "-" + new Random().nextInt() + ".pdf" + "\"");
            byte[] bytes = output.toByteArray();
            resp.getOutputStream().write(bytes);
            resp.setContentLength((int) bytes.length);
        }

    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜