aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Print Preview in Java swing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Print Preview in Java swing " Watch "Print Preview in Java swing " New topic
Author

Print Preview in Java swing

Deepak Deepak
Greenhorn

Joined: Jan 15, 2003
Posts: 2
Dear Friends
I have made Application for Image processing Using swing API, I have one of the module in that Print Images with Print Previewe,
Searching through Internet I have found ready made API specifically made for Java Printing with print preview that is PFDocument
http://www.javaworld.com/javaworld/jw-03-2001/jw-0302-print-p2.html
My problem is that
1) I am receiving Dark Black Square instead of Image on a Page why?
I can see Image properly in print preview screen. But that image not coming on page,
2) How can add more than one image for print preview.
3) Also I like to print Image 1 image on single page,2 Image on single page ,4 Image on single page, 6 Image on single page like that how can I do that.
Please give me suggestion or example or code for above given problems
import com.infocom.print.*;
import java.awt.*;
import java.awt.print.*;
import java.net.*;
import java.awt.Image;
public class CreatePreview extends PFPrintObject implements Printable
{
private PFDocument pdf=null;
private PFPage pfp=null;
private PFPageFormat pfformat=null;
private PFImage pfImage=null;
private PFCmUnit pfcu=null;
private static Graphics g = null;
private static PageFormat pft = null;
private PFFrame pfFrame=null;
public CreatePreview(){
pdf = new PFDocument();
pfformat= new PFPageFormat();
pfcu = new PFCmUnit();
pfp = new PFPage();
pfImage = new PFImage();
pfFrame=new PFFrame();
}
public void setPrintPreview()
{
try{

pdf.setDocumentName("First Docuement Print");
pfformat.setGutter(pfcu);
pfformat.setPageOrientation(PFPageFormat.PORTRAIT);
pfformat.setPageSize(80);

PFUnit pageUnit = new PFCmUnit(5);
PFUnit pageUnit1 = new PFCmUnit(5);
pfImage.setHeight(pageUnit);
pfImage.setWidth(pageUnit1);
pfp.setPageFormat(pfformat);
pfImage.setURL("file:///c:/asp/CRANE.JPG");
pfp.add(pfImage);
pdf.addPage(pfp);
pdf.showPageDialog(true);
pdf.showPrintDialog(true);
pdf.printPreview();

}catch(Exception e){System.out.println("Exception in set priview->"+e);}
}
public void print(Graphics2D parg)
{

parg.draw3DRect(10,50,50,50,true);

}

public int print(java.awt.Graphics g,java.awt.print.PageFormat p2,int p3) throws java.awt.print.PrinterException
{
System.out.println("Print method with java.awt.print.PageFormat has been called ");
Graphics2D g2 = (Graphics2D) g;
if(p3==0)
{
String s ="Hello";
g2.setPaint(Color.black);
g2.translate(p2.getImageableX(),p2.getImageableY());
g2.drawString(s,50,50);
return (PAGE_EXISTS);
}else{
return (NO_SUCH_PAGE);
}
}
public static void main(String args[])
{
CreatePreview CP = new CreatePreview();
CP.setPrintPreview();
}

}
Pondy Prem
Greenhorn

Joined: Oct 28, 2001
Posts: 11
For all the manipulations that you are mentioning you have to do the page length/width calculations..
Also regarding the size of image... try adding the images in their own JPanel .. before placing it on the global JPanel.


<a href="mailto:pondyprem@yahoo.com" rel="nofollow">pondyprem@yahoo.com</a>
Pondy Prem
Greenhorn

Joined: Oct 28, 2001
Posts: 11
This one may be useful:

