Bonjour,

Je cherche une solution native pour imprimer un pdf sur une imprimante en Java.

J'ai essayé différentes méthodes:

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static void testPrint(){
        DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        //aset.add(MediaSizeName.ISO_A4);
        PrintService[] pservices =
            PrintServiceLookup.lookupPrintServices(flavor, aset);
        for (int i=0;i<pservices.length;i++){
            System.out.println(pservices[i]);
        }
        if (pservices.length > 0) {
            System.out.println("Imprimante selectionnée: " + pservices[0]);
            DocPrintJob pj = pservices[0].createPrintJob();
            try {
                FileInputStream fis = new FileInputStream("C:/BCS_TEST_perso.pdf");
                Doc doc = new SimpleDoc(fis, flavor, null);
                pj.print(doc, aset);
            } catch (FileNotFoundException fe) {
                System.out.println(fe);
            } catch (PrintException e) { 
                System.out.println(e);
            }
        }
    }
mais celle-ci ne donne rien. et si j'utilise DocFlavor.INPUT_STREAM.AUTOSENSE, j'ai des caractères bizarres...

Ensuite avec l'API JPedal, qui ne marche pas...

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public static void printPDF_JPedal_1(){ 
 
        try {
            String fileName = "c:/BCS_TEST_perso.pdf";
 
            //Open & decode the pdf file  
            PdfDecoder decode_pdf = new PdfDecoder(true);
            decode_pdf.openPdfFile(fileName);
 
            //Get the total number of pages in the pdf file  
            int pageCount = decode_pdf.getPageCount();  
            //set to print all pages  
            decode_pdf.setPagePrintRange(1, pageCount);  
            //Auto-rotate and scale flag  
            decode_pdf.setPrintAutoRotateAndCenter(false);  
            // Are we printing the current area only  
            decode_pdf.setPrintCurrentView(false);  
            //set mode - see org.jpedal.objects.contstants.PrinterOptions for all values  
            //the pdf file already is in the desired format. So turn off scaling  
            decode_pdf.setPrintPageScalingMode(PrinterOptions.PAGE_SCALING_NONE);  
            //by default scaling will center on page as well.  
            decode_pdf.setCenterOnScaling(false);  
            //flag if we use paper size or PDF size.  
            //Use PDF size as it already has the desired paper size  
            decode_pdf.setUsePDFPaperSize(true);  
            //setup print job and objects  
            PrinterJob printJob = PrinterJob.getPrinterJob();
 
            PrintService[] service =PrinterJob.lookupPrintServices();
            PrintService ps = service[0];
            printJob.setPrintService(ps);
 
            //setup Java Print Service (JPS) to use JPedal  
            printJob.setPageable(decode_pdf);  
            //Print the file to the desired printer  
            printJob.print();  
        } catch (PdfException e) {
            System.out.println(e);
        } catch (PrinterException e) {
            System.out.println(e);
        }  
    }
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public static void printPDF_JPedal_2() {
        PdfDecoder pdfD = null;
        try {
            PrintService[] psService = PrinterJob.lookupPrintServices();
            PrinterJob pjPrintJob = PrinterJob.getPrinterJob();
            pjPrintJob.setPrintService(psService[0]);
            System.out.println("Service: " + psService[0]);
 
            Paper paper = new Paper();
            paper.setSize(595, 842);
            paper.setImageableArea(0, 0, 595, 842);
            PageFormat pf = pjPrintJob.defaultPage();
            pf.setPaper(paper);
 
            pdfD = new PdfDecoder(true);
            pdfD.openPdfFile("C:/BCS_TEST_perso.pdf");
            pdfD.setPageFormat(pf);
 
            pjPrintJob.setPageable(pdfD);
            pjPrintJob.print();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            pdfD.closePdfFile();
        }
    }
Ensuite, en utilisant PDFRenderer:

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class PDFPrintPage implements Printable {
        private PDFFile file;
        PDFPrintPage(PDFFile file) {
            this.file = file;
        }
 
        public int print(Graphics g, PageFormat format, int index)
        throws PrinterException {
            int pagenum = index + 1;
 
            // don't bother if the page number is out of range.
            if ((pagenum >= 1) && (pagenum <= file.getNumPages())) {
                // fit the PDFPage into the printing area
                Graphics2D g2 = (Graphics2D)g;
                PDFPage page = file.getPage(pagenum);
                double pwidth = format.getImageableWidth();
                double pheight = format.getImageableHeight();
 
                double aspect = page.getAspectRatio();
                double paperaspect = pwidth / pheight;
 
                Rectangle imgbounds;
 
                if (aspect>paperaspect) {
                    // paper is too tall / pdfpage is too wide
                    int height= (int)(pwidth / aspect);
                    imgbounds= new Rectangle(
                            (int)format.getImageableX(),
                            (int)(format.getImageableY() + ((pheight - height) / 2)),
                            (int)pwidth,
                            height
                    );
                } else {
                    // paper is too wide / pdfpage is too tall
                    int width = (int)(pheight * aspect);
                    imgbounds = new Rectangle(
                            (int)(format.getImageableX() + ((pwidth - width) / 2)),
                            (int)format.getImageableY(),
                            width,
                            (int)pheight
                    );
                }
 
                // render the page
                PDFRenderer pgs = new PDFRenderer(page, g2, imgbounds, null, null);
                try {
                    page.waitForFinish();
                    pgs.run();
                } catch (InterruptedException ie) {}
 
                return PAGE_EXISTS;
            } else {
                return NO_SUCH_PAGE;
            }
        }
    }
 
public void testPrintPDFRenderer(){
 
        try {
            // Create a PDFFile from a File reference
            File f = new File("c:/BCS_TEST_perso.pdf");
            FileInputStream fis;
            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);
 
            PrintService[] service =PrinterJob.lookupPrintServices();
            PrintService ps = service[0];
            System.out.println("Imprimante: " + service[0]);
 
            // Create Print Job
            PrinterJob pjob = PrinterJob.getPrinterJob();
            pjob.setPrintService(ps);
 
            PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
            pjob.setJobName(f.getName());
            Book book = new Book();
            book.append(pages, pf, pdfFile.getNumPages());
            pjob.setPageable(book);
 
            // Send print job to default printer
            pjob.print();
 
        } catch (FileNotFoundException e) {
            // Log the error
        } catch (PrinterException e) {
            // Log the error
        } catch (IOException e) {
            // Log the error
        }
    }
mais il m'imprime le pdf sans les images:

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
Imprimante: Win32 Printer : \\neit\BAT26-IMSIE22-NB
sun.awt.image.ImageFormatException: Unsupported color conversion request
Une meilleure idée d'implémentation?

Merci :-)