Impressão direta de um pdf em Java

1 resposta
alexwebsp

Gostaria de imprimir um arquivo PDF que já existe, em uma impressora, mas direto sem ter que visualizá-lo.
Tentei fazer, peguei este código na internet, mas ele está imprimindo um X enorme na folha, se alguém puder me ajudar, ou se alguém tiver algum outro código que imprima um pdf já criado direto, sem visulizá-lo, agradeço, preciso de ajudo, por favor!

import com.lowagie.text.pdf.PdfException;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.JobName;
import javax.print.attribute.standard.PageRanges;
import org.jpedal.PdfDecoder;

/**
 *
 * @author Alex
 */
public class ImprimirPDF {

   private String                   fileName          = null;
   private FileInputStream          fileInput         = null;
   private PrintService[]           services          = null;
   private PrintService             defaultPrinter    = null;
   private PrinterJob               printerJob        = null;
   private PrintRequestAttributeSet printerAttributes = null;
   private PdfDecoder               decoder           = null;
   private Paper                    paper             = null;
   private PageFormat               pageFormat        = null;

   public ImprimirPDF(String fileName)  {
      this.fileName = fileName;
   }

   private void configurePage(double width, double height) {

      double polegada    = 0.393700787;
      double paperWidth  = (width / 10) * polegada * 72;
      double paperHeight = (height / 10) * polegada * 72;

      this.paper = new Paper();
      this.paper.setSize(paperWidth, paperHeight);
      this.paper.setImageableArea(0, 0, this.paper.getWidth(), this.paper.getHeight());

      this.pageFormat = printerJob.defaultPage();
      this.pageFormat.setPaper(this.paper);
      this.decoder.setPageFormat(pageFormat);
   }

   private void loadConfiguration() throws FileNotFoundException, PdfException, org.jpedal.exception.PdfException {
      File file      = new File(fileName);
      String jobName = file.getName().substring(0, file.getName().lastIndexOf("."));
      this.fileInput = new FileInputStream(file);
      this.services = PrintServiceLookup.lookupPrintServices(null, null);
      /* Impressora padr�o */
      this.defaultPrinter    = PrintServiceLookup.lookupDefaultPrintService();
      if (this.defaultPrinter == null) {
         this.defaultPrinter = this.services[this.services.length-1];
      }

      this.printerAttributes = new HashPrintRequestAttributeSet();
      this.printerAttributes.add(new JobName(jobName, null));
      this.decoder = new PdfDecoder();
      this.decoder.openPdfFile(this.fileName);
      this.printerJob = PrinterJob.getPrinterJob();
   }

   private void releaseConfiguration() throws IOException {
      this.fileInput.close();
      this.fileInput         = null;
      this.services          = null;
      this.defaultPrinter    = null;
        this.printerAttributes = null;
        this.decoder.closePdfFile();
        this.decoder           = null;
        this.printerJob        = null;
   }


   private void loadPageConfiguration() throws FileNotFoundException, IOException {
      File file = new File("ImprimirPDF.properties");

      float defaultHeight = 210f;
      float defaultWidth  = 290f;

      if (!file.exists()) {
         /* se o arquivo de configura��o n�o for encontrador
          * � usado o padr�o A4*/
         configurePage(defaultHeight, defaultWidth);
         return;
      }

      FileInputStream fileIn = new FileInputStream(file);
      Properties properties = new Properties();
      properties.load(fileIn);

      String strHeight = properties.getProperty("paper.height");
      String strWidth  = properties.getProperty("paper.width");

      float height = 0f;
      float width  = 0f;

      try {
         height = Float.parseFloat(strHeight);
         width  = Float.parseFloat(strWidth);
      } catch (NumberFormatException e) {
         height = defaultHeight;
         width = defaultWidth;
      }
      configurePage(height, width);
   }

   public void print() throws PrintException,
           FileNotFoundException, IOException, PdfException, PrinterException, org.jpedal.exception.PdfException  {
        loadConfiguration();
      try {
            this.printerAttributes.add(new PageRanges(1, decoder.getPageCount()));

            loadPageConfiguration();
            this.decoder.setTextPrint(PdfDecoder.TEXT);
            this.printerJob.setPageable(this.decoder);

         if (this.printerJob.printDialog(this.printerAttributes)) {
                this.printerJob.print(this.printerAttributes);
         }
         releaseConfiguration();
      } finally {
      }
   }




}

1 Resposta

luisbizzan

Boa tarde alexwebsp, sei que vc já postou seu problema a algum tempo, mas c conseguiu resolve-lo ?
Pois eu estou com um problema parecido, quero imprimir um PDF através de uma URL, para utilizar em uma applet, mas meu problema esta que ele até imprimi mas a impressão sai com a imagem do pdf bem menor doque a folha e não sei o pq? Olha meu código:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.smarapd;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPrintPage;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.DocFlavor;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;

/**
 *
 * @author LGBIZZAN
 */
public class Print3 {

    public Print3(boolean showDialog, String imp) {
        try {
            String url = "http://xxx/resultados/AAKALWCCLWYHHYZNADGX.pdf";
            String docName = "C:\Temp\teste.pdf";
            /*Busca Arquivo na URL*/
            URL remote = new URL(url);
            URLConnection conn = remote.openConnection();
            conn.setRequestProperty("Accept", "*/*");
            InputStream in = conn.getInputStream();
                                    
            File fl = new File(docName);                    
            
            /*Escrever o File*/
            OutputStream outputStream = new FileOutputStream(fl);
            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = in.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }            
            
            FileInputStream fis = new FileInputStream(fl);
            FileChannel fc = fis.getChannel();
            ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
            
            PDFFile curFile = new PDFFile(bb); // Create PDF Print Page
            PDFPrintPage pages = new PDFPrintPage(curFile);

            PrinterJob pjob = PrinterJob.getPrinterJob();                      
            pjob.setJobName(docName);
            Book book = new Book();
            PageFormat pformat = PrinterJob.getPrinterJob().defaultPage();
            book.append(pages, pformat, curFile.getNumPages());
            pjob.setPageable(book);

            PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
            //aset.add(MediaSizeName.ISO_A4); // informa o tipo de folha 
            //aset.add(javax.print.attribute.standard.MediaTray.ENVELOPE);
            // print
            if (showDialog) {
                if(pjob.printDialog())
                    pjob.print();
            }else{
                PrintService impressora = null;
                if(!imp.isEmpty())
                    impressora = buscaImpressora(imp);
                else
                    impressora = PrintServiceLookup.lookupDefaultPrintService();
                pjob.setPrintService(impressora);
                
                pjob.print(aset);
            }
            if(fl.exists())
                fl.delete();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Print3.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Print3.class.getName()).log(Level.SEVERE, null, ex);
        } catch (PrinterException ex) {
            Logger.getLogger(Print3.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public PrintService buscaImpressora(String i){
        PrintService impressora = null;
        DocFlavor df = DocFlavor.SERVICE_FORMATTED.PRINTABLE;  
        PrintService[] ps = PrintServiceLookup.lookupPrintServices(df, null);  
        for (PrintService p: ps) {
            if(p.getName().equalsIgnoreCase(i)){                
                impressora = p;
                break;
            }
        }
        return impressora;
    }
    
    public static void main(String[] args) {  
        new Print3(true,null);
    }
}
Criado 29 de junho de 2009
Ultima resposta 13 de set. de 2013
Respostas 1
Participantes 2