PDF Download From Servlet

Hi guys,
I'm having issues creating a file download servlet to download pdf files. I can successfully download text files using this code. For some reason however I cannot download a pdf using the same code. On execution, the browser will present me with a dialogue box asking me to open, save or cancel. If i open or save and open later I get an error message saying that the pdf file is corrupt or damaged and won't open properly. I have tried opening the original pdf on the server and there are no problems there. I have absolutely no idea why this is happening. Can someone point me in the right direction please.
     request.setAttribute("message", "This is a warning");
          String urlString = "test.jsp";
          DataInputStream dataInputStream=null;
          ServletOutputStream out = response.getOutputStream();
          String filePath = "/files";
          String originalFilename="test.pdf";
          File f = new File(originalFilename);
          response.setContentType("application/pdf");
          response.setContentLength((int) f.length());
          response.setHeader( "Content-Disposition", "attachment; filename=" +originalFilename );
          try{
               dataInputStream = new DataInputStream(new FileInputStream(filePath+originalFilename));
               byte[] bbuf = new byte[1024];
               dataInputStream.read() method
               while (dataInputStream.read(bbuf) != -1){
                    out.write(bbuf);
          } catch(IOException e){
               e.printStackTrace();
          } finally{
               dataInputStream.close();
               out.flush();
               out.close();
     }                   Thank You

Try this
in this scenario i'm reading file from databsae (Object type in SQLServer) as bytes
String path=getServletContext().getRealPath("/");
               byte[] buf = new byte[3 * 1024 * 1024];
               HashMap fileInfo=new HashMap();
          System.out.println("servlet called----> "+path);
          //String fileName=(String)arg0.getSession().getAttribute("fileName");
          int id=Integer.parseInt(arg0.getParameter("id"));
          String pageName=(String)arg0.getParameter("pageName");
          TrainingDBImpl dbImpl= new TrainingDBImpl();
          if(pageName.equals("Employee")){
               fileInfo=dbImpl.getEmpFile(id);     
          }else if(pageName.equals("Courses")){
               fileInfo=dbImpl.getFile(id);
          //fileInfo=dbImpl.getFile(id);
          //fileInfo=dbImpl.getEmpFile(id);
          String fileName=fileInfo.get("FileName").toString();
          buf=(byte[])fileInfo.get("EmployeeFile");
response.setHeader("Content-Disposition","attachment;filename=\""+fileName+"\"");
OutputStream out = response.getOutputStream();
          ByteArrayInputStream bain=new ByteArrayInputStream(buf);
     BufferedInputStream bIn = new BufferedInputStream(bain);
     int bytesRead;
     while ((bytesRead = bIn.read(buf)) != -1) {
     out.write(buf, 0, bytesRead);
     out.flush();
     bIn.close();
     out.close();

Similar Messages

  • Display PDF document from Servlets to browser - how 2 change the title

    Hi, need help of changing the html title when Display PDF document from Servlets to browser. By default the browser's title shows the obsolute URL where the rdf comes from (i.e. http://www.google.com/sample.pdf), because servlet responds a binary data (PDF), there seems to be no other way to change the browser's title to fit my own choice.
    Appreciate your quick help,

    You can try and check with
    .setTitle("Welcome");

  • With OSX10.7.5 and Adobe Reader 11.0.02 when I try to open a PDF downloaded from the web I get 'There was an error opening this document. This file is damaged and could not be repaired. Preview will not open either. Older PDFs OK.

    I am running OS X 10.7.5 and Adobe Reader 11.0.02. In the last few days I have been unable to open PDF's downloaded from the web. Reader gives the error message 'There was an error opening this document. The file is damaged and could not be repaired'. Removing Reader and trying to use Preview to open these files give the error 'Preview cannot open this file. It may be damaged or use a file format that Preview doesn't recognise' (or something like that). Downloading the same files with Reader removed from my Mac Preview opens the files OK.
    I was recently prompted to update Adobe software but did not note exactly what the update was nor when it was done.
    Reader and Preview will both open PDFs I downloaded a week ago. Reader will also open files downloaded on another Mac running OS X 10.0.0 and copied to my Mac. Any ideas?

    Back up all data.
    Triple-click the line of text below to select it, the copy the selected text to the Clipboard (command-C):
    /Library/Internet Plug-ins
    In the Finder, select
    Go ▹ Go to Folder
    from the menu bar, or press the key combination shift-command-G. Paste into the text box that opens (command-V), then press return.
    From the folder that opens, remove any items that have the letters “PDF” in the name. You may be prompted for your login password. Then quit and relaunch Safari, and test.
    The "Silverlight" web plugin distributed by Microsoft can also interfere with PDF display in Safari, so you may need to remove it as well, if it's present.
    If you still have the issue, repeat with this line:
    ~/Library/Internet Plug-ins
    If you don’t like the results of this procedure, restore the items from the backup you made before you started. Relaunch Safari again.

  • Error opening PDF downloaded from Interactive Report

    hi -- I'm getting an error opening a PDF file downloaded from an interactive report.
    I've seen on the forum that this could be related to the size of the file, but I've tried
    this out on 10-row results (1k files) and it's still an issue.
    I save the file to my file system. If I try to open it in Adobe Reader, I get:
    File does not begin with '%PDF-'
    and
    Adobe Reader could not open <filename>.pdf because it is either not a supported
    file type or because the file has been damaged (for example, it was sent as an email
    attachment and wasn't correctly decoded).
    If I try to open in Internet Explorer, I get:
    File does not begin with '%PDF-'
    Other users are having the same problem. Download to csv and open in Excel works fine.
    Do I need to have special print attributes for this? I didn't think so... I'm just using the defaults
    (response header = report settings, content disposition = attachment).
    Ideas?
    Thanks,
    Carol

    Hi,
    I'm having the same problem that was described above, and my site does have BI Publisher installed, and it does successfully produce readable pdfs for many reports.
    But there are other reports, even reports produced using the Apex Wizard and all defaults, that just keep producing the same Adobe Reader error reported above, ie
    "Adobe Reader could not open <filename>.pdf because it is either not a supported
    file type or because the file has been damaged (for example, it was sent as an email
    attachment and wasn't correctly decoded)."
    Any suggestions?
    Cheers,
    Peter

  • Unable to open PDF output (PDF downloaded from Interactive Report--APEX)

    Hi,
    I'm getting below error while opening a PDF file downloaded from an interactive report (APEX).
    Adobe reader cound not open "TEST.pdf"because it is either not supportd file or because the file has been damaged.
    Thanks & Regards,
    Ramamuni.

    Steps of pdf Printing of Report from FOP:
    1) Download and unzip the following needed files in D:\Apex_fop directory.
    2) Open your command prompt .
    Change the directory to D:\Apex_fop\cocoon-2.1.11.
    Set the Java_Home environment variable as: set JAVA_HOME= C:\Program Files\Java\jdk1.5.0_21
    then type build war
    3) After getting the prompt back as D:>Apex_fop>cocoon-2.1.11>
    Copy coocon.war file from the folder D:\Apex_fop\cocoon-2.1.11\build\cocoon.
    Paste this file into webapps subdirectory in main tomcat directory having path as D:\APEX_FOP\apache-tomcat-6.0.26\webapps.....place it in the top
    level of webapps directory.
    4) Now just startup tomcat as D:>APEX_FOP>apache-tomcat-6.0.26>bin>startup.bat
    The cocoon.war file will automatically uncompressed as directory.
    5) To change the port of apache tomcat , edit apache-tomcat-6.0.26\conf\server.xml & change port attribute of Connector element from 8080 to 8181.
    Just check whether Tomcat is running or not as http://localhost:8181/
    & to check cocoon type http://localhost:8181/cocoon/
    6) Now copy fop_post directory & paste it undes new cocoon directory in webapps having path as D:\APEX_FOP\apache-tomcat-6.0.26\webapps
    \cocoon.
    7) Now you need to do some apex settings as follows:
    In APEX, just log in as ADMIN into apex/apex_admin and went to Instance Settings and did the following:
    - Print Serverr: Standard Support
    - Print Server Protocol: HTTP
    - Print Server Host Address:localhost
    - Print Server Port: 8181
    - Print Server Script: /cocoon/fop_post
    In your APEX application, in the Regions section, Click on the Print link next to your report and do the following settings:
    - Enable Report Printing: Yes
    - Link Label: Print
    - Response Header: Report Settings
    - View File As: Attachment
    - Output Format: PDF
    - Report Layout: Default Report Layout
    - Print URL: f?p=&APP_ID.:1:&SESSION.:FLOW_XMLP_OUTPUT_R1063230002781575
    8) Open up the Report Page and click Print , You will get the pdf report.
    I am sure this will help you
    Regards

  • Display PDF document from Servlets to browser

    Hi All,
    I am displaying a PDF document in Servlet after reading the stream. PDF size is of more than 3MB, so it takes a lot of time to get downloaded and to display on the browser.
    Is there anyway to display the initial pages to the browser (whatever data has been sent ). Can you please help me in this.
    Please treat it as urgent
    Thanks in advance,
    Purav

    I have to ask:
    Why are you trying to pump a PDF to the client? Is it stored in a database rather than to the file system? Or...are you trying to display a PDF file in HTML format so end users don't need Acrobat?
    If neither of these is the case, couldn't you just send a response.redirect("path to PDF file") and get the same result without all the headache?
    If case 1 (the PDF is stored in the database and not the filesystem), you may want to ask why? You could simply create a table that maps some document_id to a local file path. That way if you need to delete it or change it, you know what and where it is.
    If case 2 (you want to read a PDF and display as HTML to the client) you should use a parser like:
    http://www.tethys-milano.com/tethys/pdfparser.xtmlor
    http://www.jpedal.org/

  • Trouble Opening PDFs Downloaded From Web

    I have Adobe Acrobat Pro (10.1.6) for the latest Mac OSX and I can open and edit PDFs from others. But I cannot open any PDFs I download from the Web. I get the message “There was an error opening this document. The file is damaged and could not be repaired.” Any suggestions?

    Trash the app and download it again.

  • Allowing PDF downloads from a specific URL

    I accidentally blocked an URL (e.g. www.XXXXX.org) and now I need to download from that site but I can't. I went into Privileged Access and under Add File I added said URL but it still blocks me. Any advice?

    Blocked where: your browser, firewall, ...?  You need to unblock it from where you blocked it in the first place.
    What exactly do you get when you try to download anything from that URL?  (Adobe Reader is not involved in downloading anything.)

  • When I try to open a PDF downloaded from Adobe DC I get an error message:Adobe Acrobat Reader DC could not open 'nrneph.2015.33.pdf' because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email

    When I try to download a PDF from Adobe DC, I get an error message: "Adobe Acrobat Reader DC could not open 'nrneph.2015.33.pdf' because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded)"
    I am using a Macbook Pro, OSX 10.9.5, Safari browser. Previous versions of Adobe Acrobat have worked fine for years.
    WGC

    What's the name of the file you are attempting to open?  Is it "ScreenFlow_4.5.2.dmg"?  If it is the correct name then the message is correct and you are attempting to open a file with DMG files extension and not one with a PDF file extension.  Adobe Reader opens PDF files an not any other file type.

  • PDF download from BSP application

    hi all,
    With the bellow code i am able to download to PDF from BSP application
    Issue is when i click on the download button waiting popup window is not disappearing even after PDF displayed.
    Please help me to resolve how to stop this waiting popup window.
    response->delete_header_field( name = 'Cache-Control' ).  "#EC NOTEXT
      response->delete_header_field( name = 'Expires' ).        "#EC NOTEXT
      response->delete_header_field( name = 'Pragma' ).         "#EC NOTEXT
    Deactivated because of Note 904314 and Kompression in Kernel
      response->set_compression( options = '4' ).
      response->set_header_field( name  = 'content-type'
                                  value = 'application/pdf' ).
      response->set_header_field(
                         name  = 'cache-control'
                         value = 'max-age=0' ).
        response->set_header_field(
                           name  = 'content-disposition'
                           value = 'attachment; filename=candidate.pdf' ).
      l_pdf_len = XSTRLEN( l_pdf_xstring ).
      response->set_data( data   = l_pdf_xstring
                          length = l_pdf_len ).
      navigation->response_complete( ).
    Any help on this is highly appreciated.
    Thanks,
    Ravi

    May be you can navigate to another page AFTER the response_complete() method and show the message that 'PDF is downloaded successfully'
    or something meanful message. so that it will get a response back from server and 'wait...Processing' message might disappear.
    I'm not sure and didnt try..may be you can give it a try and let us know..
    navigation->response_complete( ).
    navigation->goto_page(....)

  • Can't open a pdf download from my bank

    Until a few days ago, I was able to go to statements from my online banking web site.  Since I updated my google web browser, I've been unable to get the download to work.  I don't know if that browser update has anything to do with the download problem??  I can open saved (in my computer) .pdf files in Adobe Reader (10.1.1).  I've tried to update Reader and the utility says I don't need updates.  Does anyone have any ideas for me?

    This seems to be a common problem with the upgrade Adobe Reader X 10.1.1.  Mine freezes as soon as I click "Open" on any pdf file, and I have to use Task Manager to get out of the program.  An Adobe tech support person (who wouldn't help without my paying a $39 fee) did say to go to the forum on freezing at http://forums.adobe.com/thread/886700.  Try what it suggests in the way of unclicking "protected mode" from General Preferences under Edit.

  • Problem downloading from servlet in WLS6

    A servlet running in WLS6 is used for downloading files. When the file is
              selected in IE5 the dialog asking what to do with the file (open from
              current location/save) opens. If the file is small enough the service
              request is handled (file written to ServletOuputStream and stream flushed &
              closed) at the servlet side BEFORE a selection in this dialog is even made!
              So if the user selects cancel from the first dialog when the actual download
              has not even started, then it seems at the server side that the user
              downloaded the file.
              How can I change this behaviour so that nothing is written in to the
              ServletOutputStream until the client is actually receiving? I have tried to
              modify buffer size and flush all the time without success!
              

    Hi Gareth,
    I don't think it's possible to donwload classes from R/3 to CRM. It was possible between CRM 2.0c & R/3, but was deactivated as a standard functionality because the data models for classes in the two systems are to different.
    What kind of classification data would you like to download?
    Kind regards,
    Michaael.

  • How to optimize the width of column in PDF downloaded from ALV?

    Hi Gurus,
    I have an ALV from where i am downloading PDF, i have optimized the field catalog length as well in layout.
    The problem is The first column of ALV is not fully visible in downloaded PDF instead it is displayed as 800000.. actual value is 8000006.
    The field is LIFNR field and it is also referring the same data element.
    Can anybody suggest a work around for this?
    Regards
    S.Janagar.

    done with fix width option in catalog

  • HT5826 iBooks on mac does not sync PDFS downloaded from iPad?

    I recently downloaded Mavericks for my iMac, and opened up Ibooks. It syncs only the books I purchased on my iPad, but not the PDFS I downloaded on my Ipad. It shows the collections, but they are empty. Can anyone help?

    Some suggestions.
    https://discussions.apple.com/message/25039824#25039824

  • PDF Download from PL/Sql

    Hi,
    I am working on Oracle Database 11g and Apex 4.1.
    I am using the following the code to download Excel and it is working fine.
    DECLARE
      v_insert        CLOB ;
      v_download      CLOB ;
      v_length        NUMBER ;
      l_filename      VARCHAR2(100) ;
      v_blob          BLOB ;
      FUNCTION clob_to_blob_func(v_clob Clob) RETURN BLOB AS
      v_blob BLOB;
      v_in Pls_Integer := 1;
      v_out Pls_Integer := 1;
      v_lang Pls_Integer := 0;
      v_warning Pls_Integer := 0;
      v_id number(10);
      BEGIN
      dbms_lob.createtemporary(v_blob,TRUE);
      DBMS_LOB.convertToBlob(v_blob,v_clob,DBMS_lob.getlength(v_clob),
      v_in,v_out,DBMS_LOB.default_csid,v_lang,v_warning);
      RETURN V_BLOB;
      END clob_to_blob_func;
    BEGIN
      v_insert := ' ' ;
      dbms_lob.append ( v_insert, '<table border ="0.5" width = "100%">' ) ;
      DBMS_LOB.APPEND ( V_INSERT, '<tr bgcolor="#909090">' ) ;
      dbms_lob.APPEND ( v_insert, '<td>Parent ID</td> <td>ID</td> <td>Number</td> <td>System</td> <td>Price</td> <td>Type</td> ' ) ;
      dbms_lob.APPEND ( v_insert, '</tr>' ) ;
      dbms_lob.append ( v_insert, '</table>' ) ; 
      v_blob := clob_to_blob_func ( v_insert ) ;
      l_filename := 'Billing Plan.xls' ;
      OWA_UTIL.mime_header ('application/octet', FALSE);
      v_length := dbms_lob.getlength ( v_blob ) ;
      htp.p ( 'Content-length: ' || v_length ) ;
      htp.p ( 'Content-Disposition: attachment; filename="' || l_filename || '"' ) ;
      owa_util.http_header_close;
      htmldb_application.g_unrecoverable_error := TRUE ;
      wpg_docload.download_file ( v_blob ) ;
    END;
    The issue is, I want to download the same file in PDF format. So I updated the above procedure the below two lines ,
      l_filename := 'Billing Plan.pdf' ;
      OWA_UTIL.mime_header ('application/pdf', FALSE);
    But it is downloading a file but as,
    Unable to Open Document
    File type plain text document (text/plain) is not supported
    Any suggestions on how I can download the file in PDF format.
    Thanks,
    Shoaib

    You have following content in a CLOB.
    <table border ="0.5" width = "100%">
    <tr bgcolor="#909090">
    <td>Parent ID</td> <td>ID</td> <td>Number</td> <td>System</td> <td>Price</td> <td>Type</td>
    </tr>
    </table>
    You then convert it into BLOB. And now trying to download it as a PDF file. But you need to understand that your BLOB content is not actually a PDF content. PDF is a binary data with a specific format owned by Adobe.
    So this stuff is not going to work.

Maybe you are looking for

  • Really odd First Launch issues

    Hello All, I am having som really, really odd issues with my PowerMac G4... Everytime I start-up from a cold boot (I turn it off during the night...) I return in the morning, and it can't see my network! I usually just restart again, and everything i

  • System freezes randomly

    Alright, so whenever I start up my mac, it goes through the whole startup process fine. It loads Finder and I can start opening menues or starting programs. Then, roughly 30-120 seconds after the startup completes, the system freezes. This is usually

  • Personalize Absence Details in Oracle Apss R12

    Hi, I have some information in "Absence Details" in oracle Apps R12 such as Absence Status,Absence Category, Days, Hours... I want to add some details in absence details in "Leave of Absence" in oracle Apps R12 like total of days in this year, curren

  • OLEDB Syntax error INSERT INTO in DAL

    hi guys im having problems with my DAL in my school project before im starting new one maybe you can help me using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.OleDb; public class

  • Cannot open jpeg in camera raw format

    In Elements 9 I have the option to "open as..." camera raw but the camera raw window does not open up when I pick the photo and choose that option.  Any help would be much appreciated!