Buscar
Social
Ofertas laborales ES

Foro sobre Java SE > Imprimir en JAVA, problema a generar

Hola a todos,

Tengo el siguiente JFrame que lo que hace es leer un pdf de una url y manda la orden de impresion con este.

La cuestion es que con una impresora virtual me funciona bien, pero con una fisica no, ya probe con 3 impresoras diferentes y aunque se ve que manda la peticion a al impresora, esta no imprime ningun papel.

Por favor si alguien me puede indicar que estoy haciendo mal se los agradeceria.

package pruebaimpresion;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.*;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import javax.print.*;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.print.attribute.standard.OrientationRequested;

/**
*
* @author nn
*/
public class DemoFrame extends javax.swing.JFrame implements Printable {

/**
* Creates new form DemoFrame
*/
public DemoFrame() {
initComponents();
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});

jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(209, 209, 209)
.addComponent(jButton1)
.addContainerGap(226, Short.MAX_VALUE))
.addComponent(jScrollPane1)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE)
.addContainerGap())
);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(27, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

String urlStatic = "http://dominio/pdf_remoto.pdf";

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
//System.getSecurityManager().checkPermission(new SocketPermission("192.168.1.3", "connect,resolve"));
ejecutarImpresion();
//otroprint();
} catch (Exception e) {
e.printStackTrace();
//JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.INFORMATION_MESSAGE);
System.out.println("error " + e.getMessage());
jTextArea1.append("\nError imprimiendo: " + e.getMessage());
}
}

private void ejecutarImpresion() throws ImpresoraException, PrinterException, PrintException, FileNotFoundException, IOException, Exception {


// byte[] buffer = leerPDF();
InputStream is = leerPDF();

// //Pruebo a escribirlo
// FileOutputStream fos1 = new FileOutputStream("C:/tmp/download2.pdf");
// //FileOutputStream fos1 = new FileOutputStream("/tmp/download2.pdf");
// fos1.write(buffer, 0, buffer.length);
// fos1.flush();
// fos1.close();
// jTextArea1.append("\nescribio archivo");
//

int unidad = MediaPrintableArea.MM;
float w = 80;
float h = 43;

PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(1));
aset.add(new MediaPrintableArea(0, 0, w, h,
unidad));
// Orientación
OrientationRequested orientation = OrientationRequested.PORTRAIT;
aset.add(orientation);

// DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;//PDF;
DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
//INPUT_STREAM myFormat = javax.print.DocFlavor.INPUT_STREAM.AUTOSENSE;

//Para impresion sin dialogo
// PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, null);
// if (PrintServiceLookup.lookupDefaultPrintService() != null) {
// //DocPrintJob printJob = services[0].createPrintJob();
// DocPrintJob printJob = PrintServiceLookup.lookupDefaultPrintService().createPrintJob();
//
// if (!PrintServiceLookup.lookupDefaultPrintService().isDocFlavorSupported(psInFormat)) {
// System.err.println("The printer does not support the appropriate DocFlavor");
// jTextArea1.append("\nThe printer does not support the appropriate DocFlavor.");
// }
// jTextArea1.append("\nImpresora-> " + PrintServiceLookup.lookupDefaultPrintService().getName());
// //Doc document = new SimpleDoc(buffer, flavor, null);
// Doc document = new SimpleDoc(is, psInFormat, null);
// printJob.print(document, null);
// } else {
// jTextArea1.append("\nNo PDF printer available.");
// System.out.println("No PDF printer available.");
// }

//Para impresion con dialogo.
PrintService printService[] =
PrintServiceLookup.lookupPrintServices(null, null);
PrintService defaultService =
PrintServiceLookup.lookupDefaultPrintService();
PrintService service = ServiceUI.printDialog(null, 200, 200,
printService, defaultService, psInFormat, aset);
if (service != null) {
DocPrintJob job = service.createPrintJob();
DocAttributeSet das = new HashDocAttributeSet();
Doc doc = new SimpleDoc(is, psInFormat, null);
job.print(doc, null);
}else {
jTextArea1.append("\nNo PDF printer available.");
System.out.println("No PDF printer available.");
}

}

public InputStream leerPDF() throws IOException, Exception {

URL url1 = new URL(urlStatic);

// byte[] ba1 = new byte[1024];
// int baLength;

ArrayList<Byte> lista = new ArrayList<Byte>();

try {
// Contacting the URL
System.out.print("Connecting to " + url1.toString() + " ... ");
URLConnection urlConn = url1.openConnection();

// Checking whether the URL contains a PDF
if (!urlConn.getContentType().equalsIgnoreCase("application/pdf")) {
System.out.println("Peligro.\n[Sorry. This is not a PDF.]");
jTextArea1.append("\nPeligro.\n[Sorry. This is not a PDF.] " + urlConn.getContentType());
} else {
}

try {
// Read the PDF from the URL and save to a local file
InputStream is1 = url1.openStream();

// ByteArrayOutputStream tmpOut = new ByteArrayOutputStream();
//
// byte[] buf = new byte[512];
// int len;
// while (true) {
// len = is1.read(buf);
// if (len == -1) {
// break;
// }
// tmpOut.write(buf, 0, len);
// }
// tmpOut.close();


// is1.close();


// Load the PDF document and display its page count
System.out.print("DONE.\nProcessing the PDF ... ");
jTextArea1.append("\nDONE.\nProcessing the PDF ... ");


// return tmpOut.toByteArray();
return is1;

} catch (ConnectException ce) {
ce.printStackTrace();
jTextArea1.append("\nError leyendo pdf: " + ce.getMessage());
//JOptionPane.showMessageDialog(null, ce.getMessage(), "Error", JOptionPane.INFORMATION_MESSAGE);
System.out.println("FAILED.\n[" + ce.getMessage() + "]\n");
}

} catch (NullPointerException npe) {
npe.printStackTrace();
jTextArea1.append("\nError leyendo pdf2: " + npe.getMessage());
//JOptionPane.showMessageDialog(null, npe.getMessage(), "Error", JOptionPane.INFORMATION_MESSAGE);
System.out.println("FAILED.\n[" + npe.getMessage() + "]\n");
}
return null;
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {
new DemoFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration

@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
if (pageIndex > 0) { /*
* We have only one page, and 'page' is zero-based
*/
return NO_SUCH_PAGE;
}

/*
* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
*/
Graphics2D g2d = (Graphics2D) graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
graphics.setColor(Color.decode("0x000000"));
/*
* Now we perform our rendering
*/
graphics.drawString("Hola", 2, 10);
graphics.drawString("mundo", 2, 50);
/*
* tell the caller that this page is part of the printed document
*/
return PAGE_EXISTS;
}

private void otroprint() {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
jTextArea1.append("\nError " + ex.getMessage());
System.out.println("ERR");/*
* The job did not successfully complete
*/
}
}
}
}

