Java code printing junk characters in PDF




I have a JAVA code that reads a PDF file from remote server. It then merges it with an existing PDF file and print the resultant. However, sometimes I observe that the PDF printed contains gibbersih data. It doesn't happen always. Is it some issue with the fonts used in PDF Or some inherent issue of Java, while printing PDF files.

I use a print job object to print PDF file. Logic for printing the PDF file is as following

private boolean printDocument(String fileName){
System.out.println("printComplianceDocument : Begin");
boolean result = false;
PDDocument document = null;
PDPage page = new PDPage();

try {
document = PDDocument.load(fileName);
PrinterJob pjob = PrinterJob.getPrinterJob();

PrintRequestAttributeSet attr_set = new HashPrintRequestAttributeSet();
attr_set.add(Sides.DUPLEX);
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, attr_set);
for(PrintService service : services){
if (service.getName().equalsIgnoreCase(SystemProp.getInstance().getWorkStation().getDfltRptPrinter().getAddress().trim())){
System.out.println("Printing Document to printer: " + service.getName());
pjob.setPrintService(service);
pjob.setPageable(document);
pjob.print(attr_set);
result = true;
break;
}
}

//Try printing to Default Printer if appropriate Print Service is not found
if(!result){
PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
System.out.println("Printing Document to Default Printer: " + defaultPrintService.getName());
pjob.setPrintService(defaultPrintService);
pjob.setPageable(document);
pjob.print(attr_set);
result = true;
}

} catch (IOException e) {
// Exception
} catch (PrinterException e) {
// Exception
}
System.out.println("printDocument : End");
return result;
}

Please share your ideas and suggest solutions if you could.
Posted On: Monday 1st of October 2012 04:29:40 AM Total Views:  244
View Complete with Replies

RELATED TOPICS OF Swing / AWT / SWT PROGRAMMING LANGUAGE




InputMap / ActionMap actions leave characters in TextArea

I've added a JPopupMenu to a JPanel with a TextArea in it. The popup menu is attached to the TextArea with the usual MouseListener. To bring up the popup menu with a keystroke, I've gotten the InputMap and added a (key, action) pair to it. The key is an alt P, the action is a defined Action instance. The software works fine in popping up the menu and closing the menu. Alas, if the focus is on the text area, alt p ALSO produces a "pi" symbol in the text area. The Action class uses an ActionEvent that doesn't have a consume() method. What sort of action for the ActionMap should I be using so that I can consume the alt P
VIEWS ON THIS POST

73

Posted on:

Monday 24th September 2012
View Replies!

Generating pdf from jtable

I am developing a tool in java to generate pdf from jtable. I tried to use itext but I am getting black pdf. Below is the code that I used. import java.awt.BorderLayout; import java.awt.Graphics2D; import java.awt.Shape; import java.io.FileOutputStream; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTable; //import com.itextpdf.awt.PdfGraphics2D; import com.itextpdf.text.Document; import com.itextpdf.text.PageSize; import com.itextpdf.text.pdf.PdfContentByte; //import com.itextpdf.text.pdf.PdfTemplate; import com.itextpdf.text.pdf.PdfWriter; public class Pdf extends JFrame { /** * */ private static final long serialVersionUID = 1L; private JTable table; public Pdf() { getContentPane().setLayout(new BorderLayout()); createTable(); } private void createTable() { Object[][] data = {{ "a", "b", "e", new Integer(5), new Boolean(false) } }; String[] columnNames = { "A", "B", "C", "D", "E" }; table = new JTable(data, columnNames); JPanel tPanel = new JPanel(new BorderLayout()); tPanel.add(table.getTableHeader(), BorderLayout.NORTH); tPanel.add(table, BorderLayout.CENTER); getContentPane().add(tPanel, BorderLayout.CENTER); } private void print() { Document document = new Document(PageSize.A4.rotate()); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("jTable.pdf")); document.open(); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); Graphics2D g2 = cb.createGraphicsShapes(500, 500); Shape oldClip = g2.getClip(); g2.clipRect(0, 0, 500, 500); table.print(g2); g2.setClip(oldClip); g2.dispose(); cb.restoreState(); } catch (Exception e) { System.err.println(e.getMessage()); } document.close(); } public static void main(String[] args) { Pdf frame = new Pdf(); frame.pack(); frame.setVisible(true); frame.print(); } }
VIEWS ON THIS POST

