How to display pdf file with java code?

Hi All,
i have a jsp pagein that page if i click one icon then my backing bean method will call and that method will create pdf document and write some the content in that file and now i want to display that generated pdf document.
it should look like you have pressed one icon and it displayed pdf file to you to view.
java code below:
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
HttpServletResponse resp = (HttpServletResponse) ec.getResponse();
resp.setHeader("Content-Disposition", "filename=\"" + temppdfFile);
resp.encodeRedirectURL(temppdfFile.getAbsolutePath());
resp.setContentType("application/pdf");
ServletOutputStream out = resp.getOutputStream();
ServletUtils.returnFile(temppdfFile, out);
out.flush();
and above temppdfFile is my generated pdf file.
when i am executing this code, it was opening dialog box for save and cancel for the file, but the name of the file it was showing me the "jsp file name" with no file extention (in wich jsp file i am calling my backing bean method) and type is "Unknown File type" and from is "local host"
it was not showing me open option so i am saving that file then that file saved as a pdffile with tha name of my jsp file and there is nothing in that file(i.e. empty file).
what is the solution for this. there is any wrong in my code.
Please suggest me.
Thanks in advance
Indira

public Object buildBarCodes() throws Exception
File bulkBarcodes = null;
String tempPDFFile = this.makeTempDir();
File tempDir = new File("BulkPDF_Files_Print");
if(!tempDir.exists())
tempDir.mkdir();
bulkBarcodes = File.createTempFile
(tempPDFFile, ".pdf", tempDir);
//bulkBarcodes = new File(tempDir, tempPDFFile+"BulkBarcode"+"."+"pdf");
if(!bulkBarcodes.exists())
bulkBarcodes.createNewFile();
Document document = new Document();
FileOutputStream combinedOutput = new FileOutputStream(bulkBarcodes);
PdfWriter.getInstance(document, combinedOutput);
document.open();
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
Image image = Image.getInstance(bc.generateBarcodeBytes(bc.getBarcode()));
document.add(image);
combinedOutput.flush();
document.close();
combinedOutput.close();
FacesContext facesc = FacesContext.getCurrentInstance();
ExternalContext ec = facesc.getExternalContext();
HttpServletResponse resp = (HttpServletResponse) ec.getResponse();
resp.setHeader("Content-Disposition", "inline: BulkBarcodes.pdf");
resp.encodeRedirectURL(bulkBarcodes.getAbsolutePath());
resp.setContentType("application/pdf");
resp.setBufferSize(10000000);
ServletOutputStream out = resp.getOutputStream();
ServletUtils.returnFile(bulkBarcodes, out);
out.flush();
return "success";
This is my action method which will call when ever i press a button in my jsp page.
This method will create the barcode for the given barcode number and write that barcode image in pdf file
(i saw that pdf file which i have created through my above method, This PDF file opening when i was opening manually and the data init that is also correct means successfully it writes the mage of that barcode)
This method taking the jsp file to open because as earlier i said it was trying to open unknown file type document and i saved that file and opended with editplus and that was the jsp file in which file i am calling my action method I mean to say it was not taking the pdf file which i have created above it was taking the jsp file

