Solved

Print PDF via java

Posted on 2004-09-14
18
1,586 Views
Last Modified: 2013-12-02
Is it possible to print a pdf using java?

The awt cant print pdfs.
The sdk1.4 provides printing services but pdfs are unsupported.

So... what to do?
Thanks,
Dominik
0
Comment
Question by:Daij-Djan
  • 6
  • 4
  • 2
  • +2
18 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 64 total points
Comment Utility
0
 
LVL 14

Assisted Solution

by:sudhakar_koundinya
sudhakar_koundinya earned 62 total points
Comment Utility
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
But Open Source iText library is efficient I think

http://www.lowagie.com/iText/faq.html
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
from FAQ of http://www.lowagie.com/iText/faq.html

How can I send a PDF file to a printer directly?

Printing is a very platform dependent functionality. On Windows, you can print a PDF file by executing Acrobat Reader:
String osName = System.getProperty("os.name" );
//FOR WINDOWS 95 AND 98 USE COMMAND.COM
if( osName.equals( "Windows 95" ) || osName.equals( "Windows 98" )){
    Runtime.getRuntime().exec("command.com /C start acrord32 /p /h" + claim.pdf);
}
//FOR WINDOWS NT/XP/2000 USE CMD.EXE
else {
    Runtime.getRuntime().exec("cmd.exe /C acrord32 /p /h" + claim.pdf);
}
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
If you're using a current version of GhostScript for your printing, it will accept PDF as input, and convert to your printer's language. Use POSTSCRIPT as the flavor (PDF is PostScript 3)

If not, here are some alternatives:

http://crowbar.dnsalias.com:443/crowbar/000233.html
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
Here's the pertinent portion of the post:

Well, I've just tested another "crowbar" that works very nicely with Java/Windows, but is a bit complex to setup. Once set up, however, it's quite reliable, will print to nearly any printer, and doesn't need any Adobe products. It will also work nicely under Linux (if ghostscript is installed - Redmon isn't required for Linux).

We are basically fooling Java into thinking it's printing a PostScript document, so it simply streams the PDF file's contents to the printer. Redmon intercepts the stream, and sends it through GhostScript to be interpreted into whatever language we tell it to, then streams the resultant data to the printer.

1. Install GhostScript (the latest version, or one which supports direct PDF printing)

2. Install Redmon.

3. Follow the instructions to set up a local printer, using the Apple PS printer driver (or any other PS driver):

http://www.cs.wisc.edu/~ghost/redmon/en/redmon.htm#371

4. In your .rsp file, set the DEVICE to match your printer. For PostScript printers, use "pswrite". If you're in the US, you will probably want to use "letter" for PAPERSIZE. Make sure the paths to lib and fonts match the version of gs you installed.

5. On the "RPT1: Properties" dialog, make sure the paths to gswin32c.exe and your .rsp file are set correctly (c:\gs\gs8.11\gswin32c.exe, c:\gs\myrspfile.rsp for the latest version of gs)

6. Set "Run:" to "Hidden", so that you won't get a flashing DOS box with every printjob.

7. Name your new local printer something like "PrintPDF".

8. Compile the java test program below, and run it with the path to a PDF file as the parameter.

9. When the print dialog comes up, make sure to select the printer you just created (PrintPDF), or you will print pages and pages of garbage!!!

This is a very simplistic test app - but it uses the standard javax.print methods to print PDF.

[CODE]
// PrintPDF.java
import javax.print.*;
import javax.print.attribute.*;
import java.io.*;

public class PrintPDF {
public static void main(String args[]) throws Exception {
String filename = args[0];
PrintRequestAttributeSet pras =
new HashPrintRequestAttributeSet();
DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintService printService[] =
PrintServiceLookup.lookupPrintServices(flavor, pras);
PrintService defaultService =
PrintServiceLookup.lookupDefaultPrintService();
PrintService service = ServiceUI.printDialog(null, 200, 200,
printService, defaultService, flavor, pras);
if (service != null) {
DocPrintJob job = service.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);
}
}

[/CODE]

Another option (Windows only) if Redmon/GhostScript install/config is too complex. Also handles viewing/printing Word, Excel, .txt, etc.

http://forum.planetpdf.com/webboard/wbpx.dll/read?98958,3
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Try


import java.io.*;
import java.awt.*;
import java.awt.print.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;

public class PrintPDF
{

   public void print(String filename) throws IOException, PrintException
   {
        // Use the pre-defined flavor for a PDF from an InputStream
        DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
       
        // Create a set which specifies how the job is to be printed
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        aset.add(MediaSizeName.ISO_A4);
        aset.add(new Copies(1));
       
        // Locate print services which can print a PDF file the manner specified
        PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset);
       
        if (pservices.length > 0)
        {
            // Create a Print Job
            DocPrintJob printJob = pservices[0].createPrintJob();
           
            // Create a Doc implementation to pass the print data
            // Doc doc = new InputStreamDoc(filename, flavor);
            Doc doc = new SimpleDoc(new FileInputStream(filename), flavor, null);
           
            // Print the doc as specified
            printJob.print(doc, aset);
        }
        else
        {
            System.err.println("No suitable printers");
        }
    }
       
    public static void main(String[] arg)
    {
        try
        {
            new PrintPDF().print("prova.pdf");
        }
        catch(Exception ex){ ex.printStackTrace();
        }
    }
}
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 5

Author Comment

by:Daij-Djan
Comment Utility
Read the iText solution but it is windows-only.

@CEHJ: tried that - no printers found
@sudhakar_koundinya: will try that when I have more time. Thank you!
0
 
LVL 92

Assisted Solution

by:objects
objects earned 62 total points
Comment Utility
0
 
LVL 3

Assisted Solution

by:sbockelman
sbockelman earned 62 total points
Comment Utility
what about FOP?  

http://xml.apache.org/fop/
0
 
LVL 5

Author Comment

by:Daij-Djan
Comment Utility
@sudhakar_koundinya: redmon is for windows only, no?
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
yes

i have already said that

>>Another option (Windows only) if Redmon/GhostScript install/config is too complex. Also handles viewing/printing Word,
>>Excel, .txt, etc.
0
 
LVL 5

Author Comment

by:Daij-Djan
Comment Utility
I thought only th other answer was windows-only,
anyway, as there does not seem to be a FREE cross-platform solution or different ones even, ill probably just go with JPrint
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
did the two links i posted above not help?
0
 
LVL 5

Author Comment

by:Daij-Djan
Comment Utility
the first is JPrint... Ill award points once integrated
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

PaperPort is a popular document imaging/management product from Nuance Communications (http://www.nuance.com/). It is in widespread use by both individuals (http://www.nuance.com/for-individuals/by-product/paperport/index.htm) and businesses (http:/…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
This video Micro Tutorial is the second in a two-part series that shows how to create and use custom scanning profiles in Nuance's PaperPort 14.5 (http://www.experts-exchange.com/articles/17490/). But the ability to create custom scanning profiles a…
In this sixth video of the Xpdf series, we discuss and demonstrate the PDFtoPNG utility, which converts a multi-page PDF file to separate color, grayscale, or monochrome PNG files, creating one PNG file for each page in the PDF. It does this via a c…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now