135

Posted on:

Monday 24th September 2012
View Replies!

Rpelacing characters (*) with user input

Hi all - There has to be a simple solution to this, but as far as I've searched, I've found nothing. I have a Custom TextField that is descended from java.awt.TextField (believe me, I'd much rather use swing). The user must enter 14 characters into this field. The problem is, most of those characters are zeros and they have to count for every keyboard stroke they hit. I want to put in fourteen * so every time they enter a character, the * is replaced by their input. That way, they see how many characters they have left because the * will be one less for every letter or number they put in. Like this: ************** B************* BN************ BNO************ BNO4********** And so on. Does anyone know a good way to do this I am an experienced developer, but have never had this challenge before.
VIEWS ON THIS POST

105

Posted on:

Monday 24th September 2012
View Replies!

problem in printing swing components?

i have a registration page, and after registration of a student i need to print the tc (transfer certificate), in the (Photo1430.jpg) image format, (in the same format shown in the image). field values are coming from the database.(ie. value of name, value of dob, value of place so on...) i am doing something like this: import java.awt.*; import java.awt.event.*; import java.awt.print.*; import javax.swing.*; public class PrintUIWindow implements Printable, ActionListener { JFrame frameToPrint; JLabel lblStuName, lblBirthPlace, lblDob, lblLastSch, lblLastExam, lblYearOdAdd,lblStudyingStandard; JLabel d, d1, d2, d3, d4; static JPanel panel; Box horiz1, horiz2, horiz3, horiz4, horiz5, horiz6; public PrintUIWindow() { panel = new JPanel(); lblStuName = new JLabel("1.) Name of Student (in Full)"); lblBirthPlace = new JLabel("2.) Place of Birth"); lblDob = new JLabel("3.) Date of Birth, Month and year (in figures)"); lblLastSch = new JLabel("4.) Last School College Attended"); lblLastExam = new JLabel("5.) Last Examination Passed"); d1 = new JLabel(" : ........................................................."); d2 = new JLabel(" : ........................................................."); d3 = new JLabel(" : ........................................................."); d4 = new JLabel(" : ........................................................."); d = new JLabel(" : ........................................................."); horiz1 = Box.createHorizontalBox(); horiz1.add(lblStuName); horiz1.add(d); horiz2 = Box.createHorizontalBox(); horiz2.add(lblBirthPlace); horiz2.add(d1); horiz3 = Box.createHorizontalBox(); horiz3.add(lblDob); horiz3.add(d2); horiz4 = Box.createHorizontalBox(); horiz4.add(lblLastSch); horiz4.add(d3); horiz5 = Box.createHorizontalBox(); horiz5.add(lblLastExam); horiz5.add(d4); Box vert = Box.createVerticalBox(); vert.add(Box.createVerticalStrut(100)); vert.add(horiz1); vert.add(Box.createVerticalStrut(30)); vert.add(horiz2); vert.add(Box.createVerticalStrut(30)); vert.add(horiz3); vert.add(Box.createVerticalStrut(30)); vert.add(horiz4); vert.add(Box.createVerticalStrut(30)); vert.add(horiz5); panel.add(vert); } public int print(Graphics g, PageFormat pf, int page) throws PrinterException { if (page > 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) g; g2d.translate(pf.getImageableX(), pf.getImageableY()); /* Now print the window and its visible contents */ frameToPrint.print(g); /* tell the caller that this page is part of the printed document */ return PAGE_EXISTS; } public void actionPerformed(ActionEvent e) { PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable(this); boolean ok = job.printDialog(); if (ok) { try { job.print(); } catch (PrinterException ex) { /* The job did not successfully complete */ } } } public static void main(String args[]) { JFrame f = new JFrame("Print TC"); JButton printButton = new JButton("Print TC"); printButton.addActionListener(new PrintUIWindow()); panel.add("South", printButton); f.add(panel); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.pack(); f.setVisible(true); } }
VIEWS ON THIS POST

317

Posted on:

Tuesday 25th September 2012
View Replies!

Displaying pdf and rtf files

I'm developing an application that could display most of the document formats. Currently i've created seperate clases for pdf and rtf. But i want to view pdf and rtf files in a single window based upon extensions either pdf or rtf. The codes for rtf and pdf are here given below: This is for rtf: import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.text.*; import javax.swing.event.*; import javax.swing.border.*; import javax.swing.text.rtf.*; public class WordProcessor extends JFrame { protected JTextPane m_monitor; protected StyleContext m_context; protected DefaultStyledDocument m_doc; protected RTFEditorKit m_kit; protected JFileChooser m_chooser; protected SimpleFilter m_rtfFilter; protected JToolBar m_toolBar; public WordProcessor() { super("DIGITAL READER-RTF"); setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\CS_Lab\\Downloads\\Dr.jpg")); setSize(600, 400); // Make sure we install the editor kit before creating // the initial document. m_monitor = new JTextPane(); m_kit = new RTFEditorKit(); m_monitor.setEditorKit(m_kit); m_context = new StyleContext(); m_doc = new DefaultStyledDocument(m_context); m_monitor.setDocument(m_doc); JScrollPane ps = new JScrollPane(m_monitor); getContentPane().add(ps, BorderLayout.CENTER); JMenuBar menuBar = createMenuBar(); setJMenuBar(menuBar); m_chooser = new JFileChooser(); m_chooser.setCurrentDirectory(new File(".")); m_rtfFilter = new SimpleFilter("rtf", "RTF Documents"); m_chooser.setFileFilter(m_rtfFilter); WindowListener wndCloser = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; addWindowListener(wndCloser); setVisible(true); } protected JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu mFile = new JMenu("File"); mFile.setMnemonic('f'); ImageIcon iconNew = new ImageIcon("file_new.gif"); Action actionNew = new AbstractAction("New", iconNew) { public void actionPerformed(ActionEvent e) { m_doc = new DefaultStyledDocument(m_context); m_monitor.setDocument(m_doc); } }; JMenuItem item = mFile.add(actionNew); item.setMnemonic('n'); ImageIcon iconOpen = new ImageIcon("file_open.gif"); Action actionOpen = new AbstractAction("Open...", iconOpen) { public void actionPerformed(ActionEvent e) { WordProcessor.this.setCursor( Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); Thread runner = new Thread() { public void run() { if (m_chooser.showOpenDialog(WordProcessor.this) != JFileChooser.APPROVE_OPTION) return; WordProcessor.this.repaint(); File fChoosen = m_chooser.getSelectedFile(); // Recall that text component read/write operations are // thread safe. Its ok to do this in a separate thread. try { InputStream in = new FileInputStream(fChoosen); m_doc = new DefaultStyledDocument(m_context); m_kit.read(in, m_doc, 0); m_monitor.setDocument(m_doc); in.close(); } catch (Exception ex) { ex.printStackTrace(); } WordProcessor.this.setCursor(Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR)); } }; runner.start(); } }; item = mFile.add(actionOpen); item.setMnemonic('o'); ImageIcon iconSave = new ImageIcon("file_save.gif"); Action actionSave = new AbstractAction("Save...", iconSave) { public void actionPerformed(ActionEvent e) { WordProcessor.this.setCursor( Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); Thread runner = new Thread() { public void run() { if (m_chooser.showSaveDialog(WordProcessor.this) != JFileChooser.APPROVE_OPTION) return; WordProcessor.this.repaint(); File fChoosen = m_chooser.getSelectedFile(); // Recall that text component read/write operations are // thread safe. Its ok to do this in a separate thread. try { OutputStream out = new FileOutputStream(fChoosen); m_kit.write(out, m_doc, 0, m_doc.getLength()); out.close(); } catch (Exception ex) { ex.printStackTrace(); } // Make sure chooser is updated to reflect new file m_chooser.rescanCurrentDirectory(); WordProcessor.this.setCursor(Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR)); } }; runner.start(); } }; item = mFile.add(actionSave); item.setMnemonic('s'); mFile.addSeparator(); Action actionExit = new AbstractAction("Exit") { public void actionPerformed(ActionEvent e) { System.exit(0); } }; item = mFile.add(actionExit); item.setMnemonic('x'); menuBar.add(mFile); m_toolBar = new JToolBar(); JButton bNew = new SmallButton(actionNew, "New document"); m_toolBar.add(bNew); JButton bOpen = new SmallButton(actionOpen, "Open RTF document"); m_toolBar.add(bOpen); JButton bSave = new SmallButton(actionSave, "Save RTF document"); m_toolBar.add(bSave); getContentPane().add(m_toolBar, BorderLayout.NORTH); return menuBar; } public static void main(String argv[]) { UIManager.LookAndFeelInfo plafinfo[] = UIManager.getInstalledLookAndFeels(); boolean nimbusfound=false; int nimbusindex=0; for (int look = 0; look < plafinfo.length; look++) { if(plafinfo[look].getClassName().toLowerCase().contains("nimbus")) { nimbusfound=true; nimbusindex=look; } } try { if(nimbusfound) { UIManager.setLookAndFeel(plafinfo[nimbusindex].getClassName()); } else UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch(Exception e) { } new WordProcessor(); } } // Class SmallButton unchanged from section 4.8 class SmallButton extends JButton implements MouseListener { protected Border m_raised; protected Border m_lowered; protected Border m_inactive; public SmallButton(Action act, String tip) { super((Icon)act.getValue(Action.SMALL_ICON)); m_raised = new BevelBorder(BevelBorder.RAISED); m_lowered = new BevelBorder(BevelBorder.LOWERED); m_inactive = new EmptyBorder(2, 2, 2, 2); setBorder(m_inactive); setMargin(new Insets(1,1,1,1)); setToolTipText(tip); addActionListener(act); addMouseListener(this); setRequestFocusEnabled(false); } public float getAlignmentY() { return 0.5f; } public void mousePressed(MouseEvent e) { setBorder(m_lowered); } public void mouseReleased(MouseEvent e) { setBorder(m_inactive); } public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) { setBorder(m_raised); } public void mouseExited(MouseEvent e) { setBorder(m_inactive); } } // Class SimpleFilter unchanged from section 14.1.9 class SimpleFilter extends javax.swing.filechooser.FileFilter { private String m_description = null; private String m_extension = null; public SimpleFilter(String extension, String description) { m_description = description; m_extension = "."+extension.toLowerCase(); } public String getDescription() { return m_description; } public boolean accept(File f) { if (f == null) return false; if (f.isDirectory()) return true; return f.getName().toLowerCase().endsWith(m_extension); } } [\code] Code of pdf viewr using jpedal library: [code=java] package org.jpedal.examples.jpaneldemo; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.WindowConstants; import org.jpedal.PdfDecoder; import org.jpedal.exception.PdfException; import org.jpedal.examples.simpleviewer.utils.FileFilterer; import org.jpedal.fonts.FontMappings; public class JPanelDemo extends JFrame { /** * */ private static final long serialVersionUID = 1L; private String viewerTitle="Digital Reader-PDF"; /**the actual JPanel/decoder object*/ private PdfDecoder pdfDecoder; /**name of current PDF file*/ private String currentFile=null; /**current page number (first page is 1)*/ private int currentPage=1; private final JLabel pageCounter1=new JLabel("Page "); private JTextField pageCounter2=new JTextField(4);//000 used to set prefered size private JLabel pageCounter3=new JLabel("of");//000 used to set prefered size /** * construct a pdf viewer, passing in the full file name */ public JPanelDemo(String name){ pdfDecoder = new PdfDecoder(true); //ensure non-embedded font map to sensible replacements FontMappings.setFontReplacements(); currentFile = name;//store file name for use in page changer try{ //this opens the PDF and reads its internal details pdfDecoder.openPdfFile(currentFile); //these 2 lines opens page 1 at 100% scaling pdfDecoder.decodePage(currentPage); pdfDecoder.setPageParameters(1,1); //values scaling (1=100%). page number }catch(Exception e){ e.printStackTrace(); } //setup our GUI display initializeViewer(); //set page number display pageCounter2.setText(String.valueOf(currentPage)); pageCounter3.setText("of "+pdfDecoder.getPageCount()); } /** * construct an empty pdf viewer and pop up the open window */ public JPanelDemo(){ setTitle(viewerTitle); setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\CS_Lab\\Downloads\\Dr.jpg")); pdfDecoder = new PdfDecoder(true); //ensure non-embedded font map to sensible replacements FontMappings.setFontReplacements(); initializeViewer(); // selectFile(); } /** * opens a chooser and allows user to select a pdf file and opens it */ private void selectFile() { JFileChooser open = new JFileChooser("."); open.setFileSelectionMode(JFileChooser.FILES_ONLY); String[] pdf = new String[] { "pdf" }; open.addChoosableFileFilter(new FileFilterer(pdf,"Pdf (*.pdf)")); int resultOfFileSelect = JFileChooser.ERROR_OPTION; while(resultOfFileSelect==JFileChooser.ERROR_OPTION){ resultOfFileSelect = open.showOpenDialog(this); if(resultOfFileSelect==JFileChooser.ERROR_OPTION) System.err.println("JFileChooser error"); if(resultOfFileSelect==JFileChooser.APPROVE_OPTION){ currentFile = open.getSelectedFile().getAbsolutePath(); currentPage = 1; try{ //close the current pdf before opening another pdfDecoder.closePdfFile(); // this opens the PDF and reads its internal details pdfDecoder.openPdfFile(currentFile); //check for password encription and acertain if(!checkEncryption()){ //if file content is not accessable make user select a different file resultOfFileSelect = JFileChooser.CANCEL_OPTION; } // these 2 lines opens page 1 at 100% scaling pdfDecoder.decodePage(currentPage); pdfDecoder.setPageParameters(1,1); //values scaling (1=100%). page number pdfDecoder.invalidate(); }catch(Exception e){ e.printStackTrace(); } //set page number display pageCounter2.setText(String.valueOf(currentPage)); pageCounter3.setText("of "+pdfDecoder.getPageCount()); setTitle(viewerTitle+" - "+currentFile); repaint(); } } } /** * check if encryption present and acertain password, return true if content accessable */ private boolean checkEncryption() { // check if file is encrypted if(pdfDecoder.isEncrypted()){ //if file has a null password it will have been decoded and isFileViewable will return true while(!pdfDecoder.isFileViewable()) { /** popup window if password needed */ String password = JOptionPane.showInputDialog(this,"Please enter password"); /** try and reopen with new password */ if (password != null) { try { pdfDecoder.setEncryptionPassword(password); } catch (PdfException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } //pdfDecoder.verifyAccess(); } } return true; } //if not encrypted return true return true; } /** * setup the viewer and its components */ private void initializeViewer() { setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container cPane = getContentPane(); cPane.setLayout(new BorderLayout()); JButton open = initOpenBut();//setup open button Component[] itemsToAdd = initChangerPanel();//setup page display and changer JPanel topBar = new JPanel(); topBar.setLayout(new FlowLayout(FlowLayout.LEFT,0,0)); topBar.add(open); // topBar.add(pageChanger); for(int i=0;i10){ currentPage -= 10; try { pdfDecoder.decodePage(currentPage); pdfDecoder.invalidate(); repaint(); } catch (Exception e1) { System.err.println("back 10 pages"); e1.printStackTrace(); } // set page number display pageCounter2.setText(String.valueOf(currentPage)); } } }); /**back icon*/ JButton back = new JButton(); back.setBorderPainted(false); URL backImage =getClass().getResource("/org/jpedal/examples/simpleviewer/res/back.gif"); back.setIcon(new ImageIcon(backImage)); back.setToolTipText("Rewind one page"); // currentBar1.add(back); list[2] = back; back.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(currentFile!=null && currentPage>1){ currentPage -= 1; try { pdfDecoder.decodePage(currentPage); pdfDecoder.invalidate(); repaint(); } catch (Exception e1) { System.err.println("back 1 page"); e1.printStackTrace(); } // set page number display pageCounter2.setText(String.valueOf(currentPage)); } } }); pageCounter2.setEditable(true); pageCounter2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent a) { String value=pageCounter2.getText().trim(); int newPage; //allow for bum values try{ newPage=Integer.parseInt(value); if((newPage>pdfDecoder.getPageCount())|(newPage
VIEWS ON THIS POST

108

Posted on:

Saturday 29th September 2012
View Replies!