Similar Messages

  • Problem in printing pdf document with java code

    Hi All
    I want to print a pdf document with java code i have used PDFRenderer.jar to compile my code.
    Code:
    File f = new File("C:/Documents and Settings/123/Desktop/1241422767.pdf");
    FileInputStream fis = new FileInputStream(f);
    FileChannel fc = fis.getChannel();
    ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    PDFFile pdfFile = new PDFFile(bb); // Create PDF Print Page
    PDFPrintPage pages = new PDFPrintPage(pdfFile);
    // Create Print Job
    PrinterJob pjob = PrinterJob.getPrinterJob();
    PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
    pjob.setJobName(f.getName());
    Book book = new Book();
    book.append(pages, pf, pdfFile.getNumPages());
    pjob.setPageable(book);
    // System.out.println(pjob.getPrintService());
    // Send print job to default printer
    pjob.print();
    but when i am running my program i am getting error
    Exception in thread "main" java.awt.print.PrinterException: Invalid name of PrintService.
    Please anybody, knows the solution for this error?
    Thanks In Advance
    Indira

    It seems that either there is no default printer setup or you have too many printers or no printer setup at all. Try running the following code. It should print the list of available print services.
    import java.awt.print.*;
    import javax.print.*;
    public class PrintServiceNames{
         public static void main(String args[]) throws Exception {
              PrintService[] printServices = PrinterJob.lookupPrintServices();
              int i;
              for (i = 0; i < printServices.length; i++) {
                   System.out.println("P: " + printServices);
    }From the list pick one of the print service names and set it explicitly like "printerJob.setPrintService(printServices);" and then try running the program.

  • How to print PDF files using java print API

    Hi,
    I was goign throw lot of discusion and reading lot of forums related to print pdf files using java api. but nothing seems to be working for me. Can any one tell me how to print pdf files using java api.
    Thanks in advance

    Mike,
    Can't seem to get hold of the example described in your reply below. If you could let us have the URL to get then it would be great.
    My GUI application creates a pdf document which I need to print. I want to achieve this using the standard Java class PrinterJob (no 3rd party APIs I'm afraid, commercial restraints etc ..). I had a stab at it using the following code. When executed I get the pretty printer dialog then when I click ok to print, nothing happens!
    boolean showPrintDialog=true;
    PrinterJob printJob = PrinterJob.getPrinterJob ();
    printJob.setJobName ("Contract.pdf");
    try {
    if (showPrintDialog) {
    if (printJob.printDialog()) {
    printJob.print();
    else
    printJob.print ();
    } catch (Exception PrintException) {
                   PrintException.printStackTrace();
    Thank you and a happy new year.
    Cheers,
    Chris

  • How to display Pdf file in iPad site

    Hi
    How to display Pdf file in web page which can able to view in iPad safari?
    Thanks,
    Arun

    You can't really.
    You need to use DHTML in the swf-wrapper HTML file, usually a
    division wrapped iFrame, and load the PDF into the iFrame as an
    overlay to the Flash.

  • How to create pdf files with text field data

    how to create pdf files with text field data

    That looks like it should work, but it doesn't.
    I opened the PDF I had created from Word in Acrobat (X Pro). Went to File > Properties. Selected "Change Settings". I then enabled "Restrict editing...", set a password, set "Printing Allowed" to "none", "Changes Allowed" to "none", and ensured that "Enable copying of text..." was disabled.
    I saved the PDF file, closed Acrobat, opened the PDF in Reader, and I was still able to select text and graphical objects.
    I reopened the PDF in Acrobat, and the document summart still shows everything as allowed. When I click on "show details" (from File > Properties) it shows the correct settings.
    Any ideas?

  • How to read pdf files using java.io package classes

    Dear All,
    I have a certain requirement that i should read and write PDF files at runtime. With normal java file IO reading is not working. Can any one suggest me how to proceed probably with sample code block
    Thanks in advance.

    hi I also have the pbm. to read pdf file using JAVA
    can any body help meWhy is it so difficult to read the thread you posted in? They say: java.io is pointless, use iText. So why don't you?
    or also I want to read a binary encoded data into
    ascii,
    can anybody give me a hint how to do it.Depends on what you mean with "binary encoding". ASCII's binary encoding, too, basically.

  • How to view pdf file in java/jsp?

    Hello Everybody,
    Any one help me how to view pdf file in jsp using java application.
    I have pdf file c:\app.pdf.
    How can i display the pdf file.
    Please help me.................
    Thanks

    Hello,
    You can use the below code, but i am not sure how far is this a startard way of doing it.
    # <%
    # ServletOutputStream servletOutputStream = response.getOutputStream();
    # File reportFile = new File("C:\\Tomcat 5.0\\webapps\\TestApp\\myfile.pdf");
    # FileInputStream fis = new FileInputStream(reportFile);
    # byte[] bytes= new byte[128000];
    # int count=fis.read(bytes);
    # try
    # response.setContentType("application/pdf");
    # response.setContentLength(bytes.length);
    # servletOutputStream.write(bytes, 0, bytes.length);
    # servletOutputStream.flush();
    # servletOutputStream.close();
    # }catch(Exception e){}

  • How to display pdf-files out of a blob

    Hello,
    we want to use pdf to publish our enterprise-informations (jobs, press release...) in the intranet.
    How can a display a pdf-file with Portal that was saved in blob?
    regards
    Ralf Schmitt

    Not entirely. At least we came to the conclusion it doesn't make (much) sense to block the save option of PDFs if you want to allow printing them
    Anyway; there is of course another possibilty: you could always write your own java bean PDF reader; there are plenty of java PDF libraries available:
    Open Source PDF Libraries in Java
    The easiest way would be to choose one which can open a PDF from a URL and render it; I would retrieve the image via mod_plsql using WPG_DOCLOAD and simply use the PDF library to render the PDF. No tempfiles anyway, and if you don't implement it there is also no save button.
    cheers

  • How to display pdf file in windows phone 8 silver light application?

    Hi,
    I am developing windows phone 8 silver light application . For my app I want to display pdf files . Is there any default controls to display pdf files ?
    I don't want to display using launchers , I want to display with in the app.
    any help,
    Thanks..
    Suresh.M

    Probably this should give you a fair idea : How to view PDF file inside an Windows Phone application?
    http://developer.nokia.com/community/wiki/Using_Crypto%2B%2B_library_with_Windows_Phone_8

  • Split XML in Multiple XML files with Java Code

    Hi guys , i have following xml file as input ....
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <T0020
    xsi:schemaLocation="http://www.safersys.org/namespaces/T0020V1 T0020V1.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.safersys.org/namespaces/T0020V1">
    <INTERFACE>
    <NAME>SAFER</NAME>
    <VERSION>04.02</VERSION>
    </INTERFACE>
    <TRANSACTION>
    <VERSION>01.00</VERSION>
    <OPERATION>REPLACE</OPERATION>
    <DATE_TIME>2009-09-01T00:00:00</DATE_TIME>
    <TZ>CT</TZ>
    </TRANSACTION>
    <IRP_ACCOUNT>
    <IRP_CARRIER_ID_NUMBER>274845</IRP_CARRIER_ID_NUMBER>
    <IRP_BASE_COUNTRY>US</IRP_BASE_COUNTRY>
    <IRP_BASE_STATE>AR</IRP_BASE_STATE>
    <IRP_ACCOUNT_NUMBER>55002</IRP_ACCOUNT_NUMBER>
    <IRP_ACCOUNT_TYPE>I</IRP_ACCOUNT_TYPE>
    <IRP_STATUS_CODE>100</IRP_STATUS_CODE>
    <IRP_STATUS_DATE>2007-11-06</IRP_STATUS_DATE>
    <IRP_UPDATE_DATE>2009-08-03</IRP_UPDATE_DATE>
    <IRP_NAME>
    <NAME_TYPE>LG</NAME_TYPE>
    <NAME>A P SUPPLY CO</NAME>
    <IRP_ADDRESS>
    <ADDRESS_TYPE>PH</ADDRESS_TYPE>
    <STREET_LINE_1>1400 N OATS</STREET_LINE_1>
    <STREET_LINE_2/>
    <CITY>TEXARKANA</CITY>
    <STATE>AR</STATE>
    <ZIP_CODE>71854</ZIP_CODE>
    <COUNTY>MILLER</COUNTY>
    <COLONIA/>
    <COUNTRY>US</COUNTRY>
    </IRP_ADDRESS>
    <IRP_ADDRESS>
    <ADDRESS_TYPE>MA</ADDRESS_TYPE>
    <STREET_LINE_1>P O BOX 1927</STREET_LINE_1>
    <STREET_LINE_2/>
    <CITY>TEXARKANA</CITY>
    <STATE>AR</STATE>
    <ZIP_CODE>75504</ZIP_CODE>
    <COUNTY/>
    <COLONIA/>
    <COUNTRY>US</COUNTRY>
    </IRP_ADDRESS>
    </IRP_NAME>
    </IRP_ACCOUNT>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    </T0020>
    and i want to take this xml file and split it into multiple files through java code like this ...
    File1.xml
    <T0020>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    </T0020>
    File2.xml
    <T0020>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    </T0020>
    like wise...
    Each xml file contain maximum 10 or 15 IRP_ACCOUNT.
    Can somebody please help me ? How can i do it with stax like start element and all ?
    thanks in advance.

    Ah, sorry, strike that. You want multiple files. I think the easiest way is to simply parse with DOM. [http://www.w3schools.com/xpath/default.asp] . And here [http://www.w3schools.com/xpath/default.asp].
    You can output the various XML elements using a PrintWriter or creating a separate DOM document for each file you want to create and serializing that.
    - Saish

  • How to save PDF file with predefined name?

    Hi,
    I am new in LiveCycle Designer. I have a requirement to save a PDF file with predefined file name. When user clicks a "Save as PDF" button, the fillable form is saved with the name from the form fields (e.g. FormID_UserID_Timesstamp...)
    I added a button (btnSavePDF) to the form (Control Type=Regular). Then I added an action with the Condition:"When button is clicked" and the Result: "Save the form". I got the JavaScripts it genreated:
      CoverPageForm.FormPage.btnSavePDF::click - (JavaScript, client)
    app.execMenuItem("SaveAs");
    When I tested it in Adobe Acorbat XI, I have option to save it as .pdf or other file formats. My questions is how can I save it with the predefined file name as a .pdf file, instead user has option to change the file name or change the file format? Can app.execMemuItem() method take other parameters?
    Thanks
    Sam

    You can't do it with app.execMenuItem. You can use the doc.saveAs method, but it has to be executed in a privileged context. For your application this means a folder-level JavaScript file that would have to be installed on each user's machine or with code in a certified PDF that the users chooses to trust to allow for privileged JavaScript execution.
    More information on the saveAs JavaScript method: http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.524.html
    and some sample code relevant to the folder-level JavaScript option: http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.168.html
    All of the sample code shown is for a regular PDF, so you'll have to adjust slightly for using with an XFA.

  • OpenScript/How to add .jar file to Java Code in relative path

    Hi all,
    I want to add a .jar file which can be executed separately (like "java -jar A.jar") to my recorded Java Code.I've read this wiki http://everest2.us.oracle.com/wiki/Generic_JAR_Project about how to add a .jar file to "Assets", however, I cannot figure out how to use the .jarr file in Java code,I mean , how to get this .jar file like the method the databank added in "Assets"?
    Things I did are as followed:
    1.Execute my .jar file in OpenScript Java code with absolute path like this:
    String cmd = "C:\Users\A.jar";
    Runtime.getRuntime().exec(cmd);
    This does work, but must set a absolute path in Java code like "C:\User\A.jar" ,which is not the workaround I want (I need my scripts can be run on other machines).
    2.Try to get its current path with following codes:
    File directory = new File(".");
    String currentPath=directory.getCanonicalPath();
    However,though this can get its absolute path (which is the the project path) in Eclipse like "C:\Users\Workspace\testProject", this only gets "C:\OracleATS\openScript" in OpenScript.
    I thought to copy my .jar file to the project path , got its current path in java code first,then can know the path of .jar file, but this workaround failed because of the above reason.
    I notice that in the "Assets" there are "Databanks","Object Libraries","JAR Files","Scripts". Since the databanks and scripts that added to "Databanks" and "Scripts" can be got or run in Java Code like:
    *getDatabank("DatabankName").getNextDatabankRecord(); String data = eval("{{db.DatabankName.data}}");*
    *or getScript("ScriptName").run();*
    *Is there a method to get and run the jar file added to "Assets\JAR Files" like the above?*
    Thank you very much!
    Regards,
    Angyoung

    Hi DM,
    Thanks for your reply!
    I've found a workaround,which is calling OpenScript's APIs ,such as this.getScriptPackage().getRepository() and this.getScriptPackage().getWorkspace(),etc to locate the .jar file.
    And this workaround can still work even though the script is run on other machine.
    Sorry to reply you so late!
    Regards,
    Angyoung

  • How to copy a file from Java code

    I have written a file through Java code in folder, say, "A". Now, I want a copy of that file exactly the same in some other folder "B". How, it can be done?

    http://java.sun.com/docs/books/tutorial/essential/io/streams.html

  • How to use parameter file with java

    Is it possible to use a parameter file with Java, and is there any class/method to make it easy to call and use these parameter from a text file, other than scanning the whole text file manually as we can do normally with visual basic/c++, so we can call the program with the parameter file, like java testing c:\\testing.ini

    If I understand you correctly, you may be looking for a properties file. This is basically a text file that contains pairs of strings in the form:
    parameter1=value1
    parameter2=value2
    parameter3=value3
    ...etc.
    and the values are retrieved using the java.util.Properties class - see:
    http://java.sun.com/j2se/1.3/docs/api/java/util/Properties.html
    Sample use://Call chis method once, to load the props file.
    //props file is called "demo.properties", and is
    //in a directory that is included in the classpath
        private void loadMyProperties() throws Exception
         InputStream stream = getResourceAsStream("/demo.properties");
         if(stream == null)
             throw new Exception("stream is null!");
         demoProperties = new Properties();
         demoProperties.load(stream);
         stream.close();
    // Then you can retrieve properties in your code using:
    String param3 = demoProperties.getProperty("parameter3");
    //...etc

  • How to use PDF files with links to other PDF Files

    How to use a PDF file with links to other PDF files that have been transferred to the same folder

    Are you using a mouse, or a trackpad on a laptop? Either way, your cursor is usually an arrow, right? And presumably it's working/moving MOST of the time, otherwise you wouldn't be able to do anything?
    For example, can you move the cursor arrow to the "Annotate" tool to click on it and go into Annotate mode? If so, can you click on the text tool? If so, does the cursor change to a crosshairs? At what point can you NOT move the cursor around the screen?
    Matt

Maybe you are looking for