Printing a PDF document using Java 1.4 Printing API

Hi,
When I tried to print a PDF document using JAVA 1.4 Printing API, I got the following exception.
Exception in thread "main" sun.print.PrintJobFlavorException: invalid flavor
at sun.print.Win32PrintJob.print(Win32PrintJob.java:290)
at Printing.main(Printing.java:40)
I am able to print the same PDF document using Acrobat reader.
Is PDF format not supported in JAVA 1.4 printing API? or is something wrong in my code?
here is the sample JAVA program that I was using
import javax.print.*;
import javax.print.attribute.*;
import java.io.*;
public class Printing {
public static void main(String args[]) throws Exception {
String filename = args[0];
PrintRequestAttributeSet pras =
new HashPrintRequestAttributeSet();
DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
PrintService defaultService =
PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob job = defaultService.createPrintJob();
FileInputStream fis = new FileInputStream(filename);
DocAttributeSet das = new HashDocAttributeSet();
Doc doc = new SimpleDoc(fis, flavor, das);
job.print(doc, pras);
Thread.sleep(10000);
System.exit(0);
Thank you
Sumana

Here's a pure Java solution (that works!):
http://www.mycgiserver.com/~zhouwu/pdf/readme.html
The caveats are:
- prints only to the default printer
- requires a properties file located in the home directory
my workaround for the last:
     * Print a PDF file to the default printer (might consume lots of memory!).
     * <p>
     * <b>Required:</b>
     * <ul>
     * <li>a file "acrobat.properties" needs to be in the working directory. The content is:
<table align="center" bgcolor="#E0E0E0" border=1 cellpadding="10" cellspacing="0"><tr><td><pre style="margin-top:0; margin-bottom:0">
#com.adobe.acrobat.Viewer Properties
#Wed Oct 29 20:34:05 PST 2003
com.adobe.acrobat.AcceptedLicAgreement=true
com.adobe.acrobat.Fax_Fine_Mode=true
com.adobe.acrobat.Find\:FindAll=false
com.adobe.acrobat.Find\:FindBackwards=false
com.adobe.acrobat.Find\:FindWholeWord=false
com.adobe.acrobat.Find\:MatchCase=false
com.adobe.acrobat.Open_Dialog_Directory=C\:\\temp\\
com.adobe.acrobat.Open_Dialog_File=itext.pdf
com.adobe.acrobat.Print_Method_Known=true
com.adobe.acrobat.Shrink_To_Fit=false
com.adobe.acrobat.SitePreferencesURL=file\://localhost/C\:/pdf/acrobat-site.properties
com.adobe.acrobat.Use_Print_Server=false
com.adobe.acrobat.util.fontDirectories=C\:\\Winnt\\Fonts
com.adobe.acrobat.util.fontIgnoreExtensions=.fon;.pfm;.ini;.lst;.txt;.doc;.ttmap;.z;.enc;.dir;.afm;.f3b;.pfa;.spd;.ps;.bepf;.map;.alias;.scale;.all;.upr
</pre></td></tr></table>
     * <li>The JAR files PDFPrinter.jar, acrobat.jar and MRJToolkitStubs.zip in the CLASSPATH.
     * </ul>
     * <p>
     * Note: the file "acrobat.properties" is expected to be in the user's home directory. As this is not always feasible,
     * the system property "user.home" is mapped to "user.dir" for the time of execution.
     * @param fileName Name of PDF file to print.
     * @throws Exception on error.
     * @see <a href="http://www.mycgiserver.com/~zhouwu/pdf/readme.html">PDF Server (Silent) Printing</a>
    public void printPDF(String fileName) throws Exception {
        String oldHome = System.getProperty("user.home");
        System.setProperty("user.home", System.getProperty("user.dir"));
        PDFPrinter vi = new PDFPrinter();
        vi.activate();
        vi.setDocumentInputStream(new FileInputStream(fileName));
        vi.printAll();
        System.setProperty("user.home", oldHome);
    }//printPDF()I just need the following additional files in my CLASSPATH: PDFPrinter.jar, acrobat.jar and MRJToolkitStubs.zip. Despite the note at the site above that "printing quality is not very good", i can't agree: the print quality is quite good. Not perfect, but acceptable for most uses.
(Tested on Windows 2000 SP4, J2SE 1.4.2_03, hp laserjet 2300dn)

Similar Messages

  • Markup PDF document using Java

    I want to view/render and annotate/Markup PDF document using Java. How can I achieve it?
    On [http://www.java-junction.blogspot.com|http://www.java-junction.blogspot.com] it is mentioned rendering PDF using PDFRender tool. But how can I create annotate/Markup on PDF Document.
    Is there any Open Source Tool avaible for that?

    I want to view/render and annotate/Markup PDF document using Java. How can I achieve it?
    On [http://www.java-junction.blogspot.com|http://www.java-junction.blogspot.com] it is mentioned rendering PDF using PDFRender tool. But how can I create annotate/Markup on PDF Document.
    Is there any Open Source Tool avaible for that?

  • I am having trouble printing a PDF document. Whenever I click print nothing happens but when I am printing documents from Word, Excel etc they print without a problem. I've tried printing as image but that did not work. I uninstalled Adobe Reader XI and d

    I am having trouble printing a PDF document. Whenever I click print nothing happens but when I am printing documents from Word, Excel etc they print without a problem. I've tried printing as image but that did not work. I uninstalled Adobe Reader XI and downloaded Adobe Reader X instead and that still doesn't work. I have Windows 7.

    Hello,
    Please follow the link to troubleshoot the printing issues with Adobe Reader:- Troubleshoot PDF printing | Acrobat, Reader.
    Regards,
    Nakul

  • Printing a PDF document using SMARTFORMS

    What is the easiest way to print a PDF document from an ABAP program?  I have the data in the following formats:
    Binary (XSTRING)
    String (from function module HR_KR_XSTRING_TO_STRING)
    OTF
    What format can I use in a smartform to print the PDF in the background?
    Thanks in advance.

    Sandipan,
    If I use the UTF format, what do I use for the device type?  PDF1?  Also, I have the OTF data in an internal table which has to fields (TDPRINTCOM and TDPRINTPAR).  I pass this table into the smartform function module but what do I do with the 2 fields when I loop through the internal table in the smartform?  Do I just output a text node with TDPRINTPAR and ignoreTDPRINTCOM?
    TDPRINTCOM   TDPRINTPAR
    ==========    ==========
    //             XHPLJ4       0700 00000000001
    IN            04E/ERPIS/CARRIERLABEL
    IN            05%PAGE1
    OP            DINA4   P 144  240 1683811906000010000100000
    IN            06MAIN
    IN            03TABLE_BEGIN
    MT            0141701657
    CP           41030000E
    FC           COURIER 120  00144 SF012SF012410300144E

  • Printing of pdf document from java application

    Hello,
    I want to print out a pdf document which I get from a server as a byte-stream. I don't want to display or preview it on the client but print it out right away. Is there a way to do this?
    Thank you very much!
    Matthias

    Hi Matthias,
    If you have got solution for this can u suggest me.
    I'm using following code
              PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
              DocFlavor flavor = javax.print.DocFlavor.INPUT_STREAM.AUTOSENSE;
              System.out.println("====================>"+flavor);
              PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
              PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
              PrintService service = ServiceUI.printDialog(null, 200, 200,printService, defaultService, flavor, pras);
              if (service != null)
                   try
                        javax.print.attribute.standard.Copies obj=new javax.print.attribute.standard.Copies(1);
                        Attribute at=(Attribute)pras.get(obj.getClass());
                        int noOfCopies=1;
                        if(at!=null){
                             try{
                                  noOfCopies=Integer.parseInt(at.toString());
                             }catch(Exception err){noOfCopies=1;}
                        for(int i=0;i<noOfCopies;i++)
                             URL url = null;
                             try{
                                  url = new URL(urlToPDF);
                                  url.openConnection();
                                  fis = url.openStream();
                             }catch(Exception err){}
                             DocPrintJob job = service.createPrintJob();
                             job.addPrintJobListener(printjoblis);
                             DocAttributeSet das = new HashDocAttributeSet();
                             Doc doc = new SimpleDoc(fis, flavor, null);
                             pras.add(Sides.ONE_SIDED);
                             job.print(doc, pras);
                   }catch(Exception err){System.out.println("=========>"+err);}
    some times i'm getting garbage values in the printout.
    Thanks & Regards,
    Surya.

  • How to print a word document using java?

    Hi All,
    is it possible to write a java program that takes input and directs it to printer.
    I specifically want it for word document.
    i already have a program that works for images but not for word document.
    Plz guide me where i am wrong or help me with some links or code snippets.
    Any kind of help will be really appreciated.
    // program is below
    import java.io.FileInputStream;
    import javax.print.Doc;
    import javax.print.DocFlavor;
    import javax.print.DocPrintJob;
    import javax.print.PrintService;
    import javax.print.PrintServiceLookup;
    import javax.print.ServiceUI;
    import javax.print.SimpleDoc;
    import javax.print.attribute.DocAttributeSet;
    import javax.print.attribute.HashDocAttributeSet;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    public class Convert{
         * @param args
         Convert(){
              DocFlavor psFlavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
              FileInputStream fis = null;
              // Creates a new attribute set
              PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
              try{
                   fis = new FileInputStream("d:\\print\\new.txt");
                   System.out.println("doc taken...");
                   if (fis == null) {
                        System.out.println("No File");
                        return;
              }catch(Exception e){
                   System.out.println("No Such Doc..."+e);
              PrintService printService[] = PrintServiceLookup.lookupPrintServices(psFlavor, aset);
              //System.out.println("Default Printer: ");
              PrintService services = null;
              try{
                   services =     PrintServiceLookup.lookupDefaultPrintService();//ookupPrintServices(psFlavor, aset);
              }catch(Exception e){
                   System.out.println("print exp ");
                   e.printStackTrace();
              System.out.println("Default Printer: "+ services.getName());
              System.out.println(services+" services taken..."+services.isDocFlavorSupported(psFlavor));
              PrintService service = ServiceUI.printDialog(null, 250, 250, printService, services, psFlavor, aset);
              if (service != null) {
              DocPrintJob job = service.createPrintJob();
              try {
                   DocAttributeSet d = new HashDocAttributeSet();
                   // Doc doc=new
                        Doc doc = new SimpleDoc(fis, psFlavor, d);
                        System.out.print("doc prepared...");
                        System.out.println("printing starts...");
                        job.print(doc,aset);
                        System.out.println("printing done...");
              catch (Throwable pe) {
                   pe.printStackTrace();
         }else{
              System.out.print("else...");
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              new Convert();
    }

    anamupota wrote:
    JoachimSauer wrote:
    Desktop.print() is the simplest way. Everything else will get tricky really fast.I wonder if one could print .doc file though.Desktop.print() simply tells the OS to do whatever it usually does to print the file. If Word is installed, it should start word with the file as an argument and whatever parameter it takes to tell Word to print it.
    If you don't have anything installed that can view/print words files (or the correct entries are missing in the registry), then it won't work, of course.

  • Streaming  PDF Documents Using JAVA

    Hello Geeks,
    I want to develop a document viewer which gets embedded in web browser.
    Are there any JAVA API available for this ?
    I am confused where to start.

    Embedded in a web browser -> java applet.
    Document viewer -> depends on which document type you want to show (and how you want to show it). Search on "java <document type> library"to see if anyone else solved it.

  • I cannot print a pdf document on my HP 7520 printer.

    When I open the document and click on print, it opens the printer dialog box. Since I have three printers installed on my windows 7 computer, I have to select the correct printer. When I scroll through the printer list, the HP7520 printer does not show up, so I have no way to print the document. As a test, I used photoshop to try to print the document and the 7520 printer did show up in the photoshop printer list and I was able to select the correct 7520 printer and print the document. Anyone have any idea why this will not work with adobe reader 11?

    This turns out to be a registry error which occured when I de installed the older HP printer. It works now that the registry was corrected.

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

  • Printing PDF documents in Java

    Hello All,
    I will be very gratefull if someone points me to resources on the web which show how to print a pdf document in java.
    If you are aware of any tutorials and examples, then please let me know.
    regards,
    Abhishek.

    duffymo
    Acrobat 5.0 when I open a pdf on my system.
    This is exactly the code currently in my program.
    I just ran it again to test it and it works.
    1) The application has an ugly square gray box on the screen while printing.
    2) The Acrobat reader starts on the task bar.
    3) For the application to continue I have to expand the reader and close it myself.
    public void actionPerformed(ActionEvent e) {
      String selectedDocument = SelectedDocument();
      if (selectedDocument != null) {
        try {
          String command = "C:\\Program Files\\Adobe\\Acrobat 5.0\\Reader\\AcroRd32.exe /t "+selectedDocument+" \\\\CONTROL\\HP LaserJet 4L";
          Runtime rn = Runtime.getRuntime();
          Process process = rn.exec(command);
          process.waitFor();
        catch (Exception pEX) {showSystemError("Unable to print document.", selectedDocument, pEX, false);}
    }It is not what I wanted to do - I wanted to do the print
    internally in the program.
    rykk

  • Acrobat X and XI will not print many pdf documents.

    Acrobat X and XI will not print many pdf documents. When I click Print, the document fades and I get a dialog box that says "Adobe Acrobat has Stopped Working. A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available." I was experiencing this with Acrobat X so I upgraded to XI, but the problem is exactly the same. I am using Windows 7 Professional operating system.

    Thank you for your reply. I have several printers available on our network,
    the program doesn't even go as far as allowing me to select a printer. I am
    trying to print to an HP 1320n or a LANIER MP C5502 PCL 6. I have changed
    the default printer, but the result is still the same. In does the same
    thing with Adobe (Standard XI) PDF set as the default printer.
    Stan Reznicek
    WinWholesale
    3110 Kettering Blvd
    Dayton, OH 45439
    937-294-4249
    [email protected]

  • Image not displayed in pdf generated using Java API for Forms service

    Hi,
    I am creating a pdf document using Java API for Forms Service.
    I am able to generate the pdf but the images are not visible in the generated pdf.
    The image relative path is coming in the xml as defined below. The images are stored dynamically in the Livecycle repository each time a request is fired with unique name before the xml is generated.
    <imageURI xfa:contentType="image/png" href="../Images/logo.png"></imageURI>
    Not sure if I need to specify specify specific URI values that are required to render a form with image.
    The same thing is working when I generate pdf document using Java API for Output Service.
    As, I need to generate interactive form, I have to use Forms service to generate pdfs.
    Any help will be highly appreciated.
    Thanks.

    Below is the code snippet:
                //Create a FormsServiceClient object
                FormsServiceClient formsClient = new FormsServiceClient(myFactory);
                //Specify URI values that are required to render a form
                URLSpec uriValues = new URLSpec();
                                  // Template location contains the whole rpository path for the form
                uriValues.setContentRootURI(templateLocation);
               // The base URL where form resources such as images and scripts are located.  Whole Image path is passed in BaseUrl in the http format.
                      String baseLocation = repositoryPath.concat(serviceName).concat(imagesPath);   
                                  uriValues.setBaseURL(baseLocation);                                        
                // Set run-time options using a PDFFormRenderSpec instance
                PDFFormRenderSpec pdfFormRenderSpec = new PDFFormRenderSpec();
                pdfFormRenderSpec.setCacheEnabled(new Boolean(true));           
                pdfFormRenderSpec.setAcrobatVersion(com.adobe.livecycle.formsservice.client.AcrobatVersio n.Acrobat_8);
                                  //Invoke the renderPDFForm method and write the
                //results to a client web browser
                String tempTemplateName =templateName;
                FormsResult formOut = formsClient.renderPDFForm(tempTemplateName,
                                              inXMDataTransformed,pdfFormRenderSpec,uriValues,null);
                //Create a Document object that stores form data
                Document outputDocument = formOut.getOutputContent();
                InputStream inputStream = outputDocument.getInputStream();

  • Creating a PDF by using Java

    Is it possible to create a PDF file using Java
    Is there any API/class there exists in java
    Can any one help me
    Hope some intelligent peoples are there to help me
    make a reply to me at
    [email protected]

    There's:
    http://www.lowagie.com/iText/
    If you're working with xml, maybe this one:
    http://xml.apache.org/fop/index.html
    regards.

  • 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

  • Can I print the last page of a PDF document using command line?

    Hi
    I am in a situation in which I constantly have to deal with multiple PDF documents and I need to print the last page in each of these, and ONLY the last page. The total number of pages will vary for each file, so the page number for the last page will also vary.
    I would really prefer to not do this manually, by opening up each file in the visible Adobe Reader window and then print.
    Question:
    Is there a way with Adobe Reader (maybe with the help of some other Adobe product) to print only the last page of a PDF document using some kind of command line without opening up the PDF file in the visible Adobe Reader window?
    I'm using Windows.
    Thanks in advance,
    Regards,
    Emil

    Thank you for taking the time to reply.
    I tried both ways and neither works.  It gives me a prompt box that I have to click "next" for every page but after going thru all pages, nothing is sent to the printer.
    Also, all directions I've read indicate it will print to the default printer.  If my default printer is on a network, will that cause problems....
    and...
    should I be getting a prompt box on every page?  I thought all this would happen behind the scenes and not force me to interact with every page.
    dc

Maybe you are looking for