import java.awt.*;
import javax.swing.*;
import java.awt.print.*;
/** A simple utility class that lets you very simply print
* an arbitrary component. Just pass the component to the
* PrintUtilities.printComponent. The component you want to
* print doesn't need a print method and doesn't have to
* implement any interface or do anything special at all.
* <P>
* If you are going to be printing many times, it is marginally more
* efficient to first do the following:
* <PRE>
* PrintUtilities printHelper = new PrintUtilities(theComponent);
* </PRE>
* then later do printHelper.print(). But this is a very tiny
* difference, so in most cases just do the simpler
* PrintUtilities.printComponent(componentToBePrinted).
*
* 7/99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
* May be freely used or adapted.
*/
public class PrintUtilities implements Printable {
private Component componentToBePrinted;
public static void printComponent(Component c) {
new PrintUtilities(c).print();
}

public PrintUtilities(Component componentToBePrinted) {
this.componentToBePrinted = componentToBePrinted;
}

public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
disableDoubleBuffering(componentToBePrinted);
componentToBePrinted.paint(g2d);
enableDoubleBuffering(componentToBePrinted);
return(PAGE_EXISTS);
}
}
/** The speed and quality of printing suffers dramatically if
* any of the containers have double buffering turned on.
* So this turns if off globally.
* @see enableDoubleBuffering
*/
public static void disableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
}
/** Re-enables double buffering globally. */

public static void enableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);
}
}
Pondy Prem
Greenhorn

Joined: Oct 28, 2001
Posts: 11
I copied this source from somwhre in net and finetuned...
It may be of use :
public class PrintPreview extends JDialog{
protected int m_wPage;
protected int m_hPage;

protected Printable m_target;
protected JComboBox m_cbScale;
protected PreviewContainer m_preview;

//protected PrintUtilities the_PrintUtilities;

public PrintPreview(JDialog parentJDialog, Printable target){
this(parentJDialog, target, "Print Preview");
}// C1 ends

public PrintPreview(JDialog parentJDialog,Printable target, String title){
super(parentJDialog, title);
setSize(800,600);
setModal(true);
this.setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);

JToolBar tb = new JToolBar();
JButton bt = new JButton("Print", new ImageIcon("print.gif"));

ActionListener lst = new ActionListener(){
public void actionPerformed(ActionEvent e){
}
};

bt.addActionListener(lst);
bt.setAlignmentY(0.5f);
bt.setMargin(new Insets(4,6,4,6));
//tb.add(bt);

bt = new JButton("Close");
lst = new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
}
};

bt.addActionListener(lst);
bt.setAlignmentY(0.5f);
bt.setMargin(new Insets(2,6,2,6));
tb.add(bt);

String [] scales = {"10", "25", "50", "100" };

m_cbScale = new JComboBox(scales);

lst = new ActionListener(){
public void actionPerformed(ActionEvent e){
Thread runner = new Thread(){
public void run(){
String str = m_cbScale.getSelectedItem().toString();
System.out.println("m_cbScale: " + str);
if(str.endsWith("%")){
str.substring(0, str.length()-1);
}
str.trim();
int scale = 0;

try{
scale = Integer.parseInt(str);
}
catch(NumberFormatException ex){
System.out.println("scale: " + scale);
return;
}

int w = (int) (m_wPage*scale/100);
int h = (int) (m_hPage*scale/100);

Component [] comps = m_preview.getComponents();

for(int k=0; k<comps.length; k++){
if(!( comps[k] instanceof PagePreview)) {
continue;
}

PagePreview pp = (PagePreview) comps[k];
pp.setScaledSize(w,h);
}// for() ends
m_preview.doLayout();
m_preview.getParent().getParent().validate();

}// run() ends
};// Thread ends

runner.start();
}
};// ActionListener ends

m_cbScale.addActionListener(lst);
m_cbScale.setMaximumSize(m_cbScale.getPreferredSize());
m_cbScale.setEditable(true);
tb.addSeparator();
tb.add(m_cbScale);

getContentPane().add(tb, BorderLayout.NORTH);

m_preview = new PreviewContainer();

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

if(pageFormat.getHeight() ==0 ||pageFormat.getWidth() ==0 ){
//error
return ;
}
m_wPage = (int)(pageFormat.getWidth());
m_hPage = (int)(pageFormat.getHeight());

int scale = 50;

int w = (int)(m_wPage*scale/100);
int h = (int)(m_hPage*scale/100);