agosto 2, 2012 | Unregistered CommenterJuli

He probado el código con una impresora LEXMARK T640 y ha funcionado correctamente.

agosto 2, 2012 | Unregistered CommenterGarca

Como tenia el codigo nunca me funciono pero hice lo siguiente y ahora si me trabaja:
agregue la libreria pdf-render y cree este metodo.


public void printPDF()
throws IOException, PrinterException, ConnectException, NullPointerException {

txtMensajes.append("\nDescargando pdf y buscando impresora... ");
// FileInputStream fileInputStream = new FileInputStream("C:/tmp/download2.pdf");
// byte[] pdfContent = new byte[fileInputStream.available()];
// fileInputStream.read(pdfContent, 0, fileInputStream.available());

URL url1 = new URL(urlStatic);
txtMensajes.append("Connecting to " + url1.toString() + " ... ");
URLConnection urlConn = url1.openConnection();
// Checking whether the URL contains a PDF
if (!urlConn.getContentType().equalsIgnoreCase("application/pdf")) {
System.out.println("Peligro.\n[Sorry. This is not a PDF.]");
txtMensajes.append("\nPeligro.\n[Sorry. This is not a PDF.] " + urlConn.getContentType());
} else {
txtMensajes.append("Validado pdf");
}
// Read the PDF from the URL and save to a local file
InputStream is1 = url1.openStream();

ByteArrayOutputStream tmpOut = new ByteArrayOutputStream();

byte[] buf = new byte[512];
int len;
while (true) {
len = is1.read(buf);
if (len == -1) {
break;
}
tmpOut.write(buf, 0, len);
}
tmpOut.close();
is1.close();

txtMensajes.append("\nDescargó pdf ahora envia peticion a impresora... ");

ByteBuffer buffer = ByteBuffer.wrap(tmpOut.toByteArray());

//---------------------

final PDFFile pdfFile = new PDFFile(buffer);

Printable printable = new Printable() {

@Override
public int print(Graphics graphics, PageFormat pageFormat,
int pageIndex) throws PrinterException {

int pagenum = pageIndex + 1;

if ((pagenum >= 1) && (pagenum <= pdfFile.getNumPages())) {

Graphics2D graphics2D = (Graphics2D) graphics;

PDFPage page = pdfFile.getPage(pagenum);


System.out.println("x " + pageFormat.getImageableX() + ""
+ "y " + pageFormat.getImageableY() + ""
+ "width " + pageFormat.getImageableWidth() + ""
+ "height " + pageFormat.getImageableHeight());
Rectangle imageArea = new Rectangle((int) pageFormat.getImageableX(), (int) pageFormat.getImageableY(),
(int) pageFormat.getImageableWidth(),
(int) pageFormat.getImageableHeight());

graphics2D.translate(0, 0);

PDFRenderer pdfRenderer = new PDFRenderer(page, graphics2D,
imageArea, null, null);

try {

page.waitForFinish();

pdfRenderer.run();

} catch (InterruptedException exception) {

exception.printStackTrace();

}

return PAGE_EXISTS;

} else {

return NO_SUCH_PAGE;

}

}
};

PrinterJob printJob = PrinterJob.getPrinterJob();

PageFormat pageFormat = PrinterJob.getPrinterJob().defaultPage();

printJob.setJobName("print job");

Book book = new Book();

book.append(printable, pageFormat, pdfFile.getNumPages());

printJob.setPageable(book);

Paper paper = new Paper();
paper.setSize(226.771, 121.889); //1/72nds of an inch

System.out.println("Paper " + paper.getWidth() + " : " + paper.getHeight());

paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());

pageFormat.setPaper(paper);

// PrintService[] printServices = PrinterJob.lookupPrintServices();
//
// for (int count = 0; count < printServices.length; ++count) {
//
// if (printerName.equalsIgnoreCase(printServices[count].getName())) {
//
// printJob.setPrintService(printServices[count]);
//
// break;
//
// }
//
// }
PrintService myService = PrintServiceLookup.lookupDefaultPrintService();
txtMensajes.append("\nImpresora-> " + myService.getName());
printJob.setPrintService(myService);

printJob.print();

}

agosto 2, 2012 | Unregistered CommenterAndrés