我编码用ByteArrayOutputStream在内存中创建iText PDF文件,点击一个按钮,同时点击同一个按钮打印该PDF文件。编码没有错误..
以下是特定按钮的代码;
int print = JOptionPane.showConfirmDialog(null, "Do you really want to Print the Invoice ?","Print Confirmation",JOptionPane.YES_NO_OPTION);
if((print)==0){
try{
String saledate = ((JTextField)dayChooser.getDateEditor().getUiComponent()).getText();
String invoice = InvoiceNo_txt.getText();
String citems = countitems_txt.getText();
String tDis =totalDiscount_txt.getText();
String ntotal = NetTotal_txt.getText();
//setting data to saleinfo db table
try{
String sql = "Insert into saleinfo (SaleDate,InvoiceNo,TotalItems,TotalDiscount,NetTotal)values (?,?,?,?,?)";
pst=conn.prepareStatement(sql);
pst.setString(1, saledate);
pst.setString(2, invoice);
pst.setString(3, citems);
pst.setString(4, tDis);
pst.setString(5, ntotal);
pst.execute();
}catch(Exception e){
}
//creting itext report for prining
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document salepdf = new Document();
PdfWriter.getInstance(salepdf,baos);
//salepdf.setPageSize(PageSize.A7);
salepdf.open();
//file content added here
salepdf.close();
byte[] pdfbyte = baos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(pdfbyte);
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
AttributeSet attributeSet = new HashAttributeSet();
attributeSet.add(new PrinterName("NPI8DA48A", null));
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob job= service.createPrintJob();
Doc pdfp = new SimpleDoc(bis, flavor, null);
PrintJobWatcher watcher = new PrintJobWatcher(job);
job.print(pdfp, null);
watcher.waitForDone();
}catch(DocumentException | PrintException ex){
Logger.getLogger(Newsale.class.getName()).log(Level.SEVERE, null, ex);
}
//set null feilds after printing
DefaultTableModel model = (DefaultTableModel) tableSale.getModel();
model.setRowCount(0);
countitems_txt.setText("");
totalDiscount_txt.setText("");
NetTotal_txt.setText("");
}
PrintJobWatcher类;
static class PrintJobWatcher {
// true iff it is safe to close the print job's input stream
boolean done = false;
PrintJobWatcher(DocPrintJob job) {
// Add a listener to the print job
job.addPrintJobListener(new PrintJobAdapter() {
public void printJobCanceled(PrintJobEvent pje) {
allDone();
}
public void printJobCompleted(PrintJobEvent pje) {
allDone();
}
public void printJobFailed(PrintJobEvent pje) {
allDone();
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
allDone();
}
void allDone() {
synchronized (PrintJobWatcher.this) {
done = true;
PrintJobWatcher.this.notify();
}
}
});
}
public synchronized void waitForDone() {
try {
while (!done) {
wait();
}
} catch (InterruptedException e) {
}
}
}
请注意这一点;
问题是,当我单击“打印”按钮时,文件将被添加到打印队列中并立即消失..
为什么代码不起作用?