int pageIndex = 0;

try{
while(true){
BufferedImage img = new BufferedImage(m_wPage,m_hPage, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.setColor(Color.white);
g.fillRect(0,0,m_wPage, m_hPage);
if( target.print(g, pageFormat, pageIndex) != Printable.PAGE_EXISTS){
break;
}
PagePreview pp = new PagePreview(w,h, img);
m_preview.add(pp);
pageIndex++;

}
}catch(PrinterException pe){
pe.printStackTrace();
}

JScrollPane ps = new JScrollPane(m_preview);
getContentPane().add(ps, BorderLayout.CENTER);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}// C2 ends



}// class PrintPreview ends
class PreviewContainer extends JPanel{
protected int H_GAP = 16;
protected int V_GAP = 10;

public Dimension getPreferredSize(){
int n = getComponentCount();

if(n == 0){ return new Dimension(H_GAP, V_GAP);}
Component comp = getComponent(0);
Dimension dc = comp.getPreferredSize();

int w = dc.width;
int h = dc.height;

Dimension dp = getParent().getSize();
int nCol = Math.max( (dp.width-H_GAP)/(w+H_GAP) , 1 );
int nRow = n/nCol;

if(nRow*nCol < n) nRow++;

int ww = nCol*(w+H_GAP) + H_GAP ;
int hh = nRow*(h+V_GAP) + V_GAP ;

Insets ins = getInsets();
return new Dimension(ww+ins.left+ins.right,
hh+ ins.top+ins.bottom);
}// getPreferredSize()ends

public Dimension getMaximumSize(){
return getPreferredSize();
}
public Dimension getMinimumSize(){
return getPreferredSize();
}

public void doLayout(){
Insets ins = getInsets();

int x = ins.left + H_GAP;
int y = ins.top + V_GAP;

int n = getComponentCount();

if(n==0) return;

Component comp = getComponent(0);
Dimension dc = comp.getPreferredSize();
int w = dc.width;
int h = dc.height;

Dimension dp = getParent().getSize();
int nCol = Math.max( (dp.width-H_GAP)/(w+V_GAP) ,1 );
int nRow = n/nCol;

if(nRow*nCol < n) nRow++;

int index = 0;
for(int k=0; k<nRow; k++){
for(int m=0; m<nCol; m++){
if(index >=n ) return;
comp = getComponent(index++);
comp.setBounds(x,y,w,h);
x += w+ H_GAP;
}//for(m.) ends
y += h+V_GAP;
x = ins.left + H_GAP;
}// for(k) ends

}// doLayout() ends

}// class PreviewContainer ends
class PagePreview extends JPanel{
protected int m_w;
protected int m_h;
protected Image m_source;
protected Image m_img;

public PagePreview(int w, int h, Image source){
m_w = w;
m_h = h;

m_source = source;
m_img = m_source.getScaledInstance(m_w, m_h, Image.SCALE_SMOOTH);
m_img.flush();
setBackground(Color.white);
setBorder(new MatteBorder(1,1,2,2,Color.black));
}//PagePreview ends

public void setScaledSize(int w , int h){
m_w = w;
m_h = h;
m_img = m_source.getScaledInstance(m_w, m_h, Image.SCALE_SMOOTH);
repaint();
}//void setScaledSize() ends

public Dimension getPreferredSize(){
Insets ins = getInsets();
return new Dimension(m_w+ins.left+ins.right,
m_h+ins.top + ins.bottom);
}

public Dimension getMaximumSize(){
return getPreferredSize();
}
public Dimension getMinimumSize(){
return getPreferredSize();
}

public void paint(Graphics g){
g.setColor(getBackground());
g.fillRect(0,0, getWidth(), getHeight());
g.drawImage(m_img, 0, 0, this);
paintBorder(g);
}
}//class PagePreview ends
************************ useage **************
public void showPreview(JDialog parentJDialog){
new PrintPreview(parentJDialog, PrintUtilities.this, "MyPage- preview") ;
}
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Print Preview in Java swing