Solved

Printing document on Legal Paper Only

Posted on 2009-03-30
12
1,448 Views
Last Modified: 2013-12-29
Hello,

I am able to print the document successfully. But How can I force the Printer to print the document on Legal Paper Only?

Thanks in advance.
Alok
0
Comment
Question by:shukla1_alok
12 Comments
 
LVL 12

Expert Comment

by:basav_com
Comment Utility
It seems to be somewhat the settings need to be done from the printer only.
0
 
LVL 26

Expert Comment

by:ksivananth
Comment Utility
0
 

Author Comment

by:shukla1_alok
Comment Utility
Hi ,

Following is the snippet of the code for Printing







protected void printConfirmation() {

try {

		PrintService defaultPrinter = PrintServiceLookup.lookupDefaultPrintService();

		DocPrintJob pj = defaultPrinter.createPrintJob();

		ForcedAcceptPrintService.setupPrintJob(pj); //This is workaround for JDK1.5/1.6 PrinterNot AVailable Bug

		Doc doc = new SimpleDoc(this, DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);

		//Monitor the JOB while it is getting printed

		PrintJobWatcher pjDone = new PrintJobWatcher(job);

			setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

			pj.print(doc, null);

			// Wait for the print job to be done

			pjDone.waitForDone();
 

			//PrinterJob prnJob = PrinterJob.getPrinterJob();

			//prnJob.setPrintable(this);

			//prnJob.setPageable(this);
 

			//if (!prnJob.printDialog()) return;
 

//            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

			//prnJob.print();

			setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

		}

//        catch (PrinterException e) {

//            Logger.error("Error printing.");

//            Logger.error(e.getMessage(), e);

//

//            JOptionPane.showMessageDialog(this, " Error Prinitng " + e.getMessage());

//        }

		catch (PrintException e) {

			Logger.error("Error printing.");

			Logger.error(e.getMessage(), e);

			JOptionPane.showMessageDialog(this, " Error Prinitng " + e.getMessage());

		}

	}
 

//Here Is setting the Format of the Page
 

public int print(Graphics graphics, PageFormat pf, int pageIndex) {

	if (pageIndex > 0) {

		return Printable.NO_SUCH_PAGE;

	}

	paintPane(graphics, pf);

	return Printable.PAGE_EXISTS;

}
 

protected void paintPane(Graphics graphics, PageFormat pf) {
 

	double hScale = Math.min(1, pf.getImageableWidth() / m_pane.getSize().getWidth());

	double vScale = Math.min(1, pf.getImageableHeight() / m_pane.getSize().getHeight());

	double scale = Math.min(hScale, vScale);
 

	Graphics2D g2d = (Graphics2D) graphics;

	g2d.translate(pf.getImageableX(), pf.getImageableY());

	g2d.scale(scale, scale);

	boolean wasBuffered = m_pane.isDoubleBuffered();

	m_pane.paint(g2d);

	m_pane.setDoubleBuffered(wasBuffered);

}

Open in new window

0
 

Author Comment

by:shukla1_alok
Comment Utility
My Code with the snippet after making the following changes works fine on A5 Page but the Text on the A5 is coming in small font basically at the bottom part of the Page.
Changes are attached in the code snippet section


//Is this method protected void paintPane(Graphics graphics, PageFormat pf) where I am defining the Page Size is this needs to be Changed?
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();

		aset.add(MediaSizeName.ISO_A5);

		PrintService defaultPrinter = PrintServiceLookup.lookupDefaultPrintService();

		DocPrintJob printJob = defaultPrinter.createPrintJob();

		Doc confirmationDoc = new SimpleDoc(this, DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
 

//Is this method where I am defining the Page Size is this needs to be Changed?

protected void paintPane(Graphics graphics, PageFormat pf) {

double hScale = Math.min(1, pf.getImageableWidth() / m_pane.getSize().getWidth());

double vScale = Math.min(1, pf.getImageableHeight() / m_pane.getSize().getHeight());

		double scale = Math.min(hScale, vScale);

Graphics2D g2d = (Graphics2D) graphics;

		g2d.translate(pf.getImageableX(), pf.getImageableY());

		g2d.scale(scale, scale);

		boolean wasBuffered = m_pane.isDoubleBuffered();

		m_pane.paint(g2d);

		m_pane.setDoubleBuffered(wasBuffered);

	}

Open in new window

0
 

Author Comment

by:shukla1_alok
Comment Utility
Hello All,

Just to give some historical perspective on the Problem

1. We just upgraded our application from JDK1.4 to JDK1.5
2. We were printing our Documents using the PrinterJob prnJob = PrinterJob.getPrinterJob();
3. After the Upgrade the we were able to print 2 or 3 copies of the document but after that we would get an error message stating java.awt.print.PrinterException: Printer is not accepting job.
4. After doing some research I came to know about this bug at the SDK level
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6525150
5. I came to know about the work around http://forums.sun.com/thread.jspa?threadID=766606. The code snippet is added in the code snippet section.
6. With the workaround the problem has been bypassed rather than being solved.
7. Now I am able to print without any problem but the Page is not getting printed in proper format on A5 Size Paper i) The Fonts are not Proper ii) The text is printed on the page in the specific section of the page TOP MIDDLE Section.

