0

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 Chrome is not used.

J Roq
  • 171
  • 1
  • 8

3 Answers3

1

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).

JJ.
  • 5,425
  • 3
  • 26
  • 31
  • Again, the requirement is "No plugins installed/Use only native Java sdks/no applets/no jsf". – J Roq Aug 24 '11 at 01:12
  • Ok well you can probably use Java to read the PDF file and generic static image files from the file, which can definitely be viewed in the browser without plugins. – JJ. Aug 24 '11 at 01:15
  • See this post for ideas/pointers on how to accomplish that: http://stackoverflow.com/questions/550129/export-pdf-pages-to-a-series-of-images-in-java . – JJ. Aug 24 '11 at 01:16
  • Sure I could do that but the problem is the navigation for each image plus where the images would be stored once processed, I was given a red light when I suggested Applets and JSF. Thanks for the valiant attempt dude! ^^ – J Roq Aug 24 '11 at 01:23
  • What navigation? Save the images you create on your server (Output via Java FileOutputStream) and then put them in your HTML document one after another: ` etc. Add some links to multiple HTML pages if there are too many images to display on one page. Not difficult! – JJ. Aug 24 '11 at 01:25
  • Navigating through the PDF. If it's not too difficult then I guess that could be a solution! Thanks, I'd give you my best answer award but I already gave it. I hope a simple "Thank You" would be enough, good sir. :) – J Roq Aug 24 '11 at 01:38
  • Sure, glad I could help. Perhaps you could at least "upvote". In the future consider waiting longer for other possible responses. You never know who/what might come along. – JJ. Aug 24 '11 at 01:44
  • Sure good sir! Once I get 15 rep I will, this page is bookmarked. – J Roq Aug 24 '11 at 02:22
  • FYI you can just uncheck the existing green check and change it. It gives us both rep points. – JJ. Aug 24 '11 at 10:42
0

+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);
        }

    }
}
Lucas Holt
  • 3,826
  • 1
  • 32
  • 41
Juan Rojas
  • 8,711
  • 1
  • 22
  • 30
0

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.

maerics
  • 151,642
  • 46
  • 269
  • 291
  • Thanks! Guess I should give up now. :) – J Roq Aug 24 '11 at 01:04
  • Don't give up! Just figure out what is possible and what is not and go from there! – maerics Aug 24 '11 at 01:05
  • But the requirement is "No plugins installed/Use only native Java sdks/no applets/no jsf". – J Roq Aug 24 '11 at 01:11
  • Err, I was speaking generally. If you're being asked to do something impossible then explain to your employer why the requirements are impossible and offer workarounds. – maerics Aug 24 '11 at 01:15
  • Yeah that was what I was thinking too, it was impossible. The boss finally gave up. Thanks for the support, and your idea isn't wasted, I learned something new today. :) – J Roq Aug 24 '11 at 01:21