printing html file


hello,

i have a html file. i want to print it. i using jeditorpane for showing the html file. because html file is large enough that i cannot show it whole in jeditorpane. so i used the container jscrollpane. when i want to print the document showing in the jscrollpane it print only the current shwing document not the whole document. please help me to solve this.

Posted On: Thursday 18th of October 2012 10:24:19 PM Total Views:  354
View Complete with Replies

RELATED TOPICS OF Swing / AWT / SWT PROGRAMMING LANGUAGE




java web browser save all images on html for offline viewing

I recently started working on a simple server/client program where i send in a url and it returns that html file. i can them open that file in a simple web browser with thread by javanotes 6 sources. it then loads the images from the web to display them. i want to find out how it opens the html file and finds the image links and i would like to know how to save the images to be used later for offline viewing. webbrowserwiththread src import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import java.net.*; import java.io.*; /** * Defines a simple web browser that can load web pages from * URLs specified by the user in a "Location" box. Almost all * the functionality is provided automatically by the JEditorPane * class. The program loads web pages asynchronously in a * thread. See SimpleWebBrowser for a synchronous version. * This class can be run as a standalone application and has * a nested class that can be run as an applet. The applet * version can probably only read pages from the server from which * it was loaded. */ public class SimpleWebBrowserWithThread extends JPanel { /** * The main routine simply opens a window that shows a SimpleWebBrowserWithThread panel. */ public static void main(String[] args) { JFrame window = new JFrame("SimpleWebBrowserWithThread"); SimpleWebBrowserWithThread content = new SimpleWebBrowserWithThread(); window.setContentPane(content); window.setSize(600,500); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); window.setLocation( (screenSize.width - window.getWidth())/2, (screenSize.height - window.getHeight())/2 ); window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); window.setVisible(true); } /** * The public static class SimpleWebBrowserWithThread.Applet represents this program * as an applet. The applet's init() method simply sets the content * pane of the applet to be a SimpleWebBrowserWithThread. To use the applet on * a web page, use code="SimpleWebBrowserWithThread$Applet.class" as the name of * the class. A reasonable size for the applet is 600 by 480 or larger. */ public static class Applet extends JApplet { public void init() { SimpleWebBrowserWithThread content = new SimpleWebBrowserWithThread(); setContentPane( content ); } } /** * The pane in which documents are displayed. */ private JEditorPane editPane; /** * An input box where the user enters the URL of a document * to be loaded into the edit pane. A value URL string should * contain the substring "://". If the string in the box * does not contain this substring, then "http://" is * prepended to the string. */ private JTextField locationInput; /** * A button that the user can click in order to load the url * that is specified in the location input box. */ private JButton goButton; /** * Defines a listener that responds when the user clicks on * a link in the document. */ private class LinkListener implements HyperlinkListener { public void hyperlinkUpdate(HyperlinkEvent evt) { if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { new LoaderThread(evt.getURL()); } } } /** * Defines a listener that loads a new page when the user * clicks the "Go" button or presses return in the location * input box. */ private class GoListener implements ActionListener { public void actionPerformed(ActionEvent evt) { URL url; try { String location = locationInput.getText().trim(); if (location.length() == 0) throw new Exception(); if (! location.contains("://")) location = "http://" + location; url = new URL(location); } catch (Exception e) { JOptionPane.showMessageDialog(SimpleWebBrowserWithThread.this, "The Location input box does not\nccontain a legal URL."); return; } new LoaderThread(url); } } /** * Defines the thread that actually does the loading of a document. * The thread is also responsible for enabling/disabling the go button * and the location input box. */ private class LoaderThread extends Thread { private URL urlToLoad; LoaderThread(URL url) { // constructor starts the thread. urlToLoad = url; locationInput.setEnabled(false); goButton.setEnabled(false); start(); } public void run() { InputStream in = null; try { editPane.setContentType("text/plain"); editPane.setText("Loading URL " + urlToLoad + "..."); /* Open a URL connection just for the purpose of reading * the content type. I only want to show the document if * the content type is supported by JEditorPane. */ URLConnection connection = urlToLoad.openConnection(); in = connection.getInputStream(); String contentType = connection.getContentType(); if (contentType == null) throw new Exception("Can't determine content type of url."); if ( ! (contentType.startsWith("text/plain") || contentType.startsWith("text/html") || contentType.startsWith("text/rtf") ) ) throw new Exception("Can't display content type " + contentType); editPane.setText("Retrieving document contents..."); locationInput.setText(urlToLoad.toString()); in.close(); // I don't want to actually read from the connection! in = null; editPane.setPage(urlToLoad); } catch (Exception e) { editPane.setContentType("text/plain"); editPane.setText( "Sorry, the requested document was not found\n" +"or cannot be displayed.\n\nError:" + e); } finally { goButton.setEnabled(true); locationInput.setEnabled(true); locationInput.select(); locationInput.requestFocus(); if (in != null) { try { in.close(); } catch (Exception e) { } } } } } /** * Construct a panel that contains a JEditorPane in a JScrollPane, * with a tool bar that has a Location input box and a Go button. */ public SimpleWebBrowserWithThread() { setBackground(Color.BLACK); setLayout(new BorderLayout(1,1)); setBorder(BorderFactory.createLineBorder(Color.BLACK,1)); editPane = new JEditorPane(); editPane.setEditable(false); editPane.addHyperlinkListener(new LinkListener()); add(new JScrollPane(editPane),BorderLayout.CENTER); JToolBar toolbar = new JToolBar(); toolbar.setFloatable(false); add(toolbar,BorderLayout.NORTH); ActionListener goListener = new GoListener(); locationInput = new JTextField("math.hws.edu/javanotes/index.html", 40); locationInput.addActionListener(goListener); goButton = new JButton(" Go "); goButton.addActionListener(goListener); toolbar.add( new JLabel(" Location: ")); toolbar.add(locationInput); toolbar.addSeparator(new Dimension(5,0)); toolbar.add(goButton); } }
VIEWS ON THIS POST

200

Posted on:

Saturday 22nd 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

439

Posted on:

Tuesday 25th September 2012
View Replies!

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.
VIEWS ON THIS POST

331

Posted on:

Monday 1st October 2012
View Replies!

Print Multi page JEditorPane html contents in Java

down vote favorite share [fb] share [tw] I have developed a code in Java where I have embedded HTML content into a JEditorPane by setting its content type to text / html. However this content spills over to the second page and so on. I know that the JEditorPane has a print() method that prints the contents of the JEditorPane and I know that the print() method of the JEditorPane prints all the contents of the JEditorPane and even prints multiple pages. What I want is that the top, left, right and bottom margins should be set to 0. If I would simply leave the work of setting the margins to 0 at run-time by changing the print settings before printing, it would just not work. Due to this I had to implement the Printable interface. But when I used the Printable interface it allows to print only the first page of the JEditorPane. When I searched a lot for this solution I got this link on Google; http://download.oracle.com/javase/tutorial/displayCode.htmlcode=http://download.oracle.com/javase/tutorial/2d/printing/examples/PaginationExample.java But the problem here is that I am using html contents in the JEditorPane. I dont know how to integrate the above solution provided in the link with a JEditorPane that consists of HTML Code
VIEWS ON THIS POST

166

Posted on:

Wednesday 17th October 2012
View Replies!

printing JTables - concatenating? what about the panels?

I am printing a JTable in this manner: StringBuffer sb = new StringBuffer(); PrintRequestAttributeSet attribs = new HashPrintRequestAttributeSet(); attribs.add(new Copies(1)); attribs.add(OrientationRequested.PORTRAIT); int xx = 1; //left and right margin int yy = 1; //top and bottom margin. Note that bottom margin cannot be less than 15 mm int ww = 845; //Width int hh = 599; //Height int units = MediaPrintableArea.MM; attribs.add(new MediaPrintableArea(xx, yy, ww, hh, units)); String title = "My Table"; sb.append(title); MessageFormat footer = new MessageFormat("Page {0}"); getPayrollHeadcountList().getTable().setPreferredSize(new Dimension(500, 500)); getPayrollHeadcountTotalList().getTable().setPreferredSize(new Dimension(500, 100)); try { getPayrollHeadcountList().getTable().print(PrintMode.FIT_WIDTH, header, footer, true, attribs, false); //getPayrollHeadcountTotalList().getTable().print(PrintMode.FIT_WIDTH, header, footer, true, attribs, false); } catch (PrinterException pe) { Debug.trace(pe); }
VIEWS ON THIS POST

527

Posted on:

Wednesday 17th October 2012
View Replies!

Simple text printing with pagebreaks

I have a report displayed in a GUI application as a simple text within JTextComponent. My goal is to print it but with page breaks at certain points. I have inserted \f at those places, however when I print page breaks are ignored and I get a weird character printed in those places where \f was and the rest of the text is just printed out without page breaks. One thing I v noticed is that if I output the report to a file and open it with MS Word page breaks are recognised and report is displayed correctly. However, if I try to open it with notepad page breaks are not recognised. I have tried converting the text to RTF but the \f character was still ignored. I would really appreciate if anyone shares their experience with something similar and how did you solve it cheers
VIEWS ON THIS POST

474

Posted on:

Wednesday 17th October 2012
View Replies!

printing a jtable

I've got a swing JTable of about 20 rows ans 40 columns that I want to print on paper. I tried the table.print() method but that doesn't work, I just get one big empty cell on the paper. I tried an example from another site and that one works perfectly (http://java.sun.com/docs/books/tutorial/uiswing/misc/printtable.html). Does anyone know what's going wrong Is my table too large for the paper and do I need to resize it, and if so how
VIEWS ON THIS POST

455

Posted on:

Wednesday 17th October 2012
View Replies!

JTable printing problem

I have sample of JTable with data that i would like to be right aligned, also orange background color cell renderer is applied, and font is set to be Tahoma BoldItalic with font size of 13. Problems that arise are, grid lines are over cell text, and also applied background color looks strange when PDF printer is used and document is zoomed. Interesting thing is that when font is set to be even grid lines doesn't intersect cell text. import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.JTable.PrintMode; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class TablePrintTest extends JFrame { private static final long serialVersionUID = 1L; private static final Object[] COLUMN_NAMES = { "Column1", "Column2", "Column3" }; private static final Object[][] CELL_VALUES = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; private JButton printButton; private JTable table; public TablePrintTest() { super("TablePrintTest"); createGui(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private void createGui() { table = new JTable(new DefaultTableModel() { private static final long serialVersionUID = 1L; @Override public Class getColumnClass(int columnIndex) { return Number.class; } @Override public int getColumnCount() { return COLUMN_NAMES.length; } @Override public int getRowCount() { return CELL_VALUES.length; } @Override public String getColumnName(int column) { return COLUMN_NAMES[column].toString(); } @Override public Object getValueAt(int row, int column) { return CELL_VALUES[row][column]; } }); table.setDefaultRenderer(Number.class, new DefaultTableCellRenderer() { private static final long serialVersionUID = 1L; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel label = (JLabel) super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column); label.setHorizontalAlignment(SwingConstants.RIGHT); return label; } public java.awt.Color getBackground() { return Color.orange; }; }); table.setFont(new Font("Tahoma", Font.ITALIC | Font.BOLD, 13)); printButton = new JButton("Print"); printButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Printable printable = table.getPrintable(PrintMode.NORMAL, null, null); PrinterJob pJob = PrinterJob.getPrinterJob(); pJob.setPrintable(printable); if (pJob.printDialog()) { try { pJob.print(); } catch (PrinterException e1) { e1.printStackTrace(); } } } }); JPanel contentPane = new JPanel(new BorderLayout()); contentPane.add(printButton, BorderLayout.NORTH); contentPane.add(new JScrollPane(table), BorderLayout.CENTER); setContentPane(contentPane); pack(); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new TablePrintTest().setVisible(true); } }); } }
VIEWS ON THIS POST

508

Posted on:

Wednesday 17th October 2012
View Replies!

Problem in printing JTable values

Dear Friends, I have to print the JTable values (on paper using print dialogue box). I'm using jtableObj.print to print the table values. But jtableObj.print takes more time to print the table values because it prints the values as a image(approximately 5 mins to print 10 pages). My code is , boolean complete = tableObj.print(mode, header, footer, showPrintDialog, null, interactive, null);
VIEWS ON THIS POST

460

Posted on:

Wednesday 17th October 2012
View Replies!

printing on A4 paper

The paper object creates a letter sized piece of paper with one inch margins. Is there any way to set different margins to allow a page designed to fit on letter to also print on A4 by reducing the margins Or any other ideas ------------------
VIEWS ON THIS POST

548

Posted on:

Thursday 18th October 2012
View Replies!

Not able to compile Swing files

my java files are in the jdk\bin directory but still I am not able to compile the Swing classes. The problem is only for swing classes. I guess this is a classpath problem. Could anyone please let me know which jar file I need to include in classpath for swings Look forward to responses
VIEWS ON THIS POST

89

Posted on:

Thursday 18th October 2012
View Replies!

Regarding reading a property file

hello, Please let me know what a property file is ,how to make it & how to make the parameters read from this file into a swing application\t Thanking you, Jignesh
VIEWS ON THIS POST

102

Posted on:

Thursday 18th October 2012
View Replies!

Loading html page in swing

I want to load html page which contains javascript code like :- function fun() { window.open('directoryname/filename.htm', 'title', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes ,height=500,width=700') } I am using JEditor to show html pages i.e. JEditor.setPage(url) method to show url . But it is not understanding javascript code. Is there any solution to make JEditor script enabled second solution is to load default browser .If I load default browser ,it is showing browser correctly.But I don't want to show any menu-bar or toolbar.Is there any solution to hide menubar & toolbars of browser at run-time. Or if there is another solution to show html pages [containning scripts] .Please tell me.
VIEWS ON THIS POST

133

Posted on:

Thursday 18th October 2012
View Replies!

Outputting a text file to a Java GUI component

Is there anyway I can output a '.txt' file to a Java Component..
VIEWS ON THIS POST

108

Posted on:

Thursday 18th October 2012
View Replies!

printing html and images using JEditorPane

hi i am working on printing multiple html and images(png) in a single batch.. i am able to print all in a single batch if html files are single page files but if they are multipage files i am unable to print them. i am rendering html to a JEditorPane. i can print multiple multipage html files in a single batch but unable to do html files and images in a single batch .. anyone can help me thanx in advance -if you want i can provide code bye madhu
VIEWS ON THIS POST

365

Posted on:

Thursday 18th October 2012
View Replies!

problem with file chooser

Hi all, just got a small query regarding JFileChooser. i want the user to restrict only to select .jar files . so i used JFileChooser fileChooser = new JFileChooser("Select a jar file..."); JarFilter1 jFilter = new JarFilter1( "jar", "Only Jars" ); fileChooser.setFileFilter(jFilter); FileFilter allfileFilter = fileChooser.getAcceptFileFilter(); fileChooser.removeChoosableFileFilter(allfileFilter); The jarFilter is just like this public class JarFilter1 extends FileFilter { String m_desc = null; String m_ext = null; public JarFilter1(String m_ext, String m_desc) { this.m_ext = m_ext; this.m_desc = m_desc; } public boolean accept ( File f ) { if ( f == null ) return false; if ( f.isDirectory () ) return true; return f.getName().toLowerCase().endsWith(m_ext); } public String getDescription () { return m_desc; } } int returnVal = fileChooser.showOpenDialog(this); it shows only directories and jar files, that is fine.. but when i type sample.class or *.class in the filename text box of the dialog, *.class filter gets added to the combo box, so i can select the class file and press ok. and this file is returned back to me.. but i dont want the user to get out of the open dialog until he selects a .jar file...could you please let me know how could this be possible\t
VIEWS ON THIS POST

129

Posted on:

Thursday 18th October 2012
View Replies!

Setting file name for JFileChooser SAVE dialog

Hi-- I am wondering how to do the following: when a user clicks on a save menu item, a save JFileChooser pops up. I would like to have a default file name set in the FileName box on the chooser, similar to what applications like Microsft word has. Right now, no file name will appear until the user has selected a file. I also need to know how to get the text from this box in the case that the user enters a new file name (the getSelection function is not useful here because the user will not have selected an existing file.)
VIEWS ON THIS POST

96

Posted on:

Thursday 18th October 2012
View Replies!

Images fail to show - filepath prob?

you , I finished a 3 tiered standalone application that has a neat looking GUI (for a swing beginner)... problem is, when I tested the packaged app on another system everything worked fine apart from all my images, which failed to appear. The images are used as backgrounds for all my different screens and components are positioned on top using GridbagLayout/constraints etc... Works fine on my system and I have placed all the relevant image files in the gui package. I think the problem lies in the filepath specification, where I defined it as: filename = "c:/JavaParcs/project/gui/lake.jpg"; This is specific to my system but how can I fix it so that it can be accessed by any other (I tried taking out the c:/ and the pics dissappeared on mine too) I also tried: filename = "./JavaParcs/project/gui/lake.jpg"; thinking that if a dot means look in the current dir.... but that didn't work either. Can anyone help or at least point me to a relevant resource on the matter
VIEWS ON THIS POST

84

Posted on:

Thursday 18th October 2012
View Replies!

printing data from JEditor Pane

I have a program in which the data is shown in JEditor Pane. I have used HTMl tags to get the deed format. Now i want to print it. how should i proceed :roll:
VIEWS ON THIS POST

323

Posted on:

Thursday 18th October 2012
View Replies!