Please let me know if anybody has encountered the problem.

Thanks,
Alok

**

	 * ForcedAcceptPrintService is a PrintService wrapper class that allows printing to be

	 * attempted even if Java thinks the 'Printer is not accepting job'.  It is recommended

	 * to use this after prompting the user, so they will see that the printer is

	 * reporting as offline and can choose to "force it" to try printing anyway.

	 * <p/>

	 * This hack gets around annoying 'Printer is not accepting job' errors in Java 5/6 that

	 * don't occur in Java 1.4.  This was enough of a problem for our 1000+ users that it

	 * was the sole reason we could not move the product up from Java 1.4.  Hence, the hack

	 * was invented as we had the problem with users whose printers were clearly online and

	 * they could print from any non-Java application.

	 * <p/>

	 * Turns out this hack is also useful for printing to the latest inkjet printers that

	 * have chips in the cartridges and stay in a 'No ink' status  once empty.  This is

	 * presumably to cause an inconvenience for cartridge refillers, but we're the ones who

	 * get the support calls from users that printing is not working, so it's an inconvenience

	 * to everyone except the printer manufacturer.

	 * <p/>

	 * Usage:

	 * <code>

	 *		 // Get a printer, create a print job, and try printing however you do it today

	 *		 PrintService printer = getPrinter(myFormat, aset);

	 *		 DocPrintJob job = printer.createPrintJob();

	 *		 try {

	 *			 job.print(myDoc, aset);

	 *		 } catch (PrintException pe) {         // catch the PrintException

	 *           // check for the annoying 'Printer is not accepting job' error.

	 *			 if (pe.getMessage().indexOf("accepting job") != -1) {

	 *               // recommend prompting the user at this point if they want to force it

	 *               // so they'll know there may be a problem.

	 *				 try {

	 *				     // try printing again but ignore the not-accepting-jobs attribute

	 *                   job = printer.createPrintJob();

	 *					 ForcedAcceptPrintService.setupPrintJob(job); // add secret ingredient

	 *					 job.print(myDoc, aset);

	 *				 } catch (PrintException e) {

	 *					 // ok, you really can't print

	 *					 e.printStackTrace();

	 *				 }

	 *			 } else {

	 *				 // some other printing error

	 *				 pe.printStackTrace();

	 *			 }

	 *		 }

	 * </code>

	 */

	private static class ForcedAcceptPrintService implements PrintService {

		private final DocPrintJob thePrintJob;

		private final PrintService delegate;

		private Field printServiceFieldReference = null;

 

		/**

		 * Tweak the DocPrintJob to think this class is it's PrintService, long enough to

		 * override the PrinterIsAcceptingJobs attribute.  If it doesn't work out or

		 * the printer really is offline then it's no worse than if this hack was not

		 * used.

		 *

		 * @param printJob the print job to affect

		 */

		public static void setupPrintJob(DocPrintJob printJob) {

			new ForcedAcceptPrintService(printJob);

		}

 

		/**

		 * Private constructor as this only works as a one-shot per print attempt.

		 * Use the static method above to hack a DocPrintJob, then tell it to print.

		 * The hack is gone by the time printing occurs and this instance will be

		 * garbage collected due to having no other references once the DocPrintJob

		 * is back to its original state.

		 *

		 * @param printJob the print job to affect

		 */

		private ForcedAcceptPrintService(DocPrintJob printJob) {

			this.thePrintJob = printJob;

			this.delegate = printJob.getPrintService();

 

			try {

				// replace the private PrintService field on the DocPrintJob instance with a reference

				// to our replacement PrintService so that we can intercept calls to getAttributes().

				// it is expected that the first thing the DocPrintJob will do is check it's PrintService's

				// PrinterIsAcceptingJobs attribute, at which point we'll force it to think it is accepting

				// jobs and restore the PrintService to the original instance to get out of the way.

				// The only real requirement is that the DocPrintJob does not cast the PrintService

				// to it's expected type until after it has checked the PrinterIsAcceptingJobs

				// attribute.

				Class pjClass = thePrintJob.getClass();

				Field[] fields = pjClass.getDeclaredFields();

				for (int i=0; i<fields.length; i++) {

					if (fields[i].getType().equals(PrintService.class)) {

						printServiceFieldReference = fields[i];

						printServiceFieldReference.setAccessible(true);

						// if the next line errors then the hack just isn't in place and printing

						// proceeds as it normally would (e.g. no side effects).

						printServiceFieldReference.set(thePrintJob, this);

						// there should be only one, so break once found

						break;

					}

				}

			} catch (IllegalAccessException e) {

				e.printStackTrace();

			}

		}

 

		/** Restore the DocPrintJob's PrintService to what it was originally. */

		private void restoreServiceReference() {

			try {

				// replace the private PrintService field on the DocPrintJob instance with a

				// reference to the original PrintService so that we stop intercepting calls

				// and won't cause ClassCastExceptions as printing proceeds.

				if (printServiceFieldReference != null)

					printServiceFieldReference.set(thePrintJob, delegate);

			} catch (IllegalAccessException e) {

				e.printStackTrace();

			}

		}

 

		/**

		 * getAttribute is the one PrintService method we want to intercept to override the

		 * PrinterIsAcceptingJobs attribute.

		 */

		public PrintServiceAttribute getAttribute(Class category) {

			if (category.equals(PrinterIsAcceptingJobs.class)) {

				// once we've overridden the return value for the PrinterIsAcceptingJobs attribute we're done.

				// put the DocPrintJob's PrintService back to what it was.

				restoreServiceReference();

				return PrinterIsAcceptingJobs.ACCEPTING_JOBS;

			}

			return delegate.getAttribute(category);

		}

 

		// obligatory PrintService implementation

 

		public DocPrintJob createPrintJob() {

			return delegate.createPrintJob();

		}

 

		public void addPrintServiceAttributeListener(PrintServiceAttributeListener listener) {

			delegate.addPrintServiceAttributeListener(listener);

		}

 

		public PrintServiceAttributeSet getAttributes() {

			return delegate.getAttributes();

		}

 

		public Object getDefaultAttributeValue(Class category) {

			return delegate.getDefaultAttributeValue(category);

		}

 

		public String getName() {

			return delegate.getName();

		}

 

		public ServiceUIFactory getServiceUIFactory() {

			return delegate.getServiceUIFactory();

		}

 

		public Class[] getSupportedAttributeCategories() {

			return delegate.getSupportedAttributeCategories();

		}

 

		public Object getSupportedAttributeValues(Class category, DocFlavor flavor, AttributeSet attributes) {

			return delegate.getSupportedAttributeValues(category, flavor, attributes);

		}

 

		public DocFlavor[] getSupportedDocFlavors() {

			return delegate.getSupportedDocFlavors();

		}

 

		public AttributeSet getUnsupportedAttributes(DocFlavor flavor, AttributeSet attributes) {

			return delegate.getUnsupportedAttributes(flavor, attributes);

		}

 

		public boolean isAttributeCategorySupported(Class category) {

			return delegate.isAttributeCategorySupported(category);

		}

 

		public boolean isAttributeValueSupported(Attribute attrval, DocFlavor flavor, AttributeSet attributes) {

			return delegate.isAttributeValueSupported(attrval, flavor, attributes);

		}

 

		public boolean isDocFlavorSupported(DocFlavor flavor) {

			return delegate.isDocFlavorSupported(flavor);

		}

 

		public void removePrintServiceAttributeListener(PrintServiceAttributeListener listener) {

			delegate.removePrintServiceAttributeListener(listener);

		}

	}

Open in new window

0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 20

Expert Comment

by:Venabili
Comment Utility
There used to be a bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4886069 but it was fixed long ago.

And do you try for Legal Paper or for A5? And can you make sure that the sizes are correct (print them and compare)?
0
 

Author Comment

by:shukla1_alok
Comment Utility
The dimension of the page are 8.5(Width) 14 (Height) in inches.
The page printing is fine on the Printer, now the problem is the Formatting of the Page is not right.

Following things I have done to define the Layout of the Page which used to work with JDK1.4
In the Code snippet section I have provided the details

Seems now due the Underlying the JDK Change the logic of translating the Logical Page into Physical Page is not working correctly in the Method paintPane(Graphics graphics, PageFormat pf)

Thanks,
Alok

//To Define the Layout of the Page.

public void layoutPage() {

	m_pageFormat = new PageFormat();

	Paper p = m_pageFormat.getPaper();

	double width = 8.5 * PIXELS_PER_INCH;

	double height = 14.0 * PIXELS_PER_INCH;

	double ix = PIXELS_PER_INCH / 2.0;

	double iy = PIXELS_PER_INCH / 2.0;

	double iwidth = width - PIXELS_PER_INCH;

	double iheight = height - PIXELS_PER_INCH;

	p.setSize(width, height);

	p.setImageableArea(ix, iy, iwidth, iheight);

	m_pageFormat.setPaper(p);

}
 

//This class implements the Printable Interface.

//Implementation

protected void paintPane(Graphics graphics, PageFormat pf) {

double hScale = Math.min(1, pf.getImageableWidth() / m_pane.getSize().getWidth());
 

double vScale = Math.min(1, pf.getImageableHeight() / m_pane.getSize().getHeight());
 

double scale = Math.min(hScale, vScale);

Graphics2D g2d = (Graphics2D) graphics;

g2d.translate(pf.getImageableX(), pf.getImageableY());

g2d.scale(scale, scale);

boolean wasBuffered = m_pane.isDoubleBuffered();

m_pane.paint(g2d);

m_pane.setDoubleBuffered(wasBuffered);

}
 

//The actual Invocation for Printing Request is here

protected void printConfirmation() {

	PrintRequestAttributeSet aset = new  HashPrintRequestAttributeSet();

	

aset.add(MediaSizeName.ISO_A5);

	PrintService defaultPrinter = PrintServiceLookup.lookupDefaultPrintService();

	

DocPrintJob printJob = defaultPrinter.createPrintJob();
 

Doc confirmationDoc = null;

	try {

		confirmationDoc = new SimpleDoc(this, DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);

		

	printJob.print(confirmationDoc, aset);

	} catch (PrintException pe) {

		// check for the annoying 'Printer is not accepting job' error.

	if (pe.getMessage().indexOf("accepting job") != -1) {

		// recommend prompting the user at this point if they want to force it

		// so they'll know there may be a problem.

		try {

			// try printing again but ignore the not-accepting-jobs attribute

			printJob = defaultPrinter.createPrintJob();

					ForcedAcceptPrintService.setupPrintJob(printJob); // add secret ingredient

			printJob.print(confirmationDoc, aset);

		} catch (PrintException e) {

			Logger.error("Error printing.");

			Logger.error(pe.getMessage(), pe);

					JOptionPane.showMessageDialog(this, " Error Prinitng " + pe.getMessage());

		}

	} else {

		Logger.error("Error printing.");

		Logger.error(pe.getMessage(), pe);

		JOptionPane.showMessageDialog(this, " Error Prinitng " + pe.getMessage());

		}

	}

}
 
 

	public int print(Graphics graphics, PageFormat pf, int pageIndex) {

		if (pageIndex > 0) {

			return Printable.NO_SUCH_PAGE;

		}

		paintPane(graphics, pf);

		return Printable.PAGE_EXISTS;

	}

Open in new window

0
 
LVL 20

Expert Comment

by:Venabili
Comment Utility
That's why I asked you if you print the values you can see the proper values.
Print all the values inside the method and make sure none is off (m_pane sizes, pf Imageable sizes) and so on
If you try to print on another paper, does it behave in the same way?
0
 

Author Comment

by:shukla1_alok
Comment Utility
What is surprising is the PaneSize, PageFormat Size are different

DEBUG 2009-03-31 12:37:51,096 (root) - Pane Size --> Widht : 616.0 Hieght : 1470.0
DEBUG 2009-03-31 12:37:51,096 (root) - In Terms of Dimension Object for Pane --> java.awt.Dimension[width=616,height=1470]
DEBUG 2009-03-31 12:37:51,096 (root) - Factor by which the Graphics would get Translated Sacle : 0.636734693877551
DEBUG 2009-03-31 12:37:51,096 (root) - Paper Dimensions for Page Format(Imageable) --> Width : 540.0 Height : 936.0
DEBUG 2009-03-31 12:37:51,096 (root) - Paper Dimensions for Page Format --> Width : 36.0 Height : 36.0

How I can make sure irrespective of what is the Size of the Page I should always print in terms of my Logical Page Format Only
0
 

Accepted Solution

by:
shukla1_alok earned 0 total points
Comment Utility
How I can make sure irrespective of what is the Size of the Page I should always print in terms of my Logical Page Format Only. No matter what is the size of the window the page should always be printed in A5 Size
0
 

Author Comment

by:shukla1_alok
Comment Utility
Only one query remains as follows

How I can make sure irrespective of what is the Size of the Page I should always print in terms of my Logical Page Format Only. No matter what is the size of the window the page should always be printed in A5 Size

Thanks for you r timely help
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This video teaches viewers about errors in exception